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
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
"agentcore": "./dist/index.js"
},
"main": "./dist/index.js",
"engines": {
"node": ">=20.12.0"
Comment thread
tejaskash marked this conversation as resolved.
},
"files": [
"dist"
],
Expand Down
6 changes: 3 additions & 3 deletions src/assets/templates/shared/env.local.template
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Environment variables for local development.
# `agentcore dev` loads this file into your agent's process. Values here
# override anything the CLI injects. This file is gitignored — keep secrets
# out of version control, but they are safe here.
# `agentcore project dev` loads this file into your agent's process. Values here
# override injected values except PORT, FASTMCP_PORT, and LOCAL_DEV, which the
# CLI owns. This file is gitignored — keep secrets out of version control.
#
# Example:
# MY_API_KEY=...
106 changes: 94 additions & 12 deletions src/core/dev/container.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, test } from "bun:test";
import { createHash } from "node:crypto";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { InputValidationError, InvalidEnvironmentError } from "../../errors";
Expand Down Expand Up @@ -61,6 +61,8 @@ function harness(
config: {
available?: (tool: string, probeArgs?: string[]) => Promise<boolean>;
stream?: StreamBehavior;
awsDirectory?: string;
processEnv?: NodeJS.ProcessEnv;
} = {},
) {
const calls: ProcessCall[] = [];
Expand All @@ -77,6 +79,11 @@ function harness(
(async (tool) => {
return tool === "docker";
}),
awsDirectory: config.awsDirectory ?? join(tmpdir(), "agentcore-container-no-aws"),
processEnv: config.processEnv ?? {
AWS_ACCESS_KEY_ID: "test-access-key",
AWS_SECRET_ACCESS_KEY: "test-secret-key",
},
}),
};
}
Expand Down Expand Up @@ -189,17 +196,65 @@ describe("ContainerDevRunner", () => {
"-p",
`127.0.0.1:3000:${containerPort}`,
"-e",
"API_KEY=super-secret",
"AWS_ACCESS_KEY_ID",
"-e",
"AWS_SECRET_ACCESS_KEY",
"-e",
`PORT=${containerPort}`,
"API_KEY",
"-e",
"LOCAL_DEV=1",
...(protocol === "MCP" ? ["-e", "FASTMCP_PORT=8000"] : []),
"PORT",
"-e",
"LOCAL_DEV",
...(protocol === "MCP" ? ["-e", "FASTMCP_PORT"] : []),
imageTag(root),
]);
expect(run.options.env).toBe(process.env);
expect(run.options.redactedCommand).toContain("API_KEY=<redacted>");
expect(run.options.redactedCommand?.join(" ")).not.toContain("super-secret");
expect(run.options.env).toMatchObject({
AWS_ACCESS_KEY_ID: "test-access-key",
AWS_SECRET_ACCESS_KEY: "test-secret-key",
API_KEY: "super-secret",
PORT: String(containerPort),
LOCAL_DEV: "1",
...(protocol === "MCP" ? { FASTMCP_PORT: "8000" } : {}),
});
expect(run.command.join(" ")).not.toContain("super-secret");
expect(run.command.join(" ")).not.toContain("test-secret-key");
});

test("uses a shared AWS config and rejects missing credentials", async () => {
const projectRuntime = runtime();
const root = await projectRoot(projectRuntime);
const awsDirectory = join(root, ".aws");
await mkdir(awsDirectory);
await writeFile(join(awsDirectory, "config"), "[profile sandbox]\nregion=us-east-1\n");
const { calls, runner } = harness({
awsDirectory,
processEnv: { AWS_PROFILE: "sandbox", AWS_REGION: "us-east-1" },
});

await collect(runner.run(input(root, projectRuntime)));

const run = commandCall(calls, "run");
expect(run.command).toContain(`${awsDirectory}:/aws-config:ro`);
expect(run.command).toContain("AWS_PROFILE");
expect(run.command).toContain("AWS_CONFIG_FILE");
expect(run.options.env).toMatchObject({
AWS_PROFILE: "sandbox",
AWS_REGION: "us-east-1",
AWS_CONFIG_FILE: "/aws-config/config",
AWS_SHARED_CREDENTIALS_FILE: "/aws-config/credentials",
});
expect(run.command.join(" ")).not.toContain("sandbox");

const missing = harness({
awsDirectory: join(root, "missing-aws"),
processEnv: {},
});
const missingCredentials = collect(missing.runner.run(input(root, projectRuntime)));
await expect(missingCredentials).rejects.toBeInstanceOf(InvalidEnvironmentError);
await expect(missingCredentials).rejects.toThrow(
"Unable to resolve AWS credentials for the container",
);
expect(missing.calls).toHaveLength(0);
});

test("preserves an existing build context .dockerignore", async () => {
Expand Down Expand Up @@ -244,7 +299,7 @@ describe("ContainerDevRunner", () => {
);
});

test("keeps app variables out of the container CLI environment", async () => {
test("supplies app variable values through the container CLI environment", async () => {
const projectRuntime = runtime();
const root = await projectRoot(projectRuntime);
const { calls, runner } = harness();
Expand All @@ -254,9 +309,9 @@ describe("ContainerDevRunner", () => {
await collect(runner.run(runInput));

const run = commandCall(calls, "run");
expect(run.command).toContain("DOCKER_HOST=tcp://application-value");
expect(run.options.env).toBe(process.env);
expect(run.options.redactedCommand).toContain("DOCKER_HOST=<redacted>");
expect(run.command).toContain("DOCKER_HOST");
expect(run.command.join(" ")).not.toContain("tcp://application-value");
expect(run.options.env?.DOCKER_HOST).toBe("tcp://application-value");
});

test("selects the first tool that supports container builds", async () => {
Expand Down Expand Up @@ -409,6 +464,33 @@ describe("ContainerDevRunner", () => {
expect(calls.map(({ command }) => command[1])).toEqual(["rm"]);
});

test("rejects build contexts outside the project root, including symlinks", async () => {
const root = await mkdtemp(join(tmpdir(), "agentcore-container-"));
const outside = await mkdtemp(join(tmpdir(), "agentcore-container-outside-"));
tempDirectories.push(root, outside);
await symlink(outside, join(root, "linked"), process.platform === "win32" ? "junction" : "dir");
const probes: string[] = [];

for (const buildContextPath of ["..", "linked"]) {
const { calls, runner } = harness({
available: async (tool) => {
probes.push(tool);
return true;
},
});

const escapedContext = collect(runner.run(input(root, runtime({ buildContextPath }))));
await expect(escapedContext).rejects.toBeInstanceOf(InputValidationError);
await expect(escapedContext).rejects.toThrow(
"container build context must be within the project root",
Comment thread
tejaskash marked this conversation as resolved.
);
expect(calls).toHaveLength(0);
}

expect(probes).toHaveLength(0);
await expect(readFile(join(outside, ".dockerignore"), "utf8")).rejects.toThrow();
});

test("rejects a build context that is not a directory", async () => {
const root = await mkdtemp(join(tmpdir(), "agentcore-container-"));
tempDirectories.push(root);
Expand Down
89 changes: 57 additions & 32 deletions src/core/dev/container.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createHash } from "node:crypto";
import { existsSync, statSync, writeFileSync } from "node:fs";
import { join, resolve } from "node:path";
import { existsSync, realpathSync, statSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { isAbsolute, join, relative, resolve, sep } from "node:path";
import { InputValidationError, InvalidEnvironmentError } from "../../errors";
import type { DevEvent, DevRunner, DevServerInput } from "../../handlers/project/dev/types";
import {
Expand All @@ -10,8 +11,17 @@ import {
type ProcessStreamer,
type StreamProcessOptions,
} from "../../io";
import { DEV_PORTS } from "./port";

const CONTAINER_TOOLS = ["docker", "podman", "finch"] as const;
const AWS_ENV_KEYS = [
"AWS_ACCESS_KEY_ID",
"AWS_SECRET_ACCESS_KEY",
"AWS_SESSION_TOKEN",
"AWS_REGION",
"AWS_DEFAULT_REGION",
"AWS_PROFILE",
] as const;
const CLEANUP_TIMEOUT_MS = 2_000;
const DOCKERFILE_NAME = "Dockerfile";
const CONTAINER_RUNTIME_INSTALL_HINT =
Expand Down Expand Up @@ -44,15 +54,21 @@ type ToolAvailable = typeof toolAvailable;
type ContainerDevRunnerConfig = {
streamProcess?: ProcessStreamer;
toolAvailable?: ToolAvailable;
awsDirectory?: string;
processEnv?: NodeJS.ProcessEnv;
};

export class ContainerDevRunner implements DevRunner {
private readonly streamProcess: ProcessStreamer;
private readonly toolAvailable: ToolAvailable;
private readonly awsDirectory: string;
private readonly processEnv: NodeJS.ProcessEnv;

constructor(config: ContainerDevRunnerConfig = {}) {
this.streamProcess = config.streamProcess ?? streamProcess;
this.toolAvailable = config.toolAvailable ?? toolAvailable;
this.awsDirectory = config.awsDirectory ?? join(homedir(), ".aws");
this.processEnv = config.processEnv ?? process.env;
}

public async *run(input: DevServerInput): AsyncGenerator<DevEvent, void> {
Expand All @@ -65,12 +81,36 @@ export class ContainerDevRunner implements DevRunner {
throw new InputValidationError(`container build context directory not found: ${context}`);
}

const canonicalContext = realpathSync(context);
const relativeContext = relative(realpathSync(input.projectRoot), canonicalContext);
if (
relativeContext === ".." ||
relativeContext.startsWith(`..${sep}`) ||
isAbsolute(relativeContext)
Comment thread
tejaskash marked this conversation as resolved.
) {
throw new InputValidationError(
`container build context must be within the project root: ${canonicalContext}`,
);
}

const dockerfile = input.runtime.dockerfile ?? DOCKERFILE_NAME;
const dockerfilePath = join(context, dockerfile);
if (!isFile(dockerfilePath)) {
throw new InputValidationError(`container Dockerfile not found: ${dockerfilePath}`);
}

const hasAwsCredentials = Boolean(
Comment thread
tejaskash marked this conversation as resolved.
(input.env?.AWS_ACCESS_KEY_ID ?? this.processEnv.AWS_ACCESS_KEY_ID) &&
(input.env?.AWS_SECRET_ACCESS_KEY ?? this.processEnv.AWS_SECRET_ACCESS_KEY),
);
const hasAwsConfig = existsSync(this.awsDirectory);
if (!hasAwsCredentials && !hasAwsConfig) {
throw new InvalidEnvironmentError(
"Unable to resolve AWS credentials for the container. Configure AWS credentials " +
"or set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, then retry.",
);
}

const tool = await this.resolveContainerTool(input.signal);
input.signal.throwIfAborted();
if (input.runtime.buildContextPath) {
Expand Down Expand Up @@ -116,23 +156,24 @@ export class ContainerDevRunner implements DevRunner {
yield { type: "status", message: `Building image with ${tool}` };
yield* this.streamProcess(buildCommand, buildOptions);

const containerPort = portForProtocol(input.runtime.protocol);
const forwardedEnv: Record<string, string> = {
...input.env,
const containerPort = DEV_PORTS[input.runtime.protocol ?? "HTTP"];
const forwardedEnv: Record<string, string> = {};
for (const key of AWS_ENV_KEYS) {
if (this.processEnv[key]) forwardedEnv[key] = this.processEnv[key];
}
Object.assign(forwardedEnv, input.env, {
PORT: String(containerPort),
LOCAL_DEV: "1",
};
});
if (input.runtime.protocol === "MCP") {
forwardedEnv.FASTMCP_PORT = String(containerPort);
}
const envFlags = Object.entries(forwardedEnv).flatMap(([key, value]) => [
"-e",
`${key}=${value}`,
]);
const redactedEnvFlags = Object.keys(forwardedEnv).flatMap((key) => [
"-e",
`${key}=<redacted>`,
]);
const awsMount = hasAwsConfig ? ["-v", `${this.awsDirectory}:/aws-config:ro`] : [];
if (awsMount.length) {
forwardedEnv.AWS_CONFIG_FILE = "/aws-config/config";
Comment thread
tejaskash marked this conversation as resolved.
forwardedEnv.AWS_SHARED_CREDENTIALS_FILE = "/aws-config/credentials";
}
const envFlags = Object.keys(forwardedEnv).flatMap((key) => ["-e", key]);
const runCommand = [
tool,
"run",
Expand All @@ -141,6 +182,7 @@ export class ContainerDevRunner implements DevRunner {
containerName,
"-p",
`127.0.0.1:${input.port}:${containerPort}`,
...awsMount,
...envFlags,
imageTag,
];
Expand All @@ -149,18 +191,7 @@ export class ContainerDevRunner implements DevRunner {
try {
yield* this.streamProcess(runCommand, {
cwd: context,
env: process.env,
redactedCommand: [
tool,
"run",
"--rm",
"--name",
containerName,
"-p",
`127.0.0.1:${input.port}:${containerPort}`,
...redactedEnvFlags,
imageTag,
],
env: { ...this.processEnv, ...forwardedEnv },
signal: input.signal,
});
} finally {
Expand Down Expand Up @@ -204,12 +235,6 @@ export class ContainerDevRunner implements DevRunner {
}
}

function portForProtocol(protocol: DevServerInput["runtime"]["protocol"]): number {
if (protocol === "MCP") return 8000;
if (protocol === "A2A") return 9000;
return 8080;
}

function isDirectory(path: string): boolean {
try {
return statSync(path).isDirectory();
Expand Down
49 changes: 49 additions & 0 deletions src/core/dev/port.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { describe, expect, test } from "bun:test";
import type { PortChecker } from "../../io";
import { PortInUseError, resolveDevPort } from "./port";

const signal = new AbortController().signal;

describe("resolveDevPort", () => {
test.each([
["HTTP", 8080],
["AGUI", 8080],
["MCP", 8000],
["A2A", 9000],
] as const)("uses the %s default", async (protocol, port) => {
expect(await resolveDevPort(protocol, undefined, async () => true, signal)).toEqual({
port,
requestedPort: port,
});
});

test("walks up from occupied defaults", async () => {
const checked: number[] = [];
const check: PortChecker = async (port) => {
checked.push(port);
return port === 8002;
};

expect(await resolveDevPort("MCP", undefined, check, signal)).toEqual({
port: 8002,
requestedPort: 8000,
});
expect(checked).toEqual([8000, 8001, 8002]);
});

test("accepts a free explicit port and rejects an occupied one", async () => {
expect(await resolveDevPort("A2A", 4567, async () => true, signal)).toEqual({
port: 4567,
requestedPort: 4567,
});
const occupied = resolveDevPort("A2A", 4567, async () => false, signal);
await expect(occupied).rejects.toBeInstanceOf(PortInUseError);
await expect(occupied).rejects.toThrow("lsof -i :4567");
});

test("bounds the default search", async () => {
await expect(resolveDevPort("HTTP", undefined, async () => false, signal)).rejects.toThrow(
"No free port found in range 8080-8179",
);
});
});
Loading
Loading