Skip to content

Commit c0a0739

Browse files
joe4devclaude
andauthored
fix: run awslocal against the gateway's container-side address (#138)
* fix: point in-container awslocal at the gateway's container-side address localstack-aws-client and the deployer's create-stack/delete-stack run awslocal inside the LocalStack container. awslocal derives its endpoint from LOCALSTACK_HOST, which names the host-side address, unless AWS_ENDPOINT_URL is set. With the gateway published on another host port (-p 4700:4566, LOCALSTACK_HOST=localhost.localstack.cloud:4700) or moved by GATEWAY_LISTEN, awslocal called a port nothing listens on inside the container. Each awslocal exec now gets AWS_ENDPOINT_URL=http://localhost:<port>, where the port is the first GATEWAY_LISTEN entry of the container's environment (LOCALSTACK_GATEWAY_LISTEN first, default 4566). Only the exec's environment changes; the container keeps its LOCALSTACK_HOST, so URLs LocalStack returns (SQS queue URLs) still name the host side. The awslocal-in-container pattern itself stays a known deviation (target: lstk aws, DEVX-1330); this only fixes its endpoint. Tests: unit tests for the endpoint derivation, handler tests for both tools, and tests/mcp/aws-client-ports.spec.mjs, which runs the aws-client and the deployer against LocalStack on the default port, a remapped host port and a custom GATEWAY_LISTEN. It runs in test:mcp:tools with one worker, so its default case does not race tools.spec.mjs for port 4566. Fixes DEVX-1338 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep awslocal's own endpoint for commands that build URLs for the caller 118299f pointed every in-container awslocal at the container-side gateway, so `s3 presign` returned http://localhost:<container port>/..., which the host cannot reach. Commands that sign a URL or token locally and print it without calling the gateway (s3 presign, rds generate-db-auth-token, eks get-token, dsql generate-db-connect-*) now get no AWS_ENDPOINT_URL, so awslocal uses LOCALSTACK_HOST as before. The decision lives in awslocal-endpoint.logic.ts (buildsClientUrl), and those commands skip the container inspect. The deployer now removes its temporary template in a finally block, so it no longer stays in the container when the create-stack exec throws. Tests: - unit: URL-building commands with and without global options, and look-alikes that call the gateway - handler tests run analytics and the preflights for real (PostHog and the gateway health probe mocked) and cover presign, a failing container inspect, LocalStack not running, create-stack and delete-stack failures, a missing stackName, the template cleanup, and a container auth token that must not reach the exec env, the response or analytics - aws-client-ports.spec.mjs: every case uses a free host port (the default case keeps the in-container defaults), ports are picked when a case runs, and the mapped and GATEWAY_LISTEN cases check that a presigned URL names the host port and can be fetched from the host Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent b9363e8 commit c0a0739

10 files changed

Lines changed: 957 additions & 23 deletions

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ This server provides your AI with dedicated tools for managing your LocalStack e
7474
| [`localstack-state-management`](./src/tools/localstack-state-management.ts) | Manages local file-based LocalStack state export/import workflows | - Export LocalStack state to a local file on disk through the LocalStack State REST API<br/>- Import LocalStack state from a local file<br/>- Inspect current LocalStack state as JSON metamodel data<br/>- Reset all state or only selected services<br/>- Supports service-level granularity for export, reset, and inspect<br/>- Use this for local disk workflows; use Cloud Pods for remote cloud-backed snapshots<br/>- Requires a valid LocalStack Auth Token |
7575
| [`localstack-extensions`](./src/tools/localstack-extensions.ts) | Installs, uninstalls, lists, and discovers LocalStack Extensions | - Manage installed extensions (`list`, `install`, `uninstall`) inside the running container<br/>- Browse the LocalStack Extensions marketplace (`available`)<br/>- Requires a valid LocalStack Auth Token |
7676
| [`localstack-ephemeral-instances`](./src/tools/localstack-ephemeral-instances.ts) | Manages cloud-hosted LocalStack Ephemeral Instances | - Create temporary cloud-hosted LocalStack instances and get an endpoint URL<br/>- List available ephemeral instances, fetch logs, and delete instances<br/>- Supports lifetime, extension preload, Cloud Pod preload, and custom env vars on create<br/>- Requires a valid LocalStack Auth Token |
77-
| [`localstack-aws-client`](./src/tools/localstack-aws-client.ts) | Runs AWS CLI commands inside the LocalStack for AWS container | - Executes commands via `awslocal` inside the running container<br/>- Sanitizes commands to block shell chaining<br/>- Auto-detects LocalStack coverage errors and links to docs |
77+
| [`localstack-aws-client`](./src/tools/localstack-aws-client.ts) | Runs AWS CLI commands inside the LocalStack for AWS container | - Executes commands via `awslocal` inside the running container, against the gateway's in-container address (works with a remapped host port, `LOCALSTACK_HOST` or `GATEWAY_LISTEN`)<br/>- Sanitizes commands to block shell chaining<br/>- Auto-detects LocalStack coverage errors and links to docs |
7878
| [`localstack-azure-client`](./src/tools/localstack-azure-client.ts) | Runs Azure CLI (`az`) commands against the LocalStack for Azure emulator | - Runs the Azure CLI installed on your machine with its own profile, never your Azure login<br/>- Blocks shell syntax and commands that would change the profile, install software or never end<br/>- Uses the extensions you installed with `az extension add`<br/>- Requires the Azure CLI and a valid LocalStack Auth Token |
7979
| [`localstack-aws-replicator`](./src/tools/localstack-aws-replicator.ts) | Replicates external AWS resources into a running LocalStack instance | - Start single-resource replication jobs with a resource type and identifier or ARN<br/>- Start batch replication jobs, such as SSM parameters under a path prefix<br/>- Poll job status by job ID and list existing jobs<br/>- List resource types supported by the running Replicator extension<br/>- Reads source AWS credentials from the MCP server environment and supports optional target account or region overrides |
8080
| [`localstack-app-inspector`](./src/tools/localstack-app-inspector.ts) | Inspects LocalStack application traces, spans, events, and IAM evaluations | - Enable or disable App Inspector for the running LocalStack instance<br/>- List and inspect traces to understand AWS service-to-service flows<br/>- Drill into spans, events, payload metadata, and IAM policy evaluation events<br/>- Filter by service, region, operation, resource, ARN, status, and time range<br/>- Requires a valid LocalStack Auth Token and the App Inspector feature in the connected LocalStack license |

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
"test": "jest",
1818
"test:mcp:direct": "yarn build && playwright test -c playwright.config.mjs tests/mcp/direct.spec.mjs tests/mcp/azure-offline.spec.mjs",
1919
"test:mcp:evals": "yarn build && playwright test -c playwright.config.mjs tests/mcp/evals.spec.mjs",
20-
"test:mcp:tools": "yarn build && playwright test -c playwright.config.mjs tests/mcp/tools.spec.mjs",
20+
"test:mcp:tools": "yarn build && playwright test -c playwright.config.mjs --workers=1 tests/mcp/tools.spec.mjs tests/mcp/aws-client-ports.spec.mjs",
2121
"test:mcp": "yarn test:mcp:direct && yarn test:mcp:tools && yarn test:mcp:evals"
2222
},
2323
"dependencies": {
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
import {
2+
awsCliCommandName,
3+
awslocalExecEnv,
4+
buildsClientUrl,
5+
containerEnvValue,
6+
containerGatewayEndpoint,
7+
containerGatewayPort,
8+
} from "./awslocal-endpoint.logic";
9+
10+
describe("containerGatewayEndpoint", () => {
11+
test("default: no GATEWAY_LISTEN means the gateway on 4566", () => {
12+
expect(containerGatewayEndpoint(undefined)).toBe("http://localhost:4566");
13+
expect(containerGatewayEndpoint(["PATH=/usr/bin", "DEBUG=1"])).toBe("http://localhost:4566");
14+
});
15+
16+
test("the server's own container spec (:4566,:443) keeps 4566", () => {
17+
expect(containerGatewayEndpoint(["GATEWAY_LISTEN=:4566,:443"])).toBe("http://localhost:4566");
18+
});
19+
20+
test("mapped host port: LOCALSTACK_HOST names the host side and is ignored", () => {
21+
const env = ["LOCALSTACK_HOST=localhost.localstack.cloud:4700", "PATH=/usr/bin"];
22+
expect(containerGatewayEndpoint(env)).toBe("http://localhost:4566");
23+
});
24+
25+
test("mapped host port with the server's GATEWAY_LISTEN still targets the container port", () => {
26+
const env = ["LOCALSTACK_HOST=localhost.localstack.cloud:4700", "GATEWAY_LISTEN=:4566,:443"];
27+
expect(containerGatewayEndpoint(env)).toBe("http://localhost:4566");
28+
});
29+
30+
test("custom GATEWAY_LISTEN: the first entry's port", () => {
31+
expect(containerGatewayEndpoint(["GATEWAY_LISTEN=0.0.0.0:4700"])).toBe("http://localhost:4700");
32+
expect(containerGatewayEndpoint(["GATEWAY_LISTEN=:5000,:4566"])).toBe("http://localhost:5000");
33+
expect(containerGatewayEndpoint(["GATEWAY_LISTEN= 127.0.0.1:4800 , :443"])).toBe(
34+
"http://localhost:4800"
35+
);
36+
});
37+
38+
test("custom GATEWAY_LISTEN together with LOCALSTACK_HOST on another port", () => {
39+
const env = ["GATEWAY_LISTEN=0.0.0.0:4700", "LOCALSTACK_HOST=localhost.localstack.cloud:5700"];
40+
expect(containerGatewayEndpoint(env)).toBe("http://localhost:4700");
41+
});
42+
43+
test("IPv6 entries", () => {
44+
expect(containerGatewayPort(["GATEWAY_LISTEN=[::]:4700"])).toBe(4700);
45+
expect(containerGatewayPort(["GATEWAY_LISTEN=[::1]"])).toBe(4566);
46+
});
47+
48+
test("a host without a port keeps the default port, as LocalStack reads it", () => {
49+
expect(containerGatewayPort(["GATEWAY_LISTEN=0.0.0.0"])).toBe(4566);
50+
});
51+
52+
test("LOCALSTACK_GATEWAY_LISTEN wins, since the entrypoint exports it as GATEWAY_LISTEN", () => {
53+
const env = ["GATEWAY_LISTEN=:4566", "LOCALSTACK_GATEWAY_LISTEN=:4900"];
54+
expect(containerGatewayPort(env)).toBe(4900);
55+
});
56+
57+
test("empty or unreadable values fall back to 4566", () => {
58+
expect(containerGatewayPort(["GATEWAY_LISTEN="])).toBe(4566);
59+
expect(containerGatewayPort(["GATEWAY_LISTEN=:abc"])).toBe(4566);
60+
expect(containerGatewayPort(["GATEWAY_LISTEN=:0"])).toBe(4566);
61+
expect(containerGatewayPort(["GATEWAY_LISTEN=:70000"])).toBe(4566);
62+
expect(containerGatewayPort(["GATEWAY_LISTEN=[::1"])).toBe(4566);
63+
});
64+
65+
test("a variable whose name only starts with GATEWAY_LISTEN is not read", () => {
66+
expect(containerGatewayPort(["GATEWAY_LISTEN_EXTRA=:4700"])).toBe(4566);
67+
});
68+
});
69+
70+
describe("containerEnvValue", () => {
71+
test("keeps '=' inside the value", () => {
72+
expect(containerEnvValue(["A=b=c"], "A")).toBe("b=c");
73+
expect(containerEnvValue(["A=1"], "B")).toBeUndefined();
74+
});
75+
});
76+
77+
describe("awslocalExecEnv", () => {
78+
const mapped = ["LOCALSTACK_HOST=localhost.localstack.cloud:4700", "GATEWAY_LISTEN=:4600"];
79+
80+
test("sets only AWS_ENDPOINT_URL, to the container-side gateway", () => {
81+
expect(awslocalExecEnv(mapped, ["sqs", "list-queues"])).toEqual([
82+
"AWS_ENDPOINT_URL=http://localhost:4600",
83+
]);
84+
});
85+
86+
test.each([
87+
[["s3", "presign", "s3://bucket/key"]],
88+
[["s3", "presign", "s3://bucket/key", "--expires-in", "60"]],
89+
[["--region", "eu-west-1", "s3", "presign", "s3://bucket/key"]],
90+
[["rds", "generate-db-auth-token", "--hostname", "db", "--port", "5432", "--username", "u"]],
91+
[["eks", "get-token", "--cluster-name", "c1"]],
92+
[["dsql", "generate-db-connect-auth-token", "--hostname", "h"]],
93+
[["dsql", "generate-db-connect-admin-auth-token", "--hostname", "h"]],
94+
])("%j builds a URL for the caller, so it keeps awslocal's LOCALSTACK_HOST endpoint", (args) => {
95+
expect(awslocalExecEnv(mapped, args)).toEqual([]);
96+
});
97+
98+
test.each([
99+
[["s3", "ls"]],
100+
[["s3", "cp", "presign", "s3://bucket/presign"]],
101+
[["s3api", "get-object", "--bucket", "presign", "--key", "k", "out"]],
102+
[["rds", "describe-db-instances"]],
103+
[["eks", "list-clusters"]],
104+
[["--output", "s3", "sqs", "list-queues"]],
105+
])("%j calls the gateway, so it gets the container-side endpoint", (args) => {
106+
expect(awslocalExecEnv(mapped, args)).toEqual(["AWS_ENDPOINT_URL=http://localhost:4600"]);
107+
});
108+
});
109+
110+
describe("awsCliCommandName", () => {
111+
test("skips global options and their values", () => {
112+
expect(awsCliCommandName(["--debug", "--profile", "p", "S3", "Presign", "x"])).toBe(
113+
"s3 presign"
114+
);
115+
expect(awsCliCommandName(["--region=us-east-1", "sqs", "list-queues"])).toBe("sqs list-queues");
116+
expect(awsCliCommandName(["help"])).toBe("help");
117+
expect(buildsClientUrl([])).toBe(false);
118+
});
119+
});
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
/**
2+
* Where `awslocal` must send requests when it runs inside the LocalStack container.
3+
*
4+
* `awslocal` builds its endpoint from `LOCALSTACK_HOST` unless `AWS_ENDPOINT_URL` is set.
5+
* `LOCALSTACK_HOST` names the gateway as the host sees it (for example
6+
* `localhost.localstack.cloud:4700` when the gateway is published on host port 4700), and
7+
* that port is not open inside the container. The gateway listens inside the container on
8+
* the first `GATEWAY_LISTEN` address, port 4566 by default, so `awslocal` gets that address
9+
* as `AWS_ENDPOINT_URL` for its own process only. The container's `LOCALSTACK_HOST` stays as
10+
* it is, so the URLs LocalStack returns (SQS queue URLs) still name the host-side address.
11+
*
12+
* Commands that only build a URL or token for the caller, without calling the gateway
13+
* (`s3 presign`), are the exception: their output is used from the host, so they keep the
14+
* `LOCALSTACK_HOST` address `awslocal` picks on its own.
15+
*/
16+
17+
export const DEFAULT_CONTAINER_GATEWAY_PORT = 4566;
18+
19+
/**
20+
* AWS CLI commands that sign a URL or token locally and print it, without a request to the
21+
* endpoint, so the endpoint they embed must be reachable by whoever uses the output.
22+
*/
23+
const CLIENT_URL_COMMANDS = new Set([
24+
"s3 presign",
25+
"rds generate-db-auth-token",
26+
"eks get-token",
27+
"dsql generate-db-connect-auth-token",
28+
"dsql generate-db-connect-admin-auth-token",
29+
]);
30+
31+
/** AWS CLI global options that take a value, so the next argument is not the service. */
32+
const GLOBAL_OPTIONS_WITH_VALUE = new Set([
33+
"--profile",
34+
"--region",
35+
"--output",
36+
"--query",
37+
"--endpoint-url",
38+
"--ca-bundle",
39+
"--color",
40+
"--cli-read-timeout",
41+
"--cli-connect-timeout",
42+
"--cli-binary-format",
43+
]);
44+
45+
/** The value of `key` in a container's `KEY=value` environment list, or undefined. */
46+
export function containerEnvValue(env: string[] | undefined, key: string): string | undefined {
47+
const prefix = `${key}=`;
48+
const entry = (env ?? []).find((item) => item.startsWith(prefix));
49+
return entry === undefined ? undefined : entry.slice(prefix.length);
50+
}
51+
52+
/**
53+
* The port of the first `GATEWAY_LISTEN` entry, read the way LocalStack reads it: `[ipv6]:port`,
54+
* `host:port`, `:port`, or a host alone, which keeps the default port. The container entrypoint
55+
* exports `LOCALSTACK_GATEWAY_LISTEN` as `GATEWAY_LISTEN`, so the prefixed name wins. An unset,
56+
* empty or unreadable value means the default port.
57+
*
58+
* This does not reuse `parseGatewayListen` in `container-spec.logic.ts`: that one parses the
59+
* value the server is given to start a container, and reads a bare entry (`4700`) as a port.
60+
* This one reads the value a running container already has, so it follows how LocalStack
61+
* parses each address (`HostAndPort.parse`), where a bare entry is a host on the default port.
62+
*
63+
* `GATEWAY_LISTEN=:0` lets LocalStack pick a free port, which the environment does not reveal;
64+
* it falls back to 4566.
65+
*/
66+
export function containerGatewayPort(env: string[] | undefined): number {
67+
const raw =
68+
containerEnvValue(env, "LOCALSTACK_GATEWAY_LISTEN") ?? containerEnvValue(env, "GATEWAY_LISTEN");
69+
const first = raw?.split(",")[0]?.trim();
70+
if (!first) return DEFAULT_CONTAINER_GATEWAY_PORT;
71+
72+
let portText: string | undefined;
73+
if (first.startsWith("[")) {
74+
portText = /^\[[^\]]+\](?::(\d+))?$/.exec(first)?.[1];
75+
} else if (first.includes(":")) {
76+
portText = first.slice(first.indexOf(":") + 1);
77+
}
78+
if (portText === undefined) return DEFAULT_CONTAINER_GATEWAY_PORT;
79+
80+
const port = Number(portText);
81+
return Number.isInteger(port) && port > 0 && port < 65536 ? port : DEFAULT_CONTAINER_GATEWAY_PORT;
82+
}
83+
84+
/** The gateway as a process inside the container reaches it. */
85+
export function containerGatewayEndpoint(env: string[] | undefined): string {
86+
return `http://localhost:${containerGatewayPort(env)}`;
87+
}
88+
89+
/** The service and operation of an AWS CLI argument list, skipping global options. */
90+
export function awsCliCommandName(args: string[]): string {
91+
const positional: string[] = [];
92+
for (let i = 0; i < args.length && positional.length < 2; i++) {
93+
const arg = args[i];
94+
if (arg.startsWith("-")) {
95+
if (GLOBAL_OPTIONS_WITH_VALUE.has(arg)) i++;
96+
continue;
97+
}
98+
positional.push(arg.toLowerCase());
99+
}
100+
return positional.join(" ");
101+
}
102+
103+
/** Whether the command builds a URL or token for the caller instead of calling the gateway. */
104+
export function buildsClientUrl(args: string[]): boolean {
105+
return CLIENT_URL_COMMANDS.has(awsCliCommandName(args));
106+
}
107+
108+
/**
109+
* The environment for `awslocal <args>` in the container whose environment is `env`: the
110+
* container-side gateway, except for commands that build a URL for the caller, which keep
111+
* `awslocal`'s own `LOCALSTACK_HOST` endpoint.
112+
*/
113+
export function awslocalExecEnv(env: string[] | undefined, args: string[]): string[] {
114+
if (buildsClientUrl(args)) return [];
115+
return [`AWS_ENDPOINT_URL=${containerGatewayEndpoint(env)}`];
116+
}

‎src/lib/aws/awslocal.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import type { DockerApiClient } from "../docker/docker.client";
2+
import { awslocalExecEnv, buildsClientUrl } from "./awslocal-endpoint.logic";
3+
4+
/**
5+
* Runs `awslocal <args>` inside the LocalStack container, pointed at the gateway's
6+
* container-side address (see `awslocal-endpoint.logic.ts`), so it works whatever host port
7+
* publishes the gateway and whatever `LOCALSTACK_HOST` says. Commands that build a URL for
8+
* the caller keep `awslocal`'s own endpoint and need no container inspect.
9+
*/
10+
export async function execAwslocal(
11+
dockerClient: DockerApiClient,
12+
containerId: string,
13+
args: string[]
14+
) {
15+
const containerEnv = buildsClientUrl(args)
16+
? undefined
17+
: (await dockerClient.inspectContainer(containerId)).env;
18+
return dockerClient.executeInContainer(containerId, ["awslocal", ...args], undefined, {
19+
env: awslocalExecEnv(containerEnv, args),
20+
});
21+
}

0 commit comments

Comments
 (0)