Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion docs/AZURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,16 @@
- Bicep templates need the `bicep` binary on your `PATH` (for example `brew install bicep` or `winget install Microsoft.Bicep`).
- Relative file paths in commands resolve against `LOCALSTACK_AZ_WORKDIR`, by default the directory the MCP client starts the server in.
- `rest` calls the emulator: give it a relative URL. An absolute URL must name a local host; a `management.azure.com` URL is turned into a relative one.
- Only `rest` URLs are checked: an endpoint given in a command, such as `--blob-endpoint` or a connection string, is used as it is.
- `az` reaches only the emulator: see [What `az` can reach](#what-az-can-reach).
- The Docker image does not include the Azure CLI yet: run the server with npx or from source to use the Azure tool.

## What `az` can reach

The agent writes the commands, and a command can name any endpoint: `--blob-endpoint`, a connection string, a `rest` URL. `az` would send that endpoint the file the command reads, with a key from the command. So every `az` run goes through an egress guard, a proxy on `127.0.0.1` that the tool starts for that run and points `HTTPS_PROXY` and `HTTP_PROXY` at.

- It relays only to the emulator: `localhost.localstack.cloud` and every name under it, `localhost`, `127.0.0.1` and `::1`.
- It relays only to the emulator's ports: `LOCALSTACK_PORT`, 443 and the external-service range (`EXTERNAL_SERVICE_PORTS_START` to `_END`, by default 4510 to 4560). Other local services, such as a Docker API on `localhost:2375`, stay out of reach.
- It sends those names to `127.0.0.1` itself, so no DNS answer decides where a request goes, and routers that block LocalStack's DNS answers do not matter.
- Every other request is refused, and the tool's answer names the host.

It covers what honours `HTTPS_PROXY` and `HTTP_PROXY`: `az` itself, the Azure SDKs and MSAL, and Bicep. It does not cover programs that open connections of their own, such as the Docker daemon behind `az acr login`, or a database client behind `flexible-server connect`.
18 changes: 18 additions & 0 deletions src/lib/azure/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@ const config = (env: NodeJS.ProcessEnv) => getAzureConfig(env, deps);

describe("getAzureConfig", () => {
test("defaults: the gateway every tool uses, the emulator's ARM host, a per-port profile", () => {
const servicePorts = Array.from({ length: 51 }, (_, i) => 4510 + i);
expect(config({})).toEqual({
healthBaseUrl: "http://localhost:4566",
port: 4566,
endpoint: "https://azure.localhost.localstack.cloud:4566",
emulatorPorts: [4566, 443, ...servicePorts],
configDir: "/home/u/.localstack/azure/mcp-config-4566",
homeDir: "/home/u/.localstack/azure/mcp-config-4566/home",
tmpDir: "/home/u/.localstack/azure/mcp-config-4566/tmp",
Expand All @@ -33,6 +35,22 @@ describe("getAzureConfig", () => {
expect(config({ LOCALSTACK_PORT: "abc" }).errors[0]).toContain("LOCALSTACK_PORT");
});

test("the guard's ports follow LOCALSTACK_PORT and the external-service range the start action uses", () => {
const ports = (env: NodeJS.ProcessEnv) => config(env).emulatorPorts;
expect(ports({ LOCALSTACK_PORT: "4666", EXTERNAL_SERVICE_PORTS_START: "5000" })).toEqual([
4666,
443,
...Array.from({ length: 51 }, (_, i) => 5000 + i),
]);
expect(
ports({ LOCALSTACK_EXTERNAL_SERVICE_PORTS_START: "6000", EXTERNAL_SERVICE_PORTS_END: "6001" })
).toEqual([4566, 443, 6000, 6001]);
// An invalid range falls back to the default one (the start action reports it).
expect(
ports({ EXTERNAL_SERVICE_PORTS_START: "9", EXTERNAL_SERVICE_PORTS_END: "5" })
).toHaveLength(53);
});

test("the extension dir is the user's own: AZURE_EXTENSION_DIR, else their config dir's", () => {
expect(config({ AZURE_EXTENSION_DIR: "~/ext" }).extensionDir).toBe("/home/u/ext");
expect(config({ AZURE_CONFIG_DIR: "/cfg" }).extensionDir).toBe("/cfg/cliextensions");
Expand Down
22 changes: 20 additions & 2 deletions src/lib/azure/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export interface AzureConfig {
port: number;
/** The ARM endpoint `az` talks to: https://azure.localhost.localstack.cloud:<port>. */
endpoint: string;
/** The ports the egress guard relays to: the gateway's, 443 and the external-service range. */
emulatorPorts: number[];
/** The tool's own Azure CLI config dir; `az` never sees the user's ~/.azure. */
configDir: string;
/** The child's private home and temp dir, inside the config dir. */
Expand All @@ -33,8 +35,9 @@ export interface AzureConfigDeps {
}

/**
* The hosts an absolute `rest` URL may name: LocalStack's public DNS names for 127.0.0.1
* (localhost.localstack.cloud and its subdomains) and the loopback names and addresses.
* The hosts an absolute `rest` URL may name, and the egress guard relays to: LocalStack's
* public DNS names for 127.0.0.1 (localhost.localstack.cloud and its subdomains) and the
* loopback names and addresses.
*/
export function isLocalHost(host: string): boolean {
const h = host
Expand Down Expand Up @@ -83,6 +86,20 @@ export function getAzureConfig(
};

const port = wholeNumber("LOCALSTACK_PORT", "4566", 1, 65535);
// The external-service range as the start action publishes it (an invalid one is reported there).
const rangeSetting = (name: string) =>
Number(setting(name) ?? setting(`LOCALSTACK_${name}`) ?? NaN);
let first = rangeSetting("EXTERNAL_SERVICE_PORTS_START");
first = Number.isInteger(first) ? first : 4510;
let last = rangeSetting("EXTERNAL_SERVICE_PORTS_END");
last = Number.isInteger(last) ? last : first + 50;
if (first < 1 || last > 65535 || last < first || last - first >= 1000)
[first, last] = [4510, 4560];
const emulatorPorts = [
port,
443,
...Array.from({ length: last - first + 1 }, (_, i) => first + i),
];

const userProfile = userPath(setting("AZURE_CONFIG_DIR") ?? P.join(home, ".azure"));
const configSetting = setting("LOCALSTACK_AZ_CONFIG_DIR");
Expand Down Expand Up @@ -110,6 +127,7 @@ export function getAzureConfig(
healthBaseUrl: `http://${setting("LOCALSTACK_HOSTNAME") ?? "localhost"}:${port}`,
port,
endpoint: `https://azure.localhost.localstack.cloud:${port}`,
emulatorPorts: [...new Set(emulatorPorts)],
configDir,
homeDir: P.join(configDir, "home"),
tmpDir: P.join(configDir, "tmp"),
Expand Down
134 changes: 134 additions & 0 deletions src/lib/azure/egress-guard.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import http from "http";
import net, { type AddressInfo } from "net";
import { startEgressGuard, type EgressGuard } from "./egress-guard";

// A local echo server stands in for the emulator; the guard relays to it on its port only.
let echo: net.Server;
let origin: http.Server;
let emulatorPort: number;
let httpPort: number;
let guard: EgressGuard;
const dialled: Array<[number, string]> = [];

const listen = (server: net.Server) =>
new Promise<number>((resolve) =>
server.listen(0, "127.0.0.1", () => resolve((server.address() as AddressInfo).port))
);
const guardPort = () => Number(new URL(guard.env.HTTPS_PROXY).port);

/** Sends CONNECT through the guard; resolves with its status and the open socket. */
function connectThrough(authority: string): Promise<{ status: number; socket: net.Socket }> {
return new Promise((resolve, reject) => {
const socket = net.connect(guardPort(), "127.0.0.1");
socket.once("error", reject);
let head = "";
const onData = (chunk: Buffer) => {
head += chunk.toString("latin1");
if (!head.includes("\r\n\r\n")) return;
socket.off("data", onData);
resolve({ status: Number(head.split(" ")[1]), socket });
};
socket.on("data", onData);
socket.write(`CONNECT ${authority} HTTP/1.1\r\nHost: ${authority}\r\n\r\n`);
});
}

/** Sends a plain-HTTP proxy request (absolute URI) through the guard. */
function getThrough(url: string): Promise<{ status: number; body: string }> {
return new Promise((resolve, reject) => {
const req = http.request({ host: "127.0.0.1", port: guardPort(), path: url }, (res) => {
let body = "";
res.on("data", (c) => (body += c));
res.on("end", () => resolve({ status: res.statusCode ?? 0, body }));
});
req.on("error", reject);
req.end();
});
}

beforeAll(async () => {
echo = net.createServer((socket) => socket.pipe(socket));
emulatorPort = await listen(echo);
origin = http.createServer((req, res) => res.end(`host=${req.headers.host} path=${req.url}`));
httpPort = await listen(origin);
});
afterAll(() => {
echo.close();
origin.close();
});
beforeEach(async () => {
dialled.length = 0;
guard = await startEgressGuard({
ports: [emulatorPort, httpPort],
connect: (port, host) => {
dialled.push([port, host]);
return net.connect({ port, host, allowHalfOpen: true });
},
});
});
afterEach(() => guard.close());

test("points az's HTTPS_PROXY and HTTP_PROXY at itself", () => {
expect(guard.env.HTTPS_PROXY).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/);
expect(guard.env.HTTP_PROXY).toBe(guard.env.HTTPS_PROXY);
});

test("tunnels to the emulator's names on loopback, without DNS", async () => {
for (const host of ["azure.localhost.localstack.cloud", "LOCALHOST", "127.1", "[::1]"]) {
const { status, socket } = await connectThrough(`${host}:${emulatorPort}`);
if (host === "[::1]") {
// Relayed to ::1, where the echo server does not listen: the relay was attempted.
expect([200, 502]).toContain(status);
socket.destroy();
continue;
}
expect(status).toBe(200);
const echoed = new Promise<string>((resolve) => socket.once("data", (d) => resolve(String(d))));
socket.write("ping");
expect(await echoed).toBe("ping");
socket.destroy();
}
expect(dialled.map(([, host]) => host)).toEqual(["127.0.0.1", "127.0.0.1", "127.0.0.1", "::1"]);
expect(guard.refused()).toEqual([]);
});

test("refuses other hosts, and emulator names on other ports, and records them", async () => {
const refused = [
"storage.evil.example:443",
"10.0.0.5:" + emulatorPort,
"localhost.localstack.cloud.evil.example:443",
"localhost:2375",
];
for (const authority of refused) {
const { status, socket } = await connectThrough(authority);
expect(status).toBe(403);
socket.destroy();
}
expect(guard.refused()).toEqual([
"storage.evil.example",
"10.0.0.5",
"localhost.localstack.cloud.evil.example",
"localhost:2375",
]);
expect(dialled).toEqual([]);
});

test("plain HTTP: forwards an absolute URI to an emulator name, refuses anything else", async () => {
const ok = await getThrough(`http://acct.blob.localhost.localstack.cloud:${httpPort}/c/b?x=1`);
expect(ok).toEqual({
status: 200,
body: `host=acct.blob.localhost.localstack.cloud:${httpPort} path=/c/b?x=1`,
});
expect((await getThrough("http://evil.example/upload")).status).toBe(403);
expect((await getThrough("/not-absolute")).status).toBe(400);
expect(guard.refused()).toEqual(["evil.example"]);
});

test("a malformed CONNECT gets 400; close() ends an open tunnel", async () => {
expect((await connectThrough("no-port-here")).status).toBe(400);
const { status, socket } = await connectThrough(`localhost:${emulatorPort}`);
expect(status).toBe(200);
const closed = new Promise((resolve) => socket.once("close", resolve));
await guard.close();
await closed;
});
Loading
Loading