mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(ecs): preserve binary output in exec sessions (#5621)
This commit is contained in:
1 parent
4d6ecc1ac2
commit
9f224e5760
6 files changed
+231
-11
No files matched your search
@@ -379,7 +379,9 @@ aws ecs execute-command --cluster my-cluster --task <task-arn> \
|
||||
|
||||
Floci plays the SSM agent's half of the Session Manager protocol on that channel (the binary
|
||||
`AgentMessage` framing, the handshake, sequenced acknowledgements and terminal resizes) and bridges
|
||||
it to a `docker exec` in the container. Deliberate limits:
|
||||
it to a `docker exec` in the container. Output is forwarded as bytes, including leading control
|
||||
bytes and invalid UTF-8, without interpreting the process's PTY output as Docker multiplexed headers.
|
||||
Deliberate limits:
|
||||
|
||||
- The session runs as root (uid 0) whatever the container definition's `user`, as the real ECS Exec
|
||||
agent does.
|
||||
|
||||
+26
-3
@@ -7,6 +7,8 @@
|
||||
*/
|
||||
package io.github.hectorvent.floci.core.common.docker;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.github.dockerjava.transport.DockerHttpClient;
|
||||
import com.github.dockerjava.transport.NamedPipeSocket;
|
||||
import com.github.dockerjava.transport.SSLConfig;
|
||||
@@ -71,6 +73,8 @@ import java.util.stream.Stream;
|
||||
*/
|
||||
public final class FlociDockerHttpClient implements DockerHttpClient {
|
||||
|
||||
private static final ObjectMapper EXEC_CONFIG_MAPPER = new ObjectMapper();
|
||||
|
||||
/**
|
||||
* A pooled connection idle this long is checked before it is leased again, so a socket the daemon
|
||||
* (or Podman) already closed is replaced instead of failing on its next write. The check reads with
|
||||
@@ -196,8 +200,9 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
|
||||
}
|
||||
|
||||
try {
|
||||
boolean ttyExec = isTtyExec(request);
|
||||
ClassicHttpResponse response = httpClient.executeOpen(host, httpRequest, context);
|
||||
return new FlociResponse(httpRequest, response);
|
||||
return new FlociResponse(httpRequest, response, ttyExec && response.getCode() == 200);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
@@ -208,6 +213,16 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
|
||||
httpClient.close();
|
||||
}
|
||||
|
||||
private static boolean isTtyExec(Request request) throws IOException {
|
||||
String route = request.path().split("\\?", 2)[0];
|
||||
if (!"POST".equals(request.method()) || !route.contains("/exec/") || !route.endsWith("/start")
|
||||
|| request.bodyBytes() == null) {
|
||||
return false;
|
||||
}
|
||||
JsonNode config = EXEC_CONFIG_MAPPER.readTree(request.bodyBytes());
|
||||
return config != null && config.path("Tty").asBoolean() && !config.path("Detach").asBoolean();
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests whose response is a stream that stays open, and may stay silent, for as long as what it
|
||||
* follows: a container wait, exec and attach output, followed logs, streamed stats, daemon events,
|
||||
@@ -302,10 +317,13 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
|
||||
|
||||
private final HttpUriRequestBase request;
|
||||
private final ClassicHttpResponse response;
|
||||
private final boolean ttyExec;
|
||||
private InputStream body;
|
||||
|
||||
FlociResponse(HttpUriRequestBase request, ClassicHttpResponse response) {
|
||||
FlociResponse(HttpUriRequestBase request, ClassicHttpResponse response, boolean ttyExec) {
|
||||
this.request = request;
|
||||
this.response = response;
|
||||
this.ttyExec = ttyExec;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -329,7 +347,12 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
|
||||
@Override
|
||||
public InputStream getBody() {
|
||||
try {
|
||||
return response.getEntity() != null ? response.getEntity().getContent() : EmptyInputStream.INSTANCE;
|
||||
if (body == null) {
|
||||
InputStream content = response.getEntity() != null
|
||||
? response.getEntity().getContent() : EmptyInputStream.INSTANCE;
|
||||
body = ttyExec ? new TtyFramingInputStream(content) : content;
|
||||
}
|
||||
return body;
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package io.github.hectorvent.floci.core.common.docker;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Frames raw PTY chunks for docker-java 3.7.1, whose decoder mistakes leading 0, 1, or 2 for a header.
|
||||
* The decoder removes these synthetic headers before delivering the original bytes to its callback.
|
||||
*
|
||||
* @see <a href="https://github.com/docker-java/docker-java/blob/3.7.1/docker-java-core/src/main/java/com/github/dockerjava/core/FramedInputStreamConsumer.java">docker-java's decoder</a>
|
||||
*/
|
||||
final class TtyFramingInputStream extends InputStream {
|
||||
|
||||
private final InputStream input;
|
||||
private final byte[] frame = new byte[8 + 1024];
|
||||
private int position;
|
||||
private int limit;
|
||||
|
||||
TtyFramingInputStream(InputStream input) {
|
||||
this.input = input;
|
||||
frame[0] = 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
if (position == limit && !nextFrame()) {
|
||||
return -1;
|
||||
}
|
||||
return frame[position++] & 0xff;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(byte[] bytes, int offset, int length) throws IOException {
|
||||
Objects.checkFromIndexSize(offset, length, bytes.length);
|
||||
if (length == 0) {
|
||||
return 0;
|
||||
}
|
||||
if (position == limit && !nextFrame()) {
|
||||
return -1;
|
||||
}
|
||||
int count = Math.min(length, limit - position);
|
||||
System.arraycopy(frame, position, bytes, offset, count);
|
||||
position += count;
|
||||
return count;
|
||||
}
|
||||
|
||||
private boolean nextFrame() throws IOException {
|
||||
int count = input.read(frame, 8, frame.length - 8);
|
||||
if (count < 0) {
|
||||
return false;
|
||||
}
|
||||
ByteBuffer.wrap(frame, 4, 4).putInt(count);
|
||||
position = 0;
|
||||
limit = 8 + count;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
input.close();
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -419,7 +419,8 @@ public class EcsExecChannelHandler {
|
||||
public void onNext(Frame frame) {
|
||||
byte[] payload = frame.getPayload();
|
||||
if (payload != null && payload.length > 0) {
|
||||
channel.sendOutput(payload);
|
||||
// docker-java reuses full-size buffers before the queued context write runs.
|
||||
channel.sendOutput(payload.clone());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package io.github.hectorvent.floci.core.common.docker;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.exception.DockerException;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import com.github.dockerjava.core.DefaultDockerClientConfig;
|
||||
import com.github.dockerjava.core.DockerClientImpl;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class DockerExecTtyStreamTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {0, 1, 2, 3, 15, 23, 31, 120, 255})
|
||||
void ttyExecPreservesLeadingBytesThroughDockerJava(int leadingByte) throws Exception {
|
||||
byte[] marker = "ABCDEFGH\n__TCR_EXIT_test=0\n".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] payload = new byte[marker.length + 3];
|
||||
payload[0] = (byte) leadingByte;
|
||||
payload[1] = (byte) 0xff;
|
||||
payload[2] = (byte) 0xfe;
|
||||
System.arraycopy(marker, 0, payload, 3, marker.length);
|
||||
assertArrayEquals(payload, execute(payload, true, 200));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {0, 1, 2, 7, 8, 1024, 1025, 8193})
|
||||
void ttyExecPreservesEmptyShortAndMultiFrameOutput(int length) throws Exception {
|
||||
byte[] payload = new byte[length];
|
||||
for (int i = 0; i < length; i++) {
|
||||
payload[i] = (byte) i;
|
||||
}
|
||||
assertArrayEquals(payload, execute(payload, true, 200));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonTtyExecStillDecodesDaemonFrames() throws Exception {
|
||||
byte[] stdout = {0, 1, 2, (byte) 0xff};
|
||||
byte[] stderr = {'e'};
|
||||
ByteBuffer wire = ByteBuffer.allocate(16 + stdout.length + stderr.length);
|
||||
wire.put(new byte[]{1, 0, 0, 0}).putInt(stdout.length).put(stdout);
|
||||
wire.put(new byte[]{2, 0, 0, 0}).putInt(stderr.length).put(stderr);
|
||||
assertArrayEquals(new byte[]{0, 1, 2, (byte) 0xff, 'e'}, execute(wire.array(), false, 200));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {400, 404})
|
||||
void ttyExecKeepsDockerErrorResponsesReadable(int status) {
|
||||
byte[] error = "{\"message\":\"missing exec\"}".getBytes(StandardCharsets.UTF_8);
|
||||
DockerException failure = assertThrows(DockerException.class, () -> execute(error, true, status));
|
||||
assertTrue(failure.getMessage().contains("missing exec"));
|
||||
}
|
||||
|
||||
private static byte[] execute(byte[] payload, boolean tty, int status) throws Exception {
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/v1.45/exec/test/start", exchange -> {
|
||||
exchange.getRequestBody().readAllBytes();
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/vnd.docker.raw-stream");
|
||||
exchange.sendResponseHeaders(status, payload.length);
|
||||
try (exchange) {
|
||||
exchange.getResponseBody().write(payload);
|
||||
}
|
||||
});
|
||||
server.start();
|
||||
URI host = URI.create("tcp://127.0.0.1:" + server.getAddress().getPort());
|
||||
try (FlociDockerHttpClient transport = new FlociDockerHttpClient.Builder()
|
||||
.dockerHost(host).responseTimeout(Duration.ofSeconds(5)).build();
|
||||
DockerClient client = DockerClientImpl.getInstance(DefaultDockerClientConfig.createDefaultConfigBuilder()
|
||||
.withDockerHost(host.toString()).withApiVersion("1.45").build(), transport)) {
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
ResultCallback.Adapter<Frame> callback = new ResultCallback.Adapter<>() {
|
||||
@Override
|
||||
public void onNext(Frame frame) {
|
||||
output.writeBytes(frame.getPayload());
|
||||
}
|
||||
};
|
||||
client.execStartCmd("test").withTty(tty).exec(callback);
|
||||
assertTrue(callback.awaitCompletion(10, TimeUnit.SECONDS));
|
||||
return output.toByteArray();
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
-6
@@ -17,7 +17,10 @@ import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
@@ -25,6 +28,7 @@ import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -62,8 +66,9 @@ class EcsExecChannelDockerIntegrationTest {
|
||||
"Docker daemon must be available for the ECS Exec channel test");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClientDrivingTheProtocolGetsTheCommandsOutput() throws Exception {
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void aClientDrivingTheProtocolGetsTheCommandsOutput(boolean interactive) throws Exception {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
ContainerDefinition app = new ContainerDefinition();
|
||||
app.setName("app");
|
||||
@@ -89,7 +94,8 @@ class EcsExecChannelDockerIntegrationTest {
|
||||
ExecSession session = sessions.create(task.getTaskArn(),
|
||||
"arn:aws:ecs:us-east-1:000000000000:cluster/exec-cluster", "app",
|
||||
"arn:aws:ecs:us-east-1:000000000000:container/exec/app", runtimeId,
|
||||
List.of("/bin/sh", "-c", "echo exec-channel-ok"), false);
|
||||
List.of("/bin/sh", "-c", "printf '\\000\\001\\002\\003\\377\\376'; "
|
||||
+ "head -c 5000 /dev/zero; printf 'exec-channel-ok'"), interactive);
|
||||
|
||||
PluginClient client = new PluginClient(vertx, session);
|
||||
try {
|
||||
@@ -104,9 +110,16 @@ class EcsExecChannelDockerIntegrationTest {
|
||||
|
||||
client.sendHandshakeResponse();
|
||||
|
||||
String output = client.readUntil("exec-channel-ok");
|
||||
assertTrue(output.contains("exec-channel-ok"),
|
||||
"the command's output must reach the channel, got: " + output);
|
||||
byte[] suffixBytes = "exec-channel-ok".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] expected = new byte[6 + 5000 + suffixBytes.length];
|
||||
expected[1] = 1;
|
||||
expected[2] = 2;
|
||||
expected[3] = 3;
|
||||
expected[4] = (byte) 0xff;
|
||||
expected[5] = (byte) 0xfe;
|
||||
System.arraycopy(suffixBytes, 0, expected, 5006, suffixBytes.length);
|
||||
assertArrayEquals(expected, client.readOutput(),
|
||||
"binary output must survive Docker decoding and asynchronous channel writes");
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
@@ -220,6 +233,25 @@ class EcsExecChannelDockerIntegrationTest {
|
||||
return message;
|
||||
}
|
||||
|
||||
byte[] readOutput() throws InterruptedException {
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
|
||||
while (System.nanoTime() < deadline) {
|
||||
AgentMessage message = received.poll(1, TimeUnit.SECONDS);
|
||||
if (message == null) {
|
||||
continue;
|
||||
}
|
||||
if (AgentMessage.CHANNEL_CLOSED.equals(message.messageType())) {
|
||||
return output.toByteArray();
|
||||
}
|
||||
if (AgentMessage.OUTPUT_STREAM_DATA.equals(message.messageType())
|
||||
&& message.payloadType() == AgentMessage.PAYLOAD_OUTPUT) {
|
||||
output.writeBytes(message.payload());
|
||||
}
|
||||
}
|
||||
throw new AssertionError("the command must finish and close its channel");
|
||||
}
|
||||
|
||||
/** Collects output frames until the expected text shows up or the channel goes quiet. */
|
||||
String readUntil(String expected) throws InterruptedException {
|
||||
StringBuilder output = new StringBuilder();
|
||||
|
||||
Reference in new issue
Block a user