feat(ecs): implement ExecuteCommand (#4121)

* feat(ecs): implement ExecuteCommand

ECS Exec was accepted at the API but opened nothing: a client got a
response it could not connect to. This implements the whole path, so
`aws ecs execute-command` gives a real shell in a task's container.

The gate matches AWS. The session must be interactive, which is the only
mode ECS supports; the task must belong to the cluster the request
names, must be RUNNING and must have been run with enableExecuteCommand;
and the container must have a runtime behind it, so a mock-mode task
answers TargetNotConnectedException.

The response carries a session with a single-use tokenValue and a
streamUrl pointing at Floci's own data channel, which is where
session-manager-plugin then connects. 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 with a TTY.

Two threads meet on that channel. Every call into the Docker daemon
blocks, so it runs on a worker rather than on the event loop, and the
daemon streams the container's output back on its own thread; frames are
written from the channel's Vert.x context only, which also keeps the
outbound sequence numbers in the order they reach the wire. The command
is attached to only once the client has accepted the handshake, so no
output can be written to a channel that is still being opened.

Deliberate limits, documented in docs/services/ecs.md:

- The command runs through /bin/sh -c, so an image without a shell
  cannot be exec'd into.
- Sessions are in memory, single use, and expire after five minutes if
  nobody connects.
- ExecuteCommand logging, the executeCommandConfiguration that sends
  session transcripts to S3 or CloudWatch, is not implemented. The
  cluster field still round-trips.

EcsExecSessionRegistry holds a SecureRandom, so it is registered under
--initialize-at-run-time for the native image.

AgentMessageTest covers the wire framing against a JDK-side encode and
decode, EcsExecuteCommandIntegrationTest covers the API gate, and
EcsExecChannelDockerIntegrationTest runs a real session end to end under
Docker.

* fix(ecs): compare the ECS Exec session token in constant time

The token is the single gate in front of an interactive shell in a
container, so compare it with MessageDigest.isEqual on the UTF-8 bytes
rather than String.equals, which returns on the first differing
character. Matches the constant-time comparison the repo already does in
ScimController, IamAuthValidator and LambdaLayerService.

A failed claim still leaves the session in place: dropping it would let
anyone holding a session id cancel somebody else's session.

* fix(ecs): expire an unclaimed ECS Exec session on read

Only create() swept the session map, and neither claim() nor find()
looked at createdAt, so a session nobody connected to stayed claimable,
token included, until the next ExecuteCommand call happened to come in.
On an idle emulator that is forever, which also made the five minute
expiry documented in docs/services/ecs.md untrue.

claim() and find() now go through liveSession(), which drops a session
past SESSION_TTL and reports it as gone: claim() rejects it before the
token comparison, and the WebSocket upgrade refuses to open a channel
for it. The registry takes the CDI Clock so the tests exercise expiry
without waiting out the TTL.
This commit is contained in:
Abhigya authored and GitHub committed 2026-09-22 23:47:40 -04:00
1 parent 899c6f5ec1
commit fcc89c0e8d
14 files changed
+1505 -2

No files matched your search

@@ -0,0 +1,153 @@
package io.github.hectorvent.floci.services.ecs;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
/**
* {@code ExecuteCommand}'s control-plane half: what a task has to be for a session to be opened at
* all, and what the caller gets back when it is.
*
* <p>Tests run with ECS in mock mode, so the tasks here have container models but nothing running
* behind them: the session gate is exercised up to the point where a real container would be
* needed. {@code EcsExecChannelDockerIntegrationTest} covers the rest against Docker.
*/
@QuarkusTest
class EcsExecuteCommandIntegrationTest {
private static final String TARGET = "AmazonEC2ContainerServiceV20141113.";
private static final String CT = "application/x-amz-json-1.1";
private static final String CLUSTER = "exec-cluster";
private static final String NETWORK =
"\"networkConfiguration\":{\"awsvpcConfiguration\":{\"subnets\":"
+ "[\"subnet-default-us-east-1-a\"]}}";
@BeforeAll
static void configure() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static Response call(String action, String body, int expectedStatus) {
return given().contentType(CT).header("X-Amz-Target", TARGET + action)
.body(body)
.when().post("/")
.then().statusCode(expectedStatus)
.extract().response();
}
private static String runTask(String family, boolean enableExecuteCommand) {
call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200);
call("RegisterTaskDefinition", "{\"family\":\"" + family + "\","
+ "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\","
+ "\"cpu\":\"256\",\"memory\":\"512\",\"containerDefinitions\":"
+ "[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 200);
return call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"" + family
+ "\",\"launchType\":\"FARGATE\"," + NETWORK + ",\"enableExecuteCommand\":"
+ enableExecuteCommand + "}", 200)
.jsonPath().getString("tasks[0].taskArn");
}
@Test
void aTaskRunWithExecuteCommandEnabledReportsTheAgent() {
String taskArn = runTask("exec-enabled", true);
call("DescribeTasks", "{\"cluster\":\"" + CLUSTER + "\",\"tasks\":[\"" + taskArn + "\"]}", 200)
.then()
.body("tasks[0].enableExecuteCommand", equalTo(true))
.body("tasks[0].containers", hasSize(1))
.body("tasks[0].containers[0].managedAgents[0].name", equalTo("ExecuteCommandAgent"))
.body("tasks[0].containers[0].managedAgents[0].lastStatus", equalTo("RUNNING"));
}
@Test
void executeCommandIsRefusedWhenTheTaskWasNotRunWithItEnabled() {
String taskArn = runTask("exec-disabled", false);
call("ExecuteCommand", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\"" + taskArn
+ "\",\"container\":\"app\",\"command\":\"/bin/sh\",\"interactive\":true}", 400)
.then()
.body("__type", containsString("InvalidParameterException"))
.body("message", containsString("execute command was not enabled"));
}
@Test
void executeCommandIsRefusedForAContainerThatIsNotInTheTask() {
String taskArn = runTask("exec-wrong-container", true);
call("ExecuteCommand", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\"" + taskArn
+ "\",\"container\":\"sidecar\",\"command\":\"/bin/sh\",\"interactive\":true}", 400)
.then().body("message", containsString("sidecar"));
}
@Test
void executeCommandIsRefusedWhenNothingIsRunningBehindTheContainer() {
// Mock mode reports the container but has no runtime behind it, which is exactly the
// state AWS reports as a disconnected target rather than a missing one.
String taskArn = runTask("exec-no-runtime", true);
call("ExecuteCommand", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\"" + taskArn
+ "\",\"container\":\"app\",\"command\":\"/bin/sh\",\"interactive\":true}", 400)
.then()
.body("__type", containsString("TargetNotConnectedException"));
}
@Test
void executeCommandIsRefusedOnAStoppedTask() {
String taskArn = runTask("exec-stopped", true);
call("StopTask", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\"" + taskArn + "\"}", 200);
call("ExecuteCommand", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\"" + taskArn
+ "\",\"container\":\"app\",\"command\":\"/bin/sh\",\"interactive\":true}", 400)
.then()
.body("__type", containsString("TargetNotConnectedException"))
.body("message", containsString("not running"));
}
@Test
void executeCommandIsRefusedWhenItIsNotInteractive() {
String taskArn = runTask("exec-non-interactive", true);
call("ExecuteCommand", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\"" + taskArn
+ "\",\"container\":\"app\",\"command\":\"/bin/sh\",\"interactive\":false}", 400)
.then()
.body("__type", containsString("InvalidParameterException"))
.body("message", containsString("interactive"));
}
@Test
void executeCommandIsRefusedForAClusterThatDoesNotExist() {
String taskArn = runTask("exec-unknown-cluster", true);
call("ExecuteCommand", "{\"cluster\":\"no-such-cluster\",\"task\":\"" + taskArn
+ "\",\"container\":\"app\",\"command\":\"/bin/sh\",\"interactive\":true}", 400)
.then().body("__type", containsString("ClusterNotFoundException"));
}
@Test
void executeCommandIsRefusedForATaskInAnotherCluster() {
String taskArn = runTask("exec-other-cluster", true);
call("CreateCluster", "{\"clusterName\":\"exec-bystander\"}", 200);
call("ExecuteCommand", "{\"cluster\":\"exec-bystander\",\"task\":\"" + taskArn
+ "\",\"container\":\"app\",\"command\":\"/bin/sh\",\"interactive\":true}", 400)
.then()
.body("__type", containsString("InvalidParameterException"))
.body("message", containsString("is not part of the cluster"));
}
@Test
void executeCommandRejectsAnEmptyCommand() {
String taskArn = runTask("exec-empty-command", true);
call("ExecuteCommand", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\"" + taskArn
+ "\",\"container\":\"app\",\"command\":\"\",\"interactive\":true}", 400)
.then().body("message", containsString("command cannot be empty"));
}
}
@@ -1206,6 +1206,19 @@ class EcsFargateEdgeCaseIntegrationTest {
.then().body("message", containsString("containerInstances"));
}
@Test
void executeCommandOnlySupportsInteractiveSessions() {
String family = seed("edge-interactive");
String taskArn = call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\""
+ family + "\",\"launchType\":\"FARGATE\"," + NETWORK
+ ",\"enableExecuteCommand\":true}", 200)
.jsonPath().getString("tasks[0].taskArn");
call("ExecuteCommand", "{\"cluster\":\"" + CLUSTER + "\",\"task\":\"" + taskArn
+ "\",\"container\":\"app\",\"command\":\"/bin/sh\",\"interactive\":false}", 400)
.then().body("message", containsString("interactive"));
}
// ── The Service shape's own members ──────────────────────────────────────
@Test
@@ -0,0 +1,89 @@
package io.github.hectorvent.floci.services.ecs.exec;
import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* The Session Manager frame layout. {@code session-manager-plugin} parses these bytes by fixed
* offset, so the field order, the padding, the digest and the swapped halves of the message id are
* the contract: get one wrong and the plugin drops the channel without saying why.
*/
class AgentMessageTest {
private static final int PAYLOAD_OFFSET = 120;
@Test
void encodeWritesTheHeaderTheAgentWrites() throws Exception {
UUID messageId = UUID.fromString("2f1b6a4e-9c3d-4f7a-8b2e-1d0c9a8b7c6d");
byte[] payload = "hello".getBytes(StandardCharsets.UTF_8);
AgentMessage message = new AgentMessage(AgentMessage.OUTPUT_STREAM_DATA, 1, 1700000000000L,
7L, 0L, messageId, AgentMessage.PAYLOAD_OUTPUT, payload);
byte[] encoded = message.encode();
ByteBuffer buffer = ByteBuffer.wrap(encoded);
assertEquals(AgentMessage.HEADER_LENGTH, buffer.getInt(), "the header length comes first");
byte[] type = new byte[32];
buffer.get(type);
assertEquals(AgentMessage.OUTPUT_STREAM_DATA,
new String(type, StandardCharsets.UTF_8).trim());
assertEquals(' ', (char) type[type.length - 1], "the message type is padded with spaces");
assertEquals(1, buffer.getInt(), "schema version");
assertEquals(1700000000000L, buffer.getLong(), "created date");
assertEquals(7L, buffer.getLong(), "sequence number");
assertEquals(0L, buffer.getLong(), "flags");
// The low half of the id is written before the high half.
assertEquals(messageId.getLeastSignificantBits(), buffer.getLong());
assertEquals(messageId.getMostSignificantBits(), buffer.getLong());
byte[] digest = new byte[32];
buffer.get(digest);
assertArrayEquals(MessageDigest.getInstance("SHA-256").digest(payload), digest,
"the digest covers the payload");
assertEquals(AgentMessage.PAYLOAD_OUTPUT, buffer.getInt(), "payload type");
assertEquals(payload.length, buffer.getInt(), "payload length");
assertEquals(PAYLOAD_OFFSET + payload.length, encoded.length);
}
@Test
void decodeReadsBackWhatEncodeWrote() {
UUID messageId = UUID.randomUUID();
byte[] payload = "{\"cols\":120,\"rows\":40}".getBytes(StandardCharsets.UTF_8);
AgentMessage original = new AgentMessage(AgentMessage.INPUT_STREAM_DATA, 1, 42L, 3L, 1L,
messageId, AgentMessage.PAYLOAD_SIZE, payload);
AgentMessage decoded = AgentMessage.decode(original.encode());
assertEquals(AgentMessage.INPUT_STREAM_DATA, decoded.messageType());
assertEquals(1, decoded.schemaVersion());
assertEquals(42L, decoded.createdDate());
assertEquals(3L, decoded.sequenceNumber());
assertEquals(1L, decoded.flags());
assertEquals(messageId, decoded.messageId());
assertEquals(AgentMessage.PAYLOAD_SIZE, decoded.payloadType());
assertEquals("{\"cols\":120,\"rows\":40}", decoded.payloadAsString());
}
@Test
void anEmptyPayloadRoundTrips() {
AgentMessage decoded = AgentMessage.decode(
AgentMessage.outbound(AgentMessage.CHANNEL_CLOSED, 0, AgentMessage.PAYLOAD_OUTPUT,
new byte[0]).encode());
assertEquals(AgentMessage.CHANNEL_CLOSED, decoded.messageType());
assertEquals(0, decoded.payload().length);
}
@Test
void aTruncatedFrameIsRejectedRatherThanMisread() {
byte[] tooShort = new byte[64];
assertThrows(IllegalArgumentException.class, () -> AgentMessage.decode(tooShort));
}
}
@@ -0,0 +1,210 @@
package io.github.hectorvent.floci.services.ecs.exec;
import com.github.dockerjava.api.DockerClient;
import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager;
import io.github.hectorvent.floci.services.ecs.container.EcsTaskHandle;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.WebSocket;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* ECS Exec end to end, against a real container.
*
* <p>This drives the client half of the Session Manager protocol the way
* {@code session-manager-plugin} does: open the channel with the session token, answer the
* handshake, then read the command's output off the stream. The plugin binary is not available in
* CI, so the protocol is exercised from here rather than from it.
*/
@QuarkusTest
class EcsExecChannelDockerIntegrationTest {
private static final String BUSYBOX_IMAGE = "public.ecr.aws/docker/library/busybox:latest";
private static final String TASK_ARN =
"arn:aws:ecs:us-east-1:000000000000:task/exec-cluster/execdockertask";
@Inject
EcsContainerManager containerManager;
@Inject
EcsExecSessionRegistry sessions;
@Inject
DockerClient dockerClient;
@Inject
Vertx vertx;
@BeforeEach
void requireDocker() {
Assumptions.assumeTrue(isDockerAvailable(),
"Docker daemon must be available for the ECS Exec channel test");
}
@Test
void aClientDrivingTheProtocolGetsTheCommandsOutput() throws Exception {
String suffix = UUID.randomUUID().toString().substring(0, 8);
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
app.setImage(BUSYBOX_IMAGE);
app.setCommand(List.of("sleep", "120"));
TaskDefinition taskDefinition = new TaskDefinition();
taskDefinition.setFamily("exec-docker-" + suffix);
taskDefinition.setContainerDefinitions(List.of(app));
EcsTask task = new EcsTask();
task.setTaskArn(TASK_ARN + suffix);
task.setEnableExecuteCommand(true);
EcsTaskHandle handle = containerManager.startTask(task, taskDefinition, List.of(), "us-east-1");
try {
// The agent is reported as running, which is what a client checks before connecting.
assertEquals(ManagedAgentStatus.RUNNING, ManagedAgentStatus.of(task));
String runtimeId = handle.getContainerIds().get("app");
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);
PluginClient client = new PluginClient(vertx, session);
try {
client.open();
AgentMessage handshakeRequest = client.next();
assertEquals(AgentMessage.OUTPUT_STREAM_DATA, handshakeRequest.messageType());
assertEquals(AgentMessage.PAYLOAD_HANDSHAKE_REQUEST, handshakeRequest.payloadType());
assertTrue(handshakeRequest.payloadAsString().contains("Standard_Stream"),
"the agent asks for a standard stream session: "
+ handshakeRequest.payloadAsString());
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);
} finally {
client.close();
}
// The session was single use: the token cannot open a second shell.
assertTrue(sessions.find(session.sessionId()).isEmpty(),
"a claimed session must not be claimable again");
} finally {
containerManager.stopTask(handle);
}
}
/** Reads the ExecuteCommandAgent status a task's containers report. */
private enum ManagedAgentStatus {
RUNNING, ABSENT;
static ManagedAgentStatus of(EcsTask task) {
return task.getContainers() != null
&& task.getContainers().stream().anyMatch(container ->
container.getManagedAgents() != null
&& container.getManagedAgents().stream().anyMatch(agent ->
"ExecuteCommandAgent".equals(agent.name())
&& "RUNNING".equals(agent.lastStatus())))
? RUNNING : ABSENT;
}
}
/** The half of the Session Manager protocol that {@code session-manager-plugin} implements. */
private static final class PluginClient {
private final Vertx vertx;
private final ExecSession session;
private final BlockingQueue<AgentMessage> received = new LinkedBlockingQueue<>();
private HttpClient httpClient;
private WebSocket webSocket;
private long sequence;
PluginClient(Vertx vertx, ExecSession session) {
this.vertx = vertx;
this.session = session;
}
void open() throws Exception {
httpClient = vertx.createHttpClient();
webSocket = httpClient.webSocket(RestAssured.port, "localhost",
EcsExecChannelHandler.CHANNEL_PATH_PREFIX + session.sessionId())
.toCompletionStage().toCompletableFuture().get(20, TimeUnit.SECONDS);
webSocket.binaryMessageHandler(buffer -> received.add(AgentMessage.decode(buffer.getBytes())));
webSocket.writeTextMessage("{\"MessageSchemaVersion\":\"1.0\",\"RequestId\":\""
+ UUID.randomUUID() + "\",\"TokenValue\":\"" + session.tokenValue()
+ "\",\"ClientId\":\"" + UUID.randomUUID() + "\"}");
}
void sendHandshakeResponse() {
String payload = "{\"ClientVersion\":\"1.2.0.0\",\"ProcessedClientActions\":"
+ "[{\"ActionType\":\"SessionType\",\"ActionStatus\":1}],\"Errors\":\"\"}";
AgentMessage response = AgentMessage.outbound(AgentMessage.INPUT_STREAM_DATA, sequence++,
AgentMessage.PAYLOAD_HANDSHAKE_RESPONSE, payload.getBytes(StandardCharsets.UTF_8));
webSocket.writeBinaryMessage(Buffer.buffer(response.encode()));
}
AgentMessage next() throws InterruptedException {
AgentMessage message = received.poll(30, TimeUnit.SECONDS);
assertNotNull(message, "the agent must send a frame");
return message;
}
/** Collects output frames until the expected text shows up or the channel goes quiet. */
String readUntil(String expected) throws InterruptedException {
StringBuilder output = new StringBuilder();
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
while (System.nanoTime() < deadline && !output.toString().contains(expected)) {
AgentMessage message = received.poll(1, TimeUnit.SECONDS);
if (message == null) {
continue;
}
if (AgentMessage.OUTPUT_STREAM_DATA.equals(message.messageType())
&& message.payloadType() == AgentMessage.PAYLOAD_OUTPUT) {
output.append(message.payloadAsString());
}
}
return output.toString();
}
void close() {
if (webSocket != null) {
webSocket.close();
}
if (httpClient != null) {
httpClient.close();
}
}
}
private boolean isDockerAvailable() {
try {
dockerClient.pingCmd().exec();
return true;
} catch (RuntimeException e) {
return false;
}
}
}
@@ -0,0 +1,133 @@
package io.github.hectorvent.floci.services.ecs.exec;
import io.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The token gate in front of an interactive shell. A session is claimed once, by the exact token
* that was minted for it, never by a replay of that token, and never once it has outlived its TTL.
*/
class EcsExecSessionRegistryTest {
private static final String TASK_ARN =
"arn:aws:ecs:us-east-1:000000000000:task/my-cluster/0123456789abcdef";
private static final String CLUSTER_ARN =
"arn:aws:ecs:us-east-1:000000000000:cluster/my-cluster";
private final MutableClock clock = new MutableClock();
private final EcsExecSessionRegistry registry = new EcsExecSessionRegistry(clock);
@Test
void claimWithTheMintedToken() {
ExecSession created = mint();
Optional<ExecSession> claimed = registry.claim(created.sessionId(), created.tokenValue());
assertTrue(claimed.isPresent());
assertEquals("deadbeef", claimed.get().runtimeId());
assertEquals(List.of("/bin/sh"), claimed.get().command());
}
@Test
void claim_wrongToken_isRejectedAndLeavesTheSession() {
ExecSession created = mint();
assertTrue(registry.claim(created.sessionId(), "not-the-token").isEmpty());
assertTrue(registry.find(created.sessionId()).isPresent(),
"a failed claim must not let a stranger cancel somebody else's session");
assertTrue(registry.claim(created.sessionId(), created.tokenValue()).isPresent());
}
@Test
void claim_tokenOfADifferentLength_isRejected() {
ExecSession created = mint();
assertTrue(registry.claim(created.sessionId(), created.tokenValue() + "x").isEmpty());
assertTrue(registry.claim(created.sessionId(), "").isEmpty());
}
@Test
void claim_missingToken_isRejected() {
ExecSession created = mint();
assertTrue(registry.claim(created.sessionId(), null).isEmpty());
}
@Test
void claim_unknownSession_isRejected() {
assertTrue(registry.claim("ecs-execute-command-nothingtoseehere", "any").isEmpty());
}
@Test
void claim_isSingleUse() {
ExecSession created = mint();
assertTrue(registry.claim(created.sessionId(), created.tokenValue()).isPresent());
assertTrue(registry.claim(created.sessionId(), created.tokenValue()).isEmpty(),
"a replayed token must not open a second channel");
assertTrue(registry.find(created.sessionId()).isEmpty());
}
@Test
void everySessionGetsItsOwnToken() {
ExecSession first = mint();
ExecSession second = mint();
assertNotEquals(first.sessionId(), second.sessionId());
assertNotEquals(first.tokenValue(), second.tokenValue());
assertTrue(registry.claim(first.sessionId(), second.tokenValue()).isEmpty());
}
@Test
void clearDropsEveryOpenSession() {
ExecSession created = mint();
registry.clear();
assertFalse(registry.find(created.sessionId()).isPresent());
}
@Test
void claim_sessionPastItsTtl_isRejected() {
ExecSession created = mint();
clock.advance(EcsExecSessionRegistry.SESSION_TTL.plusSeconds(1));
assertTrue(registry.claim(created.sessionId(), created.tokenValue()).isEmpty(),
"a session nobody connected to must stop being claimable once it expires");
assertTrue(registry.find(created.sessionId()).isEmpty(),
"an expired session must be dropped, not left holding its token");
}
@Test
void claim_sessionWithinItsTtl_stillWorks() {
ExecSession created = mint();
clock.advance(EcsExecSessionRegistry.SESSION_TTL.minusSeconds(1));
assertTrue(registry.claim(created.sessionId(), created.tokenValue()).isPresent());
}
@Test
void find_sessionPastItsTtl_isEmpty() {
ExecSession created = mint();
clock.advance(EcsExecSessionRegistry.SESSION_TTL.plusSeconds(1));
assertTrue(registry.find(created.sessionId()).isEmpty(),
"the channel upgrade must refuse an expired session instead of opening a channel");
}
private ExecSession mint() {
return registry.create(TASK_ARN, CLUSTER_ARN, "app",
TASK_ARN.replace(":task/", ":container/"), "deadbeef", List.of("/bin/sh"), true);
}
}