Skip to content
Merged
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=...
46 changes: 43 additions & 3 deletions src/core/dev/codezip.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdir, mkdtemp, rm } from "node:fs/promises";
import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { join, relative } from "node:path";
import { InputValidationError } from "../../errors";
import type { ProjectRuntime } from "../../projectSchemas/runtime";
import type { DevEvent, DevServerInput } from "../../handlers/project/dev/types";
import type { ProcessEvent, ProcessStreamer, StreamProcessOptions } from "../../io";
Expand All @@ -21,7 +22,11 @@ afterEach(async () => {
});

function runtime(
overrides: { entrypoint?: string; protocol?: ProjectRuntime["protocol"] } = {},
overrides: {
codeLocation?: string;
entrypoint?: string;
protocol?: ProjectRuntime["protocol"];
} = {},
): ProjectRuntime {
return {
name: "hello_world",
Expand All @@ -37,6 +42,12 @@ async function projectRoot(withNodeModules = false): Promise<string> {
const root = await mkdtemp(join(tmpdir(), "agentcore-codezip-"));
tempDirectories.push(root);
await mkdir(join(root, "app", "hello-world"), { recursive: true });
await mkdir(join(root, "app", "hello-world", "src"));
await Promise.all(
["main.py", "index.js", "src/main.py", "src/index.ts"].map((path) =>
writeFile(join(root, "app", "hello-world", path), ""),
),
);
if (withNodeModules) {
await mkdir(join(root, "app", "hello-world", "node_modules"));
}
Expand Down Expand Up @@ -81,6 +92,35 @@ describe("CodeZipDevRunner", () => {
);
});

test("rejects code and entrypoint paths outside the project root", async () => {
const root = await projectRoot();
const outside = await mkdtemp(join(tmpdir(), "agentcore-codezip-outside-"));
tempDirectories.push(outside);
await writeFile(join(outside, "main.py"), "");
await symlink(outside, join(root, "linked"), process.platform === "win32" ? "junction" : "dir");
await symlink(
outside,
join(root, "app", "hello-world", "linked"),
process.platform === "win32" ? "junction" : "dir",
);
const directory = join(root, "app", "hello-world");

const unsafeRuntimes = [
runtime({ codeLocation: relative(root, outside) }),
runtime({ codeLocation: "linked" }),
runtime({ entrypoint: relative(directory, join(outside, "main.py")) }),
runtime({ entrypoint: join("linked", "main.py") }),
];

for (const projectRuntime of unsafeRuntimes) {
const { calls, runner } = harness();
const result = collect(runner.run(input(root, projectRuntime)));
await expect(result).rejects.toBeInstanceOf(InputValidationError);
await expect(result).rejects.toThrow("must be within the project root");
expect(calls).toHaveLength(0);
}
});

test("runs HTTP Python entrypoints with uvicorn", async () => {
const root = await projectRoot();
const { calls, runner } = harness([{ type: "stdout", line: "server output" }]);
Expand Down
14 changes: 11 additions & 3 deletions src/core/dev/codezip.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { existsSync } from "node:fs";
import { join } from "node:path";
import { join, resolve } from "node:path";
import { InputValidationError } from "../../errors";
import type { DevEvent, DevRunner, DevServerInput } from "../../handlers/project/dev/types";
import { streamProcess, type ProcessStreamer, type StreamProcessOptions } from "../../io";
import { isDirectory, isFile, resolvePathWithinProject } from "./path";

type CodeZipDevRunnerConfig = {
streamProcess?: ProcessStreamer;
Expand All @@ -16,12 +17,19 @@ export class CodeZipDevRunner implements DevRunner {
}

public async *run(input: DevServerInput): AsyncGenerator<DevEvent, void> {
const directory = join(input.projectRoot, input.runtime.codeLocation);
if (!existsSync(directory)) {
const directory = resolve(input.projectRoot, input.runtime.codeLocation);
if (!isDirectory(directory)) {
throw new InputValidationError(`runtime code directory not found: ${directory}`);
}
resolvePathWithinProject(input.projectRoot, directory, "runtime code directory");

const [entrypoint] = input.runtime.entrypoint.split(":");
const entrypointPath = resolve(directory, entrypoint!);
if (!isFile(entrypointPath)) {
throw new InputValidationError(`runtime entrypoint not found: ${entrypointPath}`);
}
resolvePathWithinProject(input.projectRoot, entrypointPath, "runtime entrypoint");

if (!entrypoint!.endsWith(".py") && !existsSync(join(directory, "node_modules"))) {
yield { type: "status", message: "Installing Node dependencies with npm" };
yield* this.streamProcess(["npm", "install"], {
Expand Down
126 changes: 109 additions & 17 deletions src/core/dev/container.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
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, stat, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { parseEnv } from "node:util";
import { InputValidationError, InvalidEnvironmentError } from "../../errors";
import type { DevEvent, DevServerInput } from "../../handlers/project/dev/types";
import {
Expand All @@ -17,6 +18,7 @@ import { ContainerDevRunner } from "./container";
type ProcessCall = {
command: string[];
options: StreamProcessOptions;
envFile?: { path: string; contents: string; mode: number };
};

type StreamBehavior = (
Expand Down Expand Up @@ -61,11 +63,20 @@ function harness(
config: {
available?: (tool: string, probeArgs?: string[]) => Promise<boolean>;
stream?: StreamBehavior;
awsDirectory?: string;
processEnv?: NodeJS.ProcessEnv;
} = {},
) {
const calls: ProcessCall[] = [];
const fakeStreamProcess: ProcessStreamer = async function* (command, options) {
calls.push({ command, options });
const call: ProcessCall = { command, options };
calls.push(call);
const envFileFlag = command.indexOf("--env-file");
if (envFileFlag >= 0) {
const path = command[envFileFlag + 1]!;
const [contents, metadata] = await Promise.all([readFile(path, "utf8"), stat(path)]);
call.envFile = { path, contents, mode: metadata.mode & 0o777 };
}
if (config.stream) yield* config.stream(command, options);
};
return {
Expand All @@ -77,6 +88,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 @@ -154,7 +170,10 @@ describe("ContainerDevRunner", () => {
".",
]);
expect(build.options.cwd).toBe(root);
expect(build.options.env).toBe(process.env);
expect(build.options.env).toEqual({
AWS_ACCESS_KEY_ID: "test-access-key",
AWS_SECRET_ACCESS_KEY: "test-secret-key",
});
expect(build.options.redactedCommand).toContain("AGENT_NAME=<redacted>");
expect(build.options.redactedCommand).toContain("TARGET=<redacted>");
expect(build.options.redactedCommand?.join(" ")).not.toContain("hello-world");
Expand Down Expand Up @@ -188,18 +207,63 @@ describe("ContainerDevRunner", () => {
containerName(root),
"-p",
`127.0.0.1:3000:${containerPort}`,
"-e",
"API_KEY=super-secret",
"-e",
`PORT=${containerPort}`,
"-e",
"LOCAL_DEV=1",
...(protocol === "MCP" ? ["-e", "FASTMCP_PORT=8000"] : []),
"--env-file",
run.envFile!.path,
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).toEqual({
AWS_ACCESS_KEY_ID: "test-access-key",
AWS_SECRET_ACCESS_KEY: "test-secret-key",
});
expect(parseEnv(run.envFile!.contents)).toEqual({
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" } : {}),
});
if (process.platform !== "win32") expect(run.envFile!.mode).toBe(0o600);
await expect(readFile(run.envFile!.path, "utf8")).rejects.toThrow();
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).not.toContain("AWS_PROFILE");
expect(run.command).not.toContain("AWS_CONFIG_FILE");
expect(parseEnv(run.envFile!.contents)).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 +308,7 @@ describe("ContainerDevRunner", () => {
);
});

test("keeps app variables out of the container CLI environment", async () => {
test("keeps app variables out of the container CLI control environment", async () => {
const projectRuntime = runtime();
const root = await projectRoot(projectRuntime);
const { calls, runner } = harness();
Expand All @@ -254,9 +318,10 @@ 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).not.toContain("DOCKER_HOST");
expect(run.command.join(" ")).not.toContain("tcp://application-value");
expect(run.options.env?.DOCKER_HOST).toBeUndefined();
expect(parseEnv(run.envFile!.contents).DOCKER_HOST).toBe("tcp://application-value");
});

test("selects the first tool that supports container builds", async () => {
Expand Down Expand Up @@ -409,6 +474,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
Loading
Loading