fix(ssm): bound direct-execution output to the GetCommandInvocation limits (#4257)

The direct executor buffered a command's full stdout and stderr in memory
until the command finished, and only then truncated them to 24,000 and
8,000 characters.

Collect each stream with a bounded collector that keeps the first N
characters, keeps draining the Docker stream after the cap, decodes UTF-8
characters split across frames, and never ends on half a surrogate pair.
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-09-23 18:18:37 -04:00
1 parent ed627a6ce7
commit 1027f0a602
5 files changed
+263 -27

No files matched your search

@@ -0,0 +1,82 @@
package io.github.hectorvent.floci.services.ssm;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
/**
* Accumulates UTF-8 bytes into a character buffer bounded to a maximum number of characters.
* Bytes received after the cap is reached are decoded and discarded rather than retained, so
* memory stays proportional to {@code maxChars} regardless of how much input is fed in.
*
* <p>Handles a multi-byte UTF-8 character split across separate {@link #write(byte[])} calls
* (e.g. Docker exec stream frames) by carrying any undecoded trailing bytes over to the next
* call instead of corrupting or dropping the character.
*
* <p>Thread-safe: Docker callback threads write while the executor thread may read after a timeout.
*/
final class BoundedOutputCollector {
private static final byte[] NO_BYTES = new byte[0];
private final int maxChars;
private final StringBuilder captured;
private final CharsetDecoder decoder;
private byte[] pending = NO_BYTES;
private boolean capped;
BoundedOutputCollector(int maxChars) {
if (maxChars < 0) {
throw new IllegalArgumentException("maxChars must be >= 0");
}
this.maxChars = maxChars;
this.captured = new StringBuilder(Math.min(maxChars, 4096));
this.decoder = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE);
this.capped = maxChars == 0;
}
synchronized void write(byte[] payload) {
if (payload == null || payload.length == 0 || capped) {
return;
}
byte[] combined = pending.length == 0 ? payload : concat(pending, payload);
ByteBuffer in = ByteBuffer.wrap(combined);
CharBuffer out = CharBuffer.allocate(combined.length + 1);
decoder.decode(in, out, false);
out.flip();
int remaining = maxChars - captured.length();
if (out.length() >= remaining) {
if (remaining > 0 && Character.isHighSurrogate(out.charAt(remaining - 1))) {
remaining--;
}
captured.append(out, 0, remaining);
capped = true;
pending = NO_BYTES;
return;
}
captured.append(out);
pending = new byte[in.remaining()];
in.get(pending);
}
synchronized String content() {
if (pending.length > 0 && captured.length() < maxChars) {
return captured + "\uFFFD";
}
return captured.toString();
}
private static byte[] concat(byte[] a, byte[] b) {
byte[] result = new byte[a.length + b.length];
System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b, 0, result, a.length, b.length);
return result;
}
}
@@ -45,8 +45,8 @@ public class SsmCommandService implements Resettable {
private static final Logger LOG = Logger.getLogger(SsmCommandService.class);
private static final int MIN_TIMEOUT_SECONDS = 30;
private static final int MAX_STDOUT_CHARS = 24000;
private static final int MAX_STDERR_CHARS = 8000;
static final int MAX_STDOUT_CHARS = 24000;
static final int MAX_STDERR_CHARS = 8000;
private final StorageBackend<String, InstanceInformation> instanceStore;
private final StorageBackend<String, Command> commandStore;
@@ -10,7 +10,6 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -98,8 +97,8 @@ public class SsmDirectCommandExecutor {
String execId = create.exec().getId();
CountDownLatch latch = new CountDownLatch(1);
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
ByteArrayOutputStream stderr = new ByteArrayOutputStream();
BoundedOutputCollector stdout = new BoundedOutputCollector(SsmCommandService.MAX_STDOUT_CHARS);
BoundedOutputCollector stderr = new BoundedOutputCollector(SsmCommandService.MAX_STDERR_CHARS);
Instant start = Instant.now();
ResultCallback<Frame> callback = dockerClient.execStartCmd(execId).exec(new ResultCallback.Adapter<Frame>() {
@@ -109,12 +108,8 @@ public class SsmDirectCommandExecutor {
if (payload == null) {
return;
}
ByteArrayOutputStream target = frame.getStreamType() == StreamType.STDERR ? stderr : stdout;
try {
target.write(payload);
}
catch (IOException ignored) {
}
BoundedOutputCollector target = frame.getStreamType() == StreamType.STDERR ? stderr : stdout;
target.write(payload);
}
@Override
@@ -124,12 +119,8 @@ public class SsmDirectCommandExecutor {
@Override
public void onError(Throwable throwable) {
try {
stderr.write((throwable.getMessage() != null ? throwable.getMessage() : throwable.toString())
.getBytes(StandardCharsets.UTF_8));
}
catch (IOException ignored) {
}
stderr.write((throwable.getMessage() != null ? throwable.getMessage() : throwable.toString())
.getBytes(StandardCharsets.UTF_8));
latch.countDown();
}
});
@@ -138,15 +129,15 @@ public class SsmDirectCommandExecutor {
if (!completed) {
closeQuietly(callback);
return ExecutionResult.timedOut(
stdout.toString(StandardCharsets.UTF_8),
stdout.content(),
"Timed out after " + timeoutSeconds + "s",
start);
}
Long exitCode = dockerClient.inspectExecCmd(execId).exec().getExitCodeLong();
int responseCode = exitCode != null ? exitCode.intValue() : 1;
String standardOutput = stdout.toString(StandardCharsets.UTF_8);
String standardError = stderr.toString(StandardCharsets.UTF_8);
String standardOutput = stdout.content();
String standardError = stderr.content();
if (isTimeoutExitCode(responseCode)) {
logFailureDiagnostics(containerId);
return ExecutionResult.timedOut(standardOutput, standardError, start);
@@ -196,7 +187,7 @@ public class SsmDirectCommandExecutor {
.withAttachStderr(true);
String execId = create.exec().getId();
CountDownLatch latch = new CountDownLatch(1);
ByteArrayOutputStream output = new ByteArrayOutputStream();
BoundedOutputCollector output = new BoundedOutputCollector(SsmCommandService.MAX_STDOUT_CHARS);
ResultCallback<Frame> callback = dockerClient.execStartCmd(execId).exec(new ResultCallback.Adapter<Frame>() {
@Override
public void onNext(Frame frame) {
@@ -204,11 +195,7 @@ public class SsmDirectCommandExecutor {
if (payload == null) {
return;
}
try {
output.write(payload);
}
catch (IOException ignored) {
}
output.write(payload);
}
@Override
@@ -225,7 +212,7 @@ public class SsmDirectCommandExecutor {
if (!completed) {
closeQuietly(callback);
}
return output.toString(StandardCharsets.UTF_8);
return output.content();
}
static String failureDiagnosticsScript() {