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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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 DownExpand 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