From e9ec0dbdb42e5b3b6c29ec6440e4c16c8889cbe4 Mon Sep 17 00:00:00 2001 From: Varun Gunda Date: Thu, 19 Nov 2026 13:52:16 -0800 Subject: [PATCH 01/10] fix(build): decrypt only the .env.local keys box egress routes use Build decrypted every .env.local entry before it planned the box egress credentials, so one undecryptable entry stopped a valid build, even when no route used it or the shell set its variable. Build now reads .env.local with the same select and overrides options that the credential provisioner uses. It reads only each route's env:// variable and the reserved variable of the route's credential, and skips each variable that the shell sets to a non-blank value. A blank shell value does not win, so build still reads that variable from the file. An undecryptable entry that a route uses still stops the build with the decrypt error. --- src/core/project/boxNetworkWriters.ts | 29 ++++++++- src/core/project/boxProfileCredentials.ts | 9 +++ .../project/manager.boxCredentials.test.ts | 65 ++++++++++++++++++- src/core/project/manager.tsx | 10 ++- 4 files changed, 108 insertions(+), 5 deletions(-) diff --git a/src/core/project/boxNetworkWriters.ts b/src/core/project/boxNetworkWriters.ts index 424f96765..d96d052f8 100644 --- a/src/core/project/boxNetworkWriters.ts +++ b/src/core/project/boxNetworkWriters.ts @@ -26,8 +26,13 @@ import { boxBedrockPolicy, boxMemoryPolicy, } from "./boxMemory"; -import { planBoxProfileCredentials, type BoxKeySources } from "./boxProfileCredentials"; -import type { BoxEnvRoute } from "./boxProfileEgress"; +import type { ReadEnvFileOptions } from "../../io/envFile"; +import { + boxKeyVariables, + planBoxProfileCredentials, + type BoxKeySources, +} from "./boxProfileCredentials"; +import { hasValue, type BoxEnvRoute } from "./boxProfileEgress"; import { boxTelemetryPolicy, boxTelemetryPolicyFile, @@ -184,6 +189,26 @@ export const credentialsWriter: BoxNetworkWriter = { }, }; +/** + * How build reads `.env.local` for {@link credentialsWriter}, the only writer that reads it: only + * the variables its routes use, and none that `env` sets to a value, because a value set in `env` + * wins. An entry that is not read is not decrypted, so it cannot stop the build. Undefined when no + * route reads a key, and build then does not read the file. + */ +export function boxKeyReads( + networks: readonly BoxNetwork[], + env: NodeJS.ProcessEnv, +): ReadEnvFileOptions | undefined { + const routes = uniqueRoutes(networks); + if (routes.length === 0) return undefined; + const variables = boxKeyVariables(routes); + return { + select: (name) => variables.has(name), + // A blank value in `env` does not win, so build reads that variable from the file instead. + overrides: Object.fromEntries(Object.entries(env).filter(([, value]) => hasValue(value))), + }; +} + function uniqueRoutes(networks: readonly BoxNetwork[]): BoxEnvRoute[] { const routes: BoxEnvRoute[] = []; for (const route of networks.flatMap((network) => network.envRoutes)) { diff --git a/src/core/project/boxProfileCredentials.ts b/src/core/project/boxProfileCredentials.ts index d8d1af7b7..248c59777 100644 --- a/src/core/project/boxProfileCredentials.ts +++ b/src/core/project/boxProfileCredentials.ts @@ -46,6 +46,15 @@ export function boxEgressCredentialName( return holder?.name ?? route; } +/** + * The variables {@link planBoxProfileCredentials} looks up in its key sources for `routes`: each + * route's `env://` variable, and the reserved variable of the credential named for the route. + * Build reads only these from `.env.local`, so an entry no route uses cannot stop it. + */ +export function boxKeyVariables(routes: readonly BoxEnvRoute[]): Set { + return new Set(routes.flatMap(({ route, variable }) => [variable, credentialEnvVarName(route)])); +} + /** * For each `[egress.] secret.ref = "env://VAR"` route of the box profile, make sure the * project declares an `ApiKeyCredentialProvider` named ``, and that `.env.local` holds its diff --git a/src/core/project/manager.boxCredentials.test.ts b/src/core/project/manager.boxCredentials.test.ts index 715cf773f..340a2c292 100644 --- a/src/core/project/manager.boxCredentials.test.ts +++ b/src/core/project/manager.boxCredentials.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, test } from "bun:test"; -import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { appendFile, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { FsProjectManager } from "./manager"; @@ -10,6 +10,7 @@ import { BOX_PROFILE_FILE } from "./templates/boxProfile"; import { boxShowOf, FakeBoxProfileResolver } from "./boxProfileResolver-test-support"; import { resolveRuntimeTemplateShortcut } from "../../handlers/project/shortcuts"; import { credentialEnvVarName } from "../../projectSchemas/credential"; +import { ENC_PREFIX } from "../../secrets/cipher"; import { createSilentLogger, TestIdentityClient } from "../../testing"; // A box template: only it writes the box profile whose env:// secrets build provisions. @@ -21,6 +22,8 @@ const GITHUB_SHOWN = boxShowOf({ egress: { github: { destinations: ["api.github.com"], secret: { ref: "env://GITHUB_TOKEN" } } }, }); const RESERVED = credentialEnvVarName("github"); +/** A stored secret in the encrypted format that no key on this machine decrypts. */ +const UNDECRYPTABLE = `${ENC_PREFIX}${Buffer.alloc(48).toString("base64")}`; const originalCwd = process.cwd(); const directories: string[] = []; @@ -86,6 +89,17 @@ async function drain(generator: AsyncGenerator): Promise { + await mkdir(join(root, "agentcore"), { recursive: true }); + await appendFile(join(root, ENV_LOCAL_RELATIVE_PATH), `\n${line}\n`); +} + +/** The key build stored under the credential's reserved variable; reads no other entry. */ +async function storedKey(root: string): Promise { + return (await new EnvLocalFile(root).read({ select: (name) => name === RESERVED }))[RESERVED]; +} + async function specOf(root: string): Promise> { return JSON.parse(await readFile(join(root, "agentcore", "agentcore.json"), "utf8")); } @@ -162,6 +176,55 @@ describe("FsProjectManager.build: box env:// credentials", () => { expect(await credentials()).toEqual(before); }); + test("builds when .env.local holds an undecryptable entry that no route uses", async () => { + const { subject, built } = manager({ GITHUB_TOKEN: "ghp_shell" }); + const created = await project(subject, GITHUB_PROFILE); + await appendEnvLocal(created.rootPath, `OTHER_API_KEY='${UNDECRYPTABLE}'`); + + await drain(subject.build(created)); + + expect(built[0]?.spec.credentials).toContainEqual({ + authorizerType: "ApiKeyCredentialProvider", + name: "github", + }); + expect(await storedKey(created.rootPath)).toBe("ghp_shell"); + }); + + test("builds when the shell sets the variable of an undecryptable .env.local entry", async () => { + const { subject, built } = manager({ GITHUB_TOKEN: "ghp_shell" }); + const created = await project(subject, GITHUB_PROFILE); + await appendEnvLocal(created.rootPath, `GITHUB_TOKEN='${UNDECRYPTABLE}'`); + + await drain(subject.build(created)); + + expect(built[0]?.spec.credentials).toContainEqual({ + authorizerType: "ApiKeyCredentialProvider", + name: "github", + }); + expect(await storedKey(created.rootPath)).toBe("ghp_shell"); + }); + + for (const [label, env] of [ + ["the shell does not set it", {}], + ["the shell sets it blank", { GITHUB_TOKEN: " " }], + ] as const) { + test(`stops on an undecryptable .env.local entry that a route uses when ${label}`, async () => { + const { subject, built } = manager(env); + const created = await project(subject, GITHUB_PROFILE); + await appendEnvLocal(created.rootPath, `GITHUB_TOKEN='${UNDECRYPTABLE}'`); + const spec = await readFile(join(created.rootPath, "agentcore", "agentcore.json"), "utf8"); + + await expect(drain(subject.build(created))).rejects.toThrow( + "Could not decrypt a stored secret in agentcore/.env.local. " + + "Restore the original encryption key or re-add the credential.", + ); + expect(built).toEqual([]); + expect(await readFile(join(created.rootPath, "agentcore", "agentcore.json"), "utf8")).toBe( + spec, + ); + }); + } + test("stops on a box profile that does not parse, and changes nothing", async () => { const { subject } = manager({ GITHUB_TOKEN: "ghp_shell" }); const created = await project(subject, "[egress.github\n"); diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index c3f66e453..5fa9ad68b 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -58,7 +58,12 @@ import { boxGatewayIamWarnings, type BoxNetwork } from "./boxNetwork"; import { boxNetworkFailureMessage, readBoxNetworks } from "./boxNetworkSource"; import { DEFAULT_REGION, regionFromConfigFile } from "../region"; import { BoxCliProfileResolver, type BoxProfileResolver } from "./boxProfileResolver"; -import { BOX_NETWORK_WRITERS, boxNetworkEdits, writeBoxNetworkFiles } from "./boxNetworkWriters"; +import { + BOX_NETWORK_WRITERS, + boxKeyReads, + boxNetworkEdits, + writeBoxNetworkFiles, +} from "./boxNetworkWriters"; import { createProjectTree } from "./templates/project"; import { boxProfilePath, @@ -1609,11 +1614,12 @@ export class FsProjectManager implements ProjectManager { throw new InputValidationError(boxNetworkFailureMessage(networks, command)); } const envLocal = new EnvLocalFile(project.rootPath); + const keyReads = boxKeyReads(networks, this.processEnv); const edits = boxNetworkEdits(BOX_NETWORK_WRITERS, networks, { spec: project.spec, projectRoot: project.rootPath, env: this.processEnv, - envLocal: networks.length > 0 ? await envLocal.read() : {}, + envLocal: keyReads ? await envLocal.read(keyReads) : {}, }); const messages = [...edits.messages]; let result = project; From 1a96f719fea39e51e55859fb8735bc06d18c07a8 Mon Sep 17 00:00:00 2001 From: Varun Gunda Date: Thu, 19 Nov 2026 13:50:47 -0800 Subject: [PATCH 02/10] fix(build): seed a box egress key over a blank reserved variable in .env.local With AGENTCORE_CREDENTIAL_GITHUB= in .env.local and GITHUB_TOKEN set, build added the github credential but insertIfNew skipped the blank entry, so the next deploy could not provision it. insertIfNew takes an optional keep rule. Build passes boxKeyIsSet, the same rule the credential plan uses to decide which keys need a seed, so the two cannot disagree again. A blank key gets the seed at its line. A key the user set stays. The writer decrypts only the existing keys it must check, so an unused secret that cannot be decrypted does not block the seed write. --- src/core/project/boxProfileCredentials.ts | 13 ++++-- src/core/project/envLocal.test.ts | 40 ++++++++++++++++ src/core/project/envLocal.ts | 46 ++++++++++++++++++- .../project/manager.boxCredentials.test.ts | 39 ++++++++++++++++ src/core/project/manager.tsx | 4 +- 5 files changed, 136 insertions(+), 6 deletions(-) diff --git a/src/core/project/boxProfileCredentials.ts b/src/core/project/boxProfileCredentials.ts index 248c59777..e7fca1c93 100644 --- a/src/core/project/boxProfileCredentials.ts +++ b/src/core/project/boxProfileCredentials.ts @@ -20,6 +20,13 @@ export type BoxKeySources = { envLocal: Readonly>; }; +/** + * Whether a variable holds a key: set, and not blank. {@link planBoxProfileCredentials} uses it to + * decide that a reserved variable needs a seed, and build passes it as `keep` to + * `EnvLocalFile.insertIfNew`, so a blank entry that build seeds is also the one it overwrites. + */ +export const boxKeyIsSet = hasValue; + /** What {@link planBoxProfileCredentials} did with the box profile's `env://` routes. */ export type BoxCredentialPlan = { /** One message for each credential added, and for each route skipped for a reason to report. */ @@ -103,12 +110,12 @@ export function planBoxProfileCredentials( /** Stores the route's key under `credential`'s reserved variable; false when there is none. */ const seed = ({ variable }: BoxEnvRoute, credential: string): boolean => { const key = credentialEnvVarName(credential); - if (hasValue(sources.env[key]) || hasValue(sources.envLocal[key])) return true; + if (boxKeyIsSet(sources.env[key]) || boxKeyIsSet(sources.envLocal[key])) return true; if (entries.some((entry) => entry.key === key)) return true; - const value = hasValue(sources.env[variable]) + const value = boxKeyIsSet(sources.env[variable]) ? sources.env[variable] : sources.envLocal[variable]; - if (!hasValue(value)) return false; + if (!boxKeyIsSet(value)) return false; entries.push({ key, value, diff --git a/src/core/project/envLocal.test.ts b/src/core/project/envLocal.test.ts index c8d4d1b28..0dbd78045 100644 --- a/src/core/project/envLocal.test.ts +++ b/src/core/project/envLocal.test.ts @@ -242,6 +242,46 @@ test("preserves an existing secret and envelope when the key is skipped or a nei expect(await file.read()).toEqual({ MODEL_API_KEY: "old-value" }); }); +test("keep: fills an existing key it rejects in place, and leaves the keys it keeps", async () => { + const root = await tempRoot(); + const file = new EnvLocalFile(root); + await file.insertIfNew([{ key: "KEPT_API_KEY", value: "user-value", comment: "kept" }]); + const raw = await Bun.file(file.path).text(); + await Bun.write(file.path, `# user comment\nBLANK_API_KEY=\n${raw}OTHER=1\n`); + const keep = (value: string) => value.trim() !== ""; + + const result = await file.insertIfNew( + [ + { key: "BLANK_API_KEY", value: "seeded", comment: "seeded" }, + { key: "KEPT_API_KEY", value: "ignored", comment: "ignored" }, + { key: "NEW", value: "added", comment: "new" }, + ], + { keep }, + ); + + expect(result).toEqual({ written: ["BLANK_API_KEY", "NEW"], skipped: ["KEPT_API_KEY"] }); + expect(await file.read()).toEqual({ + BLANK_API_KEY: "seeded", + KEPT_API_KEY: "user-value", + OTHER: "1", + NEW: "added", + }); + const after = await Bun.file(file.path).text(); + expect(after.startsWith("# user comment\nBLANK_API_KEY=")).toBe(true); + expect(after).not.toContain("seeded"); +}); + +test("without keep, an existing blank key is skipped", async () => { + const root = await tempRoot(); + const file = new EnvLocalFile(root); + await Bun.write(file.path, "BLANK_API_KEY=\n"); + + const result = await file.insertIfNew([{ key: "BLANK_API_KEY", value: "v", comment: "c" }]); + + expect(result).toEqual({ written: [], skipped: ["BLANK_API_KEY"] }); + expect(await file.read()).toEqual({ BLANK_API_KEY: "" }); +}); + test("encrypts quote-bearing secrets before serializing them and migrates remaining secrets on removal", async () => { const root = await tempRoot(); const file = new EnvLocalFile(root); diff --git a/src/core/project/envLocal.ts b/src/core/project/envLocal.ts index 1500cb395..7e5b643e6 100644 --- a/src/core/project/envLocal.ts +++ b/src/core/project/envLocal.ts @@ -42,8 +42,15 @@ export class EnvLocalFile { * Appends entries, creating the file when missing. Keys that already exist * are left unchanged so user-managed values survive re-runs. Returns the keys * written and those skipped. + * + * `options.keep` decides from an existing key's decrypted value whether that + * key stays unchanged; without it, every existing key does. A key that `keep` + * rejects gets the entry's value in place, and counts as written. */ - async insertIfNew(entries: EnvLocalEntry[]): Promise<{ written: string[]; skipped: string[] }> { + async insertIfNew( + entries: EnvLocalEntry[], + options: { keep?: (value: string) => boolean } = {}, + ): Promise<{ written: string[]; skipped: string[] }> { const existing = await this.readOrNull(); if (existing !== null) await this.enforcePermissions(); const existingKeys = new Set( @@ -52,13 +59,42 @@ export class EnvLocalFile { .map((line) => KEY_LINE.exec(line)?.[1]) .filter((key) => key !== undefined), ); + const { keep } = options; + // Decrypt only the existing keys that `keep` must check, so a secret this + // call does not touch cannot block the write. + const checked = new Set( + entries.map((entry) => entry.key).filter((key) => existingKeys.has(key)), + ); + const values: Record = + keep !== undefined && existing !== null && checked.size > 0 + ? await this.secrets.decrypt( + Object.fromEntries( + Object.entries(parseEnv(existing) as Record).filter(([key]) => + checked.has(key), + ), + ), + ) + : {}; const written: string[] = []; const skipped: string[] = []; + const replacements = new Map(); let content = existing ?? ""; for (const entry of entries) { if (existingKeys.has(entry.key)) { - skipped.push(entry.key); + const value = values[entry.key]; + if ( + keep === undefined || + value === undefined || + keep(value) || + replacements.has(entry.key) + ) { + skipped.push(entry.key); + continue; + } + const encrypted = await this.secrets.encrypt({ [entry.key]: entry.value ?? "" }); + replacements.set(entry.key, formatValue(encrypted[entry.key])); + written.push(entry.key); continue; } const separator = content === "" || content.endsWith("\n") ? "" : "\n"; @@ -66,6 +102,12 @@ export class EnvLocalFile { content += `${separator}# ${entry.comment}\n${entry.key}=${formatValue(encrypted[entry.key])}\n`; written.push(entry.key); } + if (replacements.size > 0) { + content = content.replace(ENV_ENTRY, (span, prefix: string, key: string) => { + const value = replacements.get(key); + return value === undefined ? span : `${prefix}${value}`; + }); + } content = await this.encryptContent(content); if (content !== (existing ?? "")) { diff --git a/src/core/project/manager.boxCredentials.test.ts b/src/core/project/manager.boxCredentials.test.ts index 340a2c292..72be485ba 100644 --- a/src/core/project/manager.boxCredentials.test.ts +++ b/src/core/project/manager.boxCredentials.test.ts @@ -157,6 +157,33 @@ describe("FsProjectManager.build: box env:// credentials", () => { expect((await new EnvLocalFile(created.rootPath).read())[RESERVED]).toBe("ghp_stored"); }); + test("seeds the key over a blank reserved variable in .env.local", async () => { + const { subject, built } = manager({ GITHUB_TOKEN: "ghp_shell" }); + const created = await project(subject, GITHUB_PROFILE); + await writeFile(join(created.rootPath, ENV_LOCAL_RELATIVE_PATH), `${RESERVED}=\n`); + + const messages = await drain(subject.build(created)); + + // Build adds the credential, so the key it reads on deploy must be set, not left blank. + expect(built[0]?.spec.credentials).toContainEqual({ + authorizerType: "ApiKeyCredentialProvider", + name: "github", + }); + expect((await new EnvLocalFile(created.rootPath).read())[RESERVED]).toBe("ghp_shell"); + expect(messages).toContain(`writing ${RESERVED} to ${ENV_LOCAL_RELATIVE_PATH}`); + }); + + test("keeps a reserved variable that .env.local already sets", async () => { + const { subject } = manager({ GITHUB_TOKEN: "ghp_shell" }); + const created = await project(subject, GITHUB_PROFILE); + await writeFile(join(created.rootPath, ENV_LOCAL_RELATIVE_PATH), `${RESERVED}=ghp_user\n`); + + const messages = await drain(subject.build(created)); + + expect((await new EnvLocalFile(created.rootPath).read())[RESERVED]).toBe("ghp_user"); + expect(messages).not.toContain(`writing ${RESERVED} to ${ENV_LOCAL_RELATIVE_PATH}`); + }); + test("adds no credential, and says which variable to set, when the key is in neither place", async () => { const { subject } = manager({}); const created = await project(subject, GITHUB_PROFILE); @@ -190,6 +217,18 @@ describe("FsProjectManager.build: box env:// credentials", () => { expect(await storedKey(created.rootPath)).toBe("ghp_shell"); }); + test("seeds a blank reserved variable when .env.local also holds an unused undecryptable entry", async () => { + const { subject } = manager({ GITHUB_TOKEN: "ghp_shell" }); + const created = await project(subject, GITHUB_PROFILE); + await writeFile(join(created.rootPath, ENV_LOCAL_RELATIVE_PATH), `${RESERVED}=\n`); + await appendEnvLocal(created.rootPath, `OTHER_API_KEY='${UNDECRYPTABLE}'`); + + const messages = await drain(subject.build(created)); + + expect(await storedKey(created.rootPath)).toBe("ghp_shell"); + expect(messages).toContain(`writing ${RESERVED} to ${ENV_LOCAL_RELATIVE_PATH}`); + }); + test("builds when the shell sets the variable of an undecryptable .env.local entry", async () => { const { subject, built } = manager({ GITHUB_TOKEN: "ghp_shell" }); const created = await project(subject, GITHUB_PROFILE); diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index 5fa9ad68b..520fdc521 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -64,6 +64,7 @@ import { boxNetworkEdits, writeBoxNetworkFiles, } from "./boxNetworkWriters"; +import { boxKeyIsSet } from "./boxProfileCredentials"; import { createProjectTree } from "./templates/project"; import { boxProfilePath, @@ -1653,7 +1654,8 @@ export class FsProjectManager implements ProjectManager { } writeBoxNetworkFiles(project.rootPath, edits.files); if (edits.envLocal.length > 0) { - const { written } = await envLocal.insertIfNew([...edits.envLocal]); + // A blank entry is one the plan seeds, so it gets the seed rather than being skipped. + const { written } = await envLocal.insertIfNew([...edits.envLocal], { keep: boxKeyIsSet }); for (const key of written) messages.push(`writing ${key} to ${ENV_LOCAL_RELATIVE_PATH}`); } const warnings = networks.flatMap((network) => [ From 8766abba0ce1cc2c6ce98a23762d241376c238b0 Mon Sep 17 00:00:00 2001 From: Varun Gunda Date: Fri, 20 Nov 2026 17:22:56 -0800 Subject: [PATCH 03/10] fix(build): read no .env.local key for a box route the credential planner skips boxKeyVariables now drops a model-provider route and a route whose variable an existing credential reserves, through the same predicate planBoxProfileCredentials uses. --- src/core/project/boxNetworkWriters.ts | 3 +- .../project/boxProfileCredentials.test.ts | 23 ++++++- src/core/project/boxProfileCredentials.ts | 45 +++++++++--- .../project/manager.boxCredentials.test.ts | 69 +++++++++++++++---- src/core/project/manager.tsx | 2 +- 5 files changed, 116 insertions(+), 26 deletions(-) diff --git a/src/core/project/boxNetworkWriters.ts b/src/core/project/boxNetworkWriters.ts index 04647d0dc..57bde3d3e 100644 --- a/src/core/project/boxNetworkWriters.ts +++ b/src/core/project/boxNetworkWriters.ts @@ -203,11 +203,12 @@ export const credentialsWriter: BoxNetworkWriter = { */ export function boxKeyReads( networks: readonly BoxNetwork[], + spec: ProjectSpec, env: NodeJS.ProcessEnv, ): ReadEnvFileOptions | undefined { const routes = uniqueRoutes(networks); if (routes.length === 0) return undefined; - const variables = boxKeyVariables(routes); + const variables = boxKeyVariables(spec.credentials, routes); return { select: (name) => variables.has(name), // A blank value in `env` does not win, so build reads that variable from the file instead. diff --git a/src/core/project/boxProfileCredentials.test.ts b/src/core/project/boxProfileCredentials.test.ts index 6c5ec7081..72e9095bb 100644 --- a/src/core/project/boxProfileCredentials.test.ts +++ b/src/core/project/boxProfileCredentials.test.ts @@ -1,5 +1,9 @@ import { describe, expect, test } from "bun:test"; -import { planBoxProfileCredentials, type BoxKeySources } from "./boxProfileCredentials"; +import { + boxKeyVariables, + planBoxProfileCredentials, + type BoxKeySources, +} from "./boxProfileCredentials"; import type { BoxEnvRoute } from "./boxProfileEgress"; import { ENV_LOCAL_RELATIVE_PATH } from "./envLocal"; import { credentialEnvVarName } from "../../projectSchemas/credential"; @@ -276,3 +280,20 @@ describe("planBoxProfileCredentials", () => { ]); }); }); + +describe("boxKeyVariables", () => { + test("holds the variables of each route the planner looks up a key for", () => { + expect(boxKeyVariables([], [GITHUB])).toEqual(new Set(["GITHUB_TOKEN", RESERVED])); + }); + + test("skips a model-provider route and a route whose variable a credential reserves", () => { + const reserved = credentialEnvVarName("agentOpenAIApiKey"); + + const variables = boxKeyVariables( + [{ authorizerType: "ApiKeyCredentialProvider", name: "agentOpenAIApiKey" }], + [route("openai", "OPENAI_API_KEY"), route("my-llm", reserved)], + ); + + expect(variables).toEqual(new Set()); + }); +}); diff --git a/src/core/project/boxProfileCredentials.ts b/src/core/project/boxProfileCredentials.ts index 08b562233..182bb1cac 100644 --- a/src/core/project/boxProfileCredentials.ts +++ b/src/core/project/boxProfileCredentials.ts @@ -47,12 +47,39 @@ export function boxEgressCredentialName( } /** - * The variables {@link planBoxProfileCredentials} looks up in its key sources for `routes`: each - * route's `env://` variable, and the reserved variable of the credential named for the route. - * Build reads only these from `.env.local`, so an entry no route uses cannot stop it. + * Whether {@link planBoxProfileCredentials} skips `route` before it looks up any key, because + * something else holds the key: a credential whose variables `reserved` holds reserves the route's + * variable, or the route is a model-provider route as `agentcore create` writes it (`openai`, + * `anthropic`, `gemini` or `openai-compatible`, reading the provider variable such as + * `OPENAI_API_KEY`), whose key is the variable LiteLLM reads. */ -export function boxKeyVariables(routes: readonly BoxEnvRoute[]): Set { - return new Set(routes.flatMap(({ route, variable }) => [variable, credentialEnvVarName(route)])); +function boxRouteKeyHeldElsewhere( + { route, variable }: BoxEnvRoute, + reserved: { has(variable: string): boolean }, +): boolean { + return ( + reserved.has(variable) || + (MODEL_PROVIDER_EGRESS_ROUTES.has(route) && MODEL_PROVIDER_KEY_VARIABLES.has(variable)) + ); +} + +/** + * The variables {@link planBoxProfileCredentials} can look up in its key sources for `routes` in a + * project with `credentials`: for each route it does not skip first, the route's `env://` variable + * and the reserved variable of the credential named for the route. Build reads only these from + * `.env.local`, so an entry no route uses cannot stop it. A credential that the planner adds for + * one route can reserve the variable of a later route, which the set then still holds. + */ +export function boxKeyVariables( + credentials: readonly Credential[], + routes: readonly BoxEnvRoute[], +): Set { + const reserved = new Set(credentials.flatMap(credentialEnvironmentVariableNames)); + return new Set( + routes + .filter((route) => !boxRouteKeyHeldElsewhere(route, reserved)) + .flatMap(({ route, variable }) => [variable, credentialEnvVarName(route)]), + ); } /** @@ -68,10 +95,7 @@ export function boxKeyVariables(routes: readonly BoxEnvRoute[]): Set { * is kept, and gets the same message if its key has gone. * * Mutates `spec.credentials` in place, and is idempotent. It skips, with no message: - * - a route whose variable an existing credential reserves: that credential holds the key; - * - a model-provider route as `agentcore create` writes it (`openai`, `anthropic`, `gemini` or - * `openai-compatible`, reading the provider variable such as `OPENAI_API_KEY`): its key is - * the variable LiteLLM reads, not a credential; + * - a route whose key something else holds ({@link boxRouteKeyHeldElsewhere}); * - a route named for an API key credential that keeps its key in Secrets Manager. * * It skips, with a message, a route that uses a model-provider name or variable in any other way, @@ -136,10 +160,9 @@ export function planBoxProfileCredentials( for (const entry of routes) { const { route, variable } = entry; - if (reservedVars.has(variable)) continue; + if (boxRouteKeyHeldElsewhere(entry, reservedVars)) continue; const providerName = MODEL_PROVIDER_EGRESS_ROUTES.has(route); const providerVariable = MODEL_PROVIDER_KEY_VARIABLES.has(variable); - if (providerName && providerVariable) continue; const skip = (reason: string) => messages.push(`skipping box egress '${route}' (env://${variable}): ${reason}`); diff --git a/src/core/project/manager.boxCredentials.test.ts b/src/core/project/manager.boxCredentials.test.ts index 241430e58..83c3e428b 100644 --- a/src/core/project/manager.boxCredentials.test.ts +++ b/src/core/project/manager.boxCredentials.test.ts @@ -35,7 +35,10 @@ afterEach(async () => { }); /** A manager whose CDK backend records the project it builds, and runs nothing. */ -function manager(processEnv: NodeJS.ProcessEnv): { subject: FsProjectManager; built: Project[] } { +function manager( + processEnv: NodeJS.ProcessEnv, + shown = GITHUB_SHOWN, +): { subject: FsProjectManager; built: Project[] } { const built: Project[] = []; const backend: ProjectBackend = { async *build(project) { @@ -61,7 +64,7 @@ function manager(processEnv: NodeJS.ProcessEnv): { subject: FsProjectManager; bu runner: async () => {}, checkTool: async () => {}, backends: { CDK: backend }, - boxProfileResolver: new FakeBoxProfileResolver(GITHUB_SHOWN), + boxProfileResolver: new FakeBoxProfileResolver(shown), }); return { subject, built }; } @@ -85,10 +88,17 @@ async function project(subject: FsProjectManager, profile: string): Promise): Promise { - const messages: string[] = []; - for await (const event of generator) if (event.type === "step") messages.push(event.message); - return messages; +/** The step messages of `generator`, then its warnings. */ +async function drain( + generator: AsyncGenerator, +): Promise<{ steps: string[]; warnings: string[] }> { + const steps: string[] = []; + const warnings: string[] = []; + for await (const event of generator) { + if (event.type === "step") steps.push(event.message); + else if (event.type === "warning") warnings.push(event.message); + } + return { steps, warnings }; } /** Appends `line` to the project's `.env.local` as written, so no value in it is encrypted. */ @@ -112,7 +122,7 @@ describe("FsProjectManager.build: box env:// credentials", () => { const created = await project(subject, GITHUB_PROFILE); const before = await specOf(created.rootPath); - const messages = await drain(subject.build(created)); + const { steps } = await drain(subject.build(created)); const after = await specOf(created.rootPath); expect(after.credentials).toEqual([ @@ -125,7 +135,7 @@ describe("FsProjectManager.build: box env:// credentials", () => { expect(others(after)).toEqual(others(before)); const stored = await new EnvLocalFile(created.rootPath).read(); expect(stored[RESERVED]).toBe("ghp_shell"); - expect(messages).toContain(`writing ${RESERVED} to ${ENV_LOCAL_RELATIVE_PATH}`); + expect(steps).toContain(`writing ${RESERVED} to ${ENV_LOCAL_RELATIVE_PATH}`); expect(built[0]?.spec.credentials).toContainEqual({ authorizerType: "ApiKeyCredentialProvider", name: "github", @@ -139,14 +149,29 @@ describe("FsProjectManager.build: box env:// credentials", () => { const spec = await readFile(join(created.rootPath, "agentcore", "agentcore.json"), "utf8"); const reread = await subject.resolve({ filePath: created.rootPath }); - const messages = await drain(subject.build(reread!)); + const { steps, warnings } = await drain(subject.build(reread!)); - expect(messages.filter((message) => message.includes("github"))).toEqual([]); + expect([...steps, ...warnings].filter((message) => message.includes("github"))).toEqual([]); expect(await readFile(join(created.rootPath, "agentcore", "agentcore.json"), "utf8")).toBe( spec, ); }); + test("a second build finds the key stored only under the credential's reserved variable", async () => { + const { subject: first } = manager({ GITHUB_TOKEN: "ghp_shell" }); + const created = await project(first, GITHUB_PROFILE); + await drain(first.build(created)); + const { subject } = manager({}); + const reread = await subject.resolve({ filePath: created.rootPath }); + + const { steps, warnings } = await drain(subject.build(reread!)); + + expect( + [...steps, ...warnings].filter((message) => message.includes("env://GITHUB_TOKEN")), + ).toEqual([]); + expect(await storedKey(created.rootPath)).toBe("ghp_shell"); + }); + test("seeds the key that agentcore dev stored in .env.local under the box variable", async () => { const { subject } = manager({}); const created = await project(subject, GITHUB_PROFILE); @@ -167,9 +192,9 @@ describe("FsProjectManager.build: box env:// credentials", () => { .credentials; const before = await credentials(); - const messages = await drain(subject.build(created)); + const { steps } = await drain(subject.build(created)); - expect(messages).toContain( + expect(steps).toContain( "not adding credential 'github' for box egress 'env://GITHUB_TOKEN': GITHUB_TOKEN is not " + `set here or in ${ENV_LOCAL_RELATIVE_PATH}, so deploy could not provision it. ` + `Set GITHUB_TOKEN, or ${RESERVED}, and build again`, @@ -203,6 +228,26 @@ describe("FsProjectManager.build: box env:// credentials", () => { expect(await storedKey(created.rootPath)).toBe("ghp_shell"); }); + test("builds when .env.local holds an undecryptable key of a model-provider route", async () => { + const { subject, built } = manager( + {}, + boxShowOf({ + egress: { + openai: { destinations: ["api.openai.com"], secret: { ref: "env://OPENAI_API_KEY" } }, + }, + }), + ); + const created = await project( + subject, + '[egress.openai]\ndestinations = ["api.openai.com"]\nsecret.ref = "env://OPENAI_API_KEY"\n', + ); + await appendEnvLocal(created.rootPath, `OPENAI_API_KEY='${UNDECRYPTABLE}'`); + + await drain(subject.build(created)); + + expect(built).toHaveLength(1); + }); + test("builds when the shell sets the variable of an undecryptable .env.local entry", async () => { const { subject, built } = manager({ GITHUB_TOKEN: "ghp_shell" }); const created = await project(subject, GITHUB_PROFILE); diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index 22facb7a8..3d49ecfc1 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -1684,7 +1684,7 @@ export class FsProjectManager implements ProjectManager { throw new InputValidationError(boxNetworkFailureMessage(networks, command)); } const envLocal = new EnvLocalFile(project.rootPath); - const keyReads = boxKeyReads(networks, this.processEnv); + const keyReads = boxKeyReads(networks, project.spec, this.processEnv); const edits = boxNetworkEdits(BOX_NETWORK_WRITERS, networks, { spec: project.spec, projectRoot: project.rootPath, From 57bfb0d07bb8db108dcdee613c94a08a56cb188f Mon Sep 17 00:00:00 2001 From: Varun Gunda Date: Fri, 20 Nov 2026 17:23:31 -0800 Subject: [PATCH 04/10] test(build): generate the two stop cases of the box credential build with test.each --- src/core/project/manager.boxCredentials.test.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/core/project/manager.boxCredentials.test.ts b/src/core/project/manager.boxCredentials.test.ts index 83c3e428b..20278dacf 100644 --- a/src/core/project/manager.boxCredentials.test.ts +++ b/src/core/project/manager.boxCredentials.test.ts @@ -262,11 +262,12 @@ describe("FsProjectManager.build: box env:// credentials", () => { expect(await storedKey(created.rootPath)).toBe("ghp_shell"); }); - for (const [label, env] of [ + test.each([ ["the shell does not set it", {}], ["the shell sets it blank", { GITHUB_TOKEN: " " }], - ] as const) { - test(`stops on an undecryptable .env.local entry that a route uses when ${label}`, async () => { + ])( + "stops on an undecryptable .env.local entry that a route uses when %s", + async (_label, env: NodeJS.ProcessEnv) => { const { subject, built } = manager(env); const created = await project(subject, GITHUB_PROFILE); await appendEnvLocal(created.rootPath, `GITHUB_TOKEN='${UNDECRYPTABLE}'`); @@ -280,8 +281,8 @@ describe("FsProjectManager.build: box env:// credentials", () => { expect(await readFile(join(created.rootPath, "agentcore", "agentcore.json"), "utf8")).toBe( spec, ); - }); - } + }, + ); test("stops on a box profile that does not parse, and changes nothing", async () => { const { subject } = manager({ GITHUB_TOKEN: "ghp_shell" }); From da4f1df3d489467d4ebf8b0d66eea87ef49843be Mon Sep 17 00:00:00 2001 From: Varun Gunda Date: Fri, 20 Nov 2026 17:24:22 -0800 Subject: [PATCH 05/10] refactor(build): drop the no-routes guard of boxKeyReads With no routes, select rejects every name, so the read decrypts nothing and returns no entry. --- src/core/project/boxNetworkWriters.ts | 10 ++++------ src/core/project/manager.boxCredentials.test.ts | 10 ++++++++++ src/core/project/manager.tsx | 3 +-- 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/core/project/boxNetworkWriters.ts b/src/core/project/boxNetworkWriters.ts index 57bde3d3e..e75dfe00b 100644 --- a/src/core/project/boxNetworkWriters.ts +++ b/src/core/project/boxNetworkWriters.ts @@ -198,17 +198,15 @@ export const credentialsWriter: BoxNetworkWriter = { /** * How build reads `.env.local` for {@link credentialsWriter}, the only writer that reads it: only * the variables its routes use, and none that `env` sets to a value, because a value set in `env` - * wins. An entry that is not read is not decrypted, so it cannot stop the build. Undefined when no - * route reads a key, and build then does not read the file. + * wins. An entry that is not read is not decrypted, so it cannot stop the build. With no routes, + * no entry is read. */ export function boxKeyReads( networks: readonly BoxNetwork[], spec: ProjectSpec, env: NodeJS.ProcessEnv, -): ReadEnvFileOptions | undefined { - const routes = uniqueRoutes(networks); - if (routes.length === 0) return undefined; - const variables = boxKeyVariables(spec.credentials, routes); +): ReadEnvFileOptions { + const variables = boxKeyVariables(spec.credentials, uniqueRoutes(networks)); return { select: (name) => variables.has(name), // A blank value in `env` does not win, so build reads that variable from the file instead. diff --git a/src/core/project/manager.boxCredentials.test.ts b/src/core/project/manager.boxCredentials.test.ts index 20278dacf..2a5734739 100644 --- a/src/core/project/manager.boxCredentials.test.ts +++ b/src/core/project/manager.boxCredentials.test.ts @@ -248,6 +248,16 @@ describe("FsProjectManager.build: box env:// credentials", () => { expect(built).toHaveLength(1); }); + test("builds with no box routes when .env.local holds an undecryptable entry", async () => { + const { subject, built } = manager({}, boxShowOf({})); + const created = await project(subject, ""); + await appendEnvLocal(created.rootPath, `GITHUB_TOKEN='${UNDECRYPTABLE}'`); + + await drain(subject.build(created)); + + expect(built).toHaveLength(1); + }); + test("builds when the shell sets the variable of an undecryptable .env.local entry", async () => { const { subject, built } = manager({ GITHUB_TOKEN: "ghp_shell" }); const created = await project(subject, GITHUB_PROFILE); diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index 3d49ecfc1..9212848a7 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -1684,12 +1684,11 @@ export class FsProjectManager implements ProjectManager { throw new InputValidationError(boxNetworkFailureMessage(networks, command)); } const envLocal = new EnvLocalFile(project.rootPath); - const keyReads = boxKeyReads(networks, project.spec, this.processEnv); const edits = boxNetworkEdits(BOX_NETWORK_WRITERS, networks, { spec: project.spec, projectRoot: project.rootPath, env: this.processEnv, - envLocal: keyReads ? await envLocal.read(keyReads) : {}, + envLocal: await envLocal.read(boxKeyReads(networks, project.spec, this.processEnv)), }); const messages = [...edits.messages]; let result = project; From 3d64c0088b7934fa7aec8c0597ed60498d8ef286 Mon Sep 17 00:00:00 2001 From: Varun Gunda Date: Fri, 20 Nov 2026 17:26:42 -0800 Subject: [PATCH 06/10] fix(build): report the box credential skip and missing-key messages as warnings planBoxProfileCredentials returns them in a separate warnings list, and build emits them as warning events. Progress messages stay steps. --- src/core/project/boxNetworkWriters.ts | 8 ++++++ .../project/boxProfileCredentials.test.ts | 25 ++++++++++--------- src/core/project/boxProfileCredentials.ts | 22 ++++++++++------ .../project/manager.boxCredentials.test.ts | 5 ++-- src/core/project/manager.tsx | 11 +++++--- 5 files changed, 45 insertions(+), 26 deletions(-) diff --git a/src/core/project/boxNetworkWriters.ts b/src/core/project/boxNetworkWriters.ts index e75dfe00b..81e5f4825 100644 --- a/src/core/project/boxNetworkWriters.ts +++ b/src/core/project/boxNetworkWriters.ts @@ -77,6 +77,8 @@ export interface BoxNetworkEdits { readonly files?: readonly BoxNetworkFile[]; /** Entries for `.env.local`; each replaces the value it holds under that key. */ readonly envLocal?: readonly EnvLocalEntry[]; + /** Messages about what the writer could not do, for the user to act on. */ + readonly warnings?: readonly string[]; } /** What a writer reads besides the models: the project, and where build looks for each key. */ @@ -106,7 +108,9 @@ export interface CollectedEdits { readonly changedFields: readonly (keyof ProjectSpec)[]; readonly files: readonly BoxNetworkFile[]; readonly envLocal: readonly EnvLocalEntry[]; + /** The step messages of the changes to agentcore.json. */ readonly messages: readonly string[]; + readonly warnings: readonly string[]; } /** @@ -134,11 +138,13 @@ export function boxNetworkEdits( const messages: string[] = []; const files: BoxNetworkFile[] = []; const envLocal: EnvLocalEntry[] = []; + const warnings: string[] = []; for (const writer of writers) { const edits = writer.edits(networks, context); for (const change of edits.spec ?? []) messages.push(...change(spec)); files.push(...(edits.files ?? [])); envLocal.push(...(edits.envLocal ?? [])); + warnings.push(...(edits.warnings ?? [])); } const changedFields = (Object.keys(spec) as (keyof ProjectSpec)[]).filter( (field) => !isDeepStrictEqual(spec[field], context.spec[field]), @@ -150,6 +156,7 @@ export function boxNetworkEdits( files, envLocal, messages, + warnings, }; } @@ -191,6 +198,7 @@ export const credentialsWriter: BoxNetworkWriter = { }, ], envLocal: plan.entries, + warnings: plan.warnings, }; }, }; diff --git a/src/core/project/boxProfileCredentials.test.ts b/src/core/project/boxProfileCredentials.test.ts index 72e9095bb..de891c115 100644 --- a/src/core/project/boxProfileCredentials.test.ts +++ b/src/core/project/boxProfileCredentials.test.ts @@ -54,7 +54,7 @@ describe("planBoxProfileCredentials", () => { expect(s.credentials).toEqual([]); expect(plan.added).toEqual([]); expect(plan.entries).toEqual([]); - expect(plan.messages).toEqual([ + expect(plan.warnings).toEqual([ "not adding credential 'github' for box egress 'env://GITHUB_TOKEN': GITHUB_TOKEN is not set " + `here or in ${ENV_LOCAL_RELATIVE_PATH}, so deploy could not provision it. Set GITHUB_TOKEN, or ${RESERVED}, ` + "and build again", @@ -64,7 +64,7 @@ describe("planBoxProfileCredentials", () => { test("names the variable once when the route reads its own credential's variable", () => { const plan = planBoxProfileCredentials(spec(), [route("github", RESERVED)], shell({})); - expect(plan.messages[0]).toEndWith(`Set ${RESERVED} and build again`); + expect(plan.warnings[0]).toEndWith(`Set ${RESERVED} and build again`); }); test("takes the key from .env.local under the box variable when the shell has none", () => { @@ -149,7 +149,7 @@ describe("planBoxProfileCredentials", () => { const plan = planBoxProfileCredentials(spec([API_KEY]), [GITHUB], shell({})); expect(plan.added).toEqual([]); - expect(plan.messages).toEqual([ + expect(plan.warnings).toEqual([ "box egress 'github' reads env://GITHUB_TOKEN, which is not set here or in " + `${ENV_LOCAL_RELATIVE_PATH}: set GITHUB_TOKEN, or ${RESERVED}, before deploy`, ]); @@ -162,6 +162,7 @@ describe("planBoxProfileCredentials", () => { expect(planBoxProfileCredentials(s, [GITHUB], shell({ GITHUB_TOKEN: "ghp_x" }))).toEqual({ messages: [], + warnings: [], added: [], entries: [], }); @@ -176,7 +177,7 @@ describe("planBoxProfileCredentials", () => { shell({ OPENAI_API_KEY: "sk-x", ANTHROPIC_API_KEY: "sk-ant-x" }), ); - expect(plan).toEqual({ messages: [], added: [], entries: [] }); + expect(plan).toEqual({ messages: [], warnings: [], added: [], entries: [] }); expect(s.credentials).toEqual([]); }); @@ -189,7 +190,7 @@ describe("planBoxProfileCredentials", () => { shell({}), ); - expect(plan).toEqual({ messages: [], added: [], entries: [] }); + expect(plan).toEqual({ messages: [], warnings: [], added: [], entries: [] }); }); test("reports a route that uses a model-provider name or variable in another way", () => { @@ -200,7 +201,7 @@ describe("planBoxProfileCredentials", () => { ); expect(plan.added).toEqual([]); - expect(plan.messages).toEqual([ + expect(plan.warnings).toEqual([ "skipping box egress 'openai' (env://MY_KEY): 'openai' is a model-provider route; " + "agentcore create declares its key", "skipping box egress 'my-llm' (env://GEMINI_API_KEY): GEMINI_API_KEY is a model provider's " + @@ -216,7 +217,7 @@ describe("planBoxProfileCredentials", () => { ); expect(plan.added).toEqual([]); - expect(plan.messages).toEqual([ + expect(plan.warnings).toEqual([ "skipping box egress 'bad name!' (env://SOME_KEY): 'bad name!' is not a valid credential name", ]); }); @@ -229,8 +230,8 @@ describe("planBoxProfileCredentials", () => { ); expect(plan.added).toEqual([]); - expect(plan.messages).toHaveLength(1); - expect(plan.messages[0]).toContain("ends in '_CLIENT_ID'"); + expect(plan.warnings).toHaveLength(1); + expect(plan.warnings[0]).toContain("ends in '_CLIENT_ID'"); }); test("reports, but does not add, a name that derives an existing credential's variable", () => { @@ -244,7 +245,7 @@ describe("planBoxProfileCredentials", () => { expect(plan.added).toEqual([]); expect(plan.entries).toEqual([]); - expect(plan.messages).toEqual([ + expect(plan.warnings).toEqual([ "skipping box egress 'git_hub' (env://GITHUB_TOKEN): credential 'git_hub' would derive the " + "same variable, AGENTCORE_CREDENTIAL_GIT_HUB, as credential 'git-hub'", ]); @@ -258,7 +259,7 @@ describe("planBoxProfileCredentials", () => { ); expect(plan.added.map(({ name }) => name)).toEqual(["git-hub"]); - expect(plan.messages[1]).toContain("as credential 'git-hub'"); + expect(plan.warnings[0]).toContain("as credential 'git-hub'"); }); test("reports, but does not use, a route named for a credential that is not an API key", () => { @@ -274,7 +275,7 @@ describe("planBoxProfileCredentials", () => { expect(plan.added).toEqual([]); expect(plan.entries).toEqual([]); - expect(plan.messages).toEqual([ + expect(plan.warnings).toEqual([ "skipping box egress 'github' (env://GITHUB_TOKEN): credential 'github' is a " + "OAuthCredentialProvider credential, not an API key", ]); diff --git a/src/core/project/boxProfileCredentials.ts b/src/core/project/boxProfileCredentials.ts index 182bb1cac..1dc9db804 100644 --- a/src/core/project/boxProfileCredentials.ts +++ b/src/core/project/boxProfileCredentials.ts @@ -22,8 +22,13 @@ export type BoxKeySources = { /** What {@link planBoxProfileCredentials} did with the box profile's `env://` routes. */ export type BoxCredentialPlan = { - /** One message for each credential added, and for each route skipped for a reason to report. */ + /** One step message for each credential added, and for each stored key replaced. */ messages: string[]; + /** + * One warning for each route skipped for a reason to report, and for each route whose key is in + * no key source, so deploy could not provision its credential. + */ + warnings: string[]; /** The credentials added to `spec.credentials`. */ added: Credential[]; /** The `.env.local` entries that store each key under its credential's reserved variable. */ @@ -91,14 +96,14 @@ export function boxKeyVariables( * The key comes from the credential's reserved variable when it is already set, else from `VAR`, * in `sources.env` first and then in `sources.envLocal`. Deploy provisions every declared * credential and fails on one with no key, so a route whose key is in neither place gets no - * credential: only a message that names the variable to set. A credential an earlier build added - * is kept, and gets the same message if its key has gone. + * credential: only a warning that names the variable to set. A credential an earlier build added + * is kept, and gets the same warning if its key has gone. * * Mutates `spec.credentials` in place, and is idempotent. It skips, with no message: * - a route whose key something else holds ({@link boxRouteKeyHeldElsewhere}); * - a route named for an API key credential that keeps its key in Secrets Manager. * - * It skips, with a message, a route that uses a model-provider name or variable in any other way, + * It skips, with a warning, a route that uses a model-provider name or variable in any other way, * and a route whose name `agentcore credentials add` would refuse: a name that is not a valid * credential name, that ends in a credential field suffix, that derives the same variable as an * existing credential, or that names a credential which is not an API key credential. @@ -122,6 +127,7 @@ export function planBoxProfileCredentials( ); const messages: string[] = []; + const warnings: string[] = []; const added: Credential[] = []; const entries: EnvLocalEntry[] = []; /** @@ -165,7 +171,7 @@ export function planBoxProfileCredentials( const providerVariable = MODEL_PROVIDER_KEY_VARIABLES.has(variable); const skip = (reason: string) => - messages.push(`skipping box egress '${route}' (env://${variable}): ${reason}`); + warnings.push(`skipping box egress '${route}' (env://${variable}): ${reason}`); if (providerName || providerVariable) { skip( providerName @@ -179,7 +185,7 @@ export function planBoxProfileCredentials( if (existing.authorizerType !== "ApiKeyCredentialProvider") { skip(`credential '${route}' is a ${existing.authorizerType} credential, not an API key`); } else if (credentialEnvironmentVariableNames(existing).length > 0 && !seed(entry, route)) { - messages.push( + warnings.push( `box egress '${route}' reads env://${variable}, which is not set here or in ` + `${ENV_LOCAL_RELATIVE_PATH}: set ${toSet(variable, route)} before deploy`, ); @@ -210,7 +216,7 @@ export function planBoxProfileCredentials( continue; } if (!seed(entry, route)) { - messages.push( + warnings.push( `not adding credential '${route}' for box egress 'env://${variable}': ${variable} is not ` + `set here or in ${ENV_LOCAL_RELATIVE_PATH}, so deploy could not provision it. ` + `Set ${toSet(variable, route)} and build again`, @@ -227,5 +233,5 @@ export function planBoxProfileCredentials( "so deploy provisions it in AgentCore Identity", ); } - return { messages, added, entries }; + return { messages, warnings, added, entries }; } diff --git a/src/core/project/manager.boxCredentials.test.ts b/src/core/project/manager.boxCredentials.test.ts index 2a5734739..7e736e19b 100644 --- a/src/core/project/manager.boxCredentials.test.ts +++ b/src/core/project/manager.boxCredentials.test.ts @@ -192,13 +192,14 @@ describe("FsProjectManager.build: box env:// credentials", () => { .credentials; const before = await credentials(); - const { steps } = await drain(subject.build(created)); + const { steps, warnings } = await drain(subject.build(created)); - expect(steps).toContain( + expect(warnings).toContain( "not adding credential 'github' for box egress 'env://GITHUB_TOKEN': GITHUB_TOKEN is not " + `set here or in ${ENV_LOCAL_RELATIVE_PATH}, so deploy could not provision it. ` + `Set GITHUB_TOKEN, or ${RESERVED}, and build again`, ); + expect(steps.filter((message) => message.includes("not adding credential"))).toEqual([]); // Build still adds the model's target, so only the credentials stay as they were. expect(await credentials()).toEqual(before); }); diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index 9212848a7..7100f30c5 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -1726,10 +1726,13 @@ export class FsProjectManager implements ProjectManager { const { written } = await envLocal.upsert([...edits.envLocal]); for (const key of written) messages.push(`writing ${key} to ${ENV_LOCAL_RELATIVE_PATH}`); } - const warnings = networks.flatMap((network) => [ - ...network.warnings, - ...boxGatewayIamWarnings(edits.spec, network), - ]); + const warnings = [ + ...edits.warnings, + ...networks.flatMap((network) => [ + ...network.warnings, + ...boxGatewayIamWarnings(edits.spec, network), + ]), + ]; const events: ProjectEvent[] = [ ...messages.map((message) => ({ type: "step" as const, message })), ...warnings.map((message) => ({ type: "warning" as const, message })), From 1794e59382d0f32514d59b46ee099d9c1c737ee7 Mon Sep 17 00:00:00 2001 From: Varun Gunda Date: Fri, 20 Nov 2026 17:26:56 -0800 Subject: [PATCH 07/10] fix(build): say "an OAuthCredentialProvider credential" in the box egress skip warning --- src/core/project/boxProfileCredentials.test.ts | 2 +- src/core/project/boxProfileCredentials.ts | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/core/project/boxProfileCredentials.test.ts b/src/core/project/boxProfileCredentials.test.ts index de891c115..cca0c4ed1 100644 --- a/src/core/project/boxProfileCredentials.test.ts +++ b/src/core/project/boxProfileCredentials.test.ts @@ -276,7 +276,7 @@ describe("planBoxProfileCredentials", () => { expect(plan.added).toEqual([]); expect(plan.entries).toEqual([]); expect(plan.warnings).toEqual([ - "skipping box egress 'github' (env://GITHUB_TOKEN): credential 'github' is a " + + "skipping box egress 'github' (env://GITHUB_TOKEN): credential 'github' is an " + "OAuthCredentialProvider credential, not an API key", ]); }); diff --git a/src/core/project/boxProfileCredentials.ts b/src/core/project/boxProfileCredentials.ts index 1dc9db804..645a35277 100644 --- a/src/core/project/boxProfileCredentials.ts +++ b/src/core/project/boxProfileCredentials.ts @@ -183,7 +183,10 @@ export function planBoxProfileCredentials( const existing = spec.credentials.find((credential) => credential.name === route); if (existing !== undefined) { if (existing.authorizerType !== "ApiKeyCredentialProvider") { - skip(`credential '${route}' is a ${existing.authorizerType} credential, not an API key`); + const article = /^[AEIOU]/.test(existing.authorizerType) ? "an" : "a"; + skip( + `credential '${route}' is ${article} ${existing.authorizerType} credential, not an API key`, + ); } else if (credentialEnvironmentVariableNames(existing).length > 0 && !seed(entry, route)) { warnings.push( `box egress '${route}' reads env://${variable}, which is not set here or in ` + From b7afa0067ec6748485dae3fbd476cece99d2541c Mon Sep 17 00:00:00 2001 From: Varun Gunda Date: Fri, 20 Nov 2026 17:28:23 -0800 Subject: [PATCH 08/10] test(build): fold the box credential skip tests into one test.each, on schema-parsed specs The Secrets Manager fixture now uses a valid secretRef, which the old cast hid. A payment credential row covers the article of the warning. --- .../project/boxProfileCredentials.test.ts | 160 ++++++++++-------- 1 file changed, 89 insertions(+), 71 deletions(-) diff --git a/src/core/project/boxProfileCredentials.test.ts b/src/core/project/boxProfileCredentials.test.ts index cca0c4ed1..d86bcf8d4 100644 --- a/src/core/project/boxProfileCredentials.test.ts +++ b/src/core/project/boxProfileCredentials.test.ts @@ -7,10 +7,11 @@ import { import type { BoxEnvRoute } from "./boxProfileEgress"; import { ENV_LOCAL_RELATIVE_PATH } from "./envLocal"; import { credentialEnvVarName } from "../../projectSchemas/credential"; -import type { ProjectSpec } from "../../projectSchemas/project"; +import { ProjectSpecSchema, type ProjectSpec } from "../../projectSchemas/project"; -function spec(credentials: ProjectSpec["credentials"] = []): ProjectSpec { - return { credentials } as unknown as ProjectSpec; +/** A project spec with `credentials`, as the schema parses it. */ +function spec(credentials: readonly object[] = []): ProjectSpec { + return ProjectSpecSchema.parse({ name: "example", version: 2, credentials }); } const route = (name: string, variable: string): BoxEnvRoute => ({ route: name, variable }); @@ -157,8 +158,14 @@ describe("planBoxProfileCredentials", () => { test("stores nothing for an API key credential that keeps its key in Secrets Manager", () => { const s = spec([ - { ...API_KEY, secretRef: "arn:aws:secretsmanager:us-west-2:111122223333:secret:gh" }, - ] as unknown as ProjectSpec["credentials"]); + { + ...API_KEY, + secretRef: { + secretId: "arn:aws:secretsmanager:us-west-2:111122223333:secret:gh", + jsonKey: "token", + }, + }, + ]); expect(planBoxProfileCredentials(s, [GITHUB], shell({ GITHUB_TOKEN: "ghp_x" }))).toEqual({ messages: [], @@ -209,76 +216,87 @@ describe("planBoxProfileCredentials", () => { ]); }); - test("reports, but does not add, a name that is not a valid credential name", () => { - const plan = planBoxProfileCredentials( - spec(), - [route("bad name!", "SOME_KEY")], - shell({ SOME_KEY: "k" }), - ); - - expect(plan.added).toEqual([]); - expect(plan.warnings).toEqual([ - "skipping box egress 'bad name!' (env://SOME_KEY): 'bad name!' is not a valid credential name", - ]); - }); - - test("reports, but does not add, a name that ends in a credential field suffix", () => { - const plan = planBoxProfileCredentials( - spec(), - [route("github_client_id", "GITHUB_ID")], - shell({ GITHUB_ID: "k" }), - ); - - expect(plan.added).toEqual([]); - expect(plan.warnings).toHaveLength(1); - expect(plan.warnings[0]).toContain("ends in '_CLIENT_ID'"); - }); - - test("reports, but does not add, a name that derives an existing credential's variable", () => { - const s = spec([{ authorizerType: "ApiKeyCredentialProvider", name: "git-hub" }]); - - const plan = planBoxProfileCredentials( - s, - [route("git_hub", "GITHUB_TOKEN")], - shell({ GITHUB_TOKEN: "k" }), - ); - - expect(plan.added).toEqual([]); - expect(plan.entries).toEqual([]); - expect(plan.warnings).toEqual([ - "skipping box egress 'git_hub' (env://GITHUB_TOKEN): credential 'git_hub' would derive the " + + test.each<{ + label: string; + credentials: object[]; + routes: BoxEnvRoute[]; + added: string[]; + warning: string; + }>([ + { + label: "a name that is not a valid credential name", + credentials: [], + routes: [route("bad name!", "SOME_KEY")], + added: [], + warning: + "skipping box egress 'bad name!' (env://SOME_KEY): 'bad name!' is not a valid credential name", + }, + { + label: "a name that ends in a credential field suffix", + credentials: [], + routes: [route("github_client_id", "GITHUB_ID")], + added: [], + warning: + "skipping box egress 'github_client_id' (env://GITHUB_ID): 'github_client_id' ends in " + + "'_CLIENT_ID', the suffix of a credential field, so its variable " + + `${credentialEnvVarName("github_client_id")} would read as a field of another credential`, + }, + { + label: "a name that derives an existing credential's variable", + credentials: [{ authorizerType: "ApiKeyCredentialProvider", name: "git-hub" }], + routes: [route("git_hub", "GITHUB_TOKEN")], + added: [], + warning: + "skipping box egress 'git_hub' (env://GITHUB_TOKEN): credential 'git_hub' would derive the " + "same variable, AGENTCORE_CREDENTIAL_GIT_HUB, as credential 'git-hub'", - ]); - }); - - test("reports two routes in one profile that derive the same variable, and adds the first", () => { + }, + { + label: "the second of two routes in one profile that derive the same variable", + credentials: [], + routes: [route("git-hub", "GITHUB_TOKEN"), route("git_hub", "GITHUB_TOKEN")], + added: ["git-hub"], + warning: + "skipping box egress 'git_hub' (env://GITHUB_TOKEN): credential 'git_hub' would derive the " + + "same variable, AGENTCORE_CREDENTIAL_GIT_HUB, as credential 'git-hub'", + }, + { + label: "a route named for an OAuth credential", + credentials: [ + { + authorizerType: "OAuthCredentialProvider", + name: "github", + discoveryUrl: "https://example.com/.well-known/openid-configuration", + }, + ], + routes: [GITHUB], + added: [], + warning: + "skipping box egress 'github' (env://GITHUB_TOKEN): credential 'github' is an " + + "OAuthCredentialProvider credential, not an API key", + }, + { + label: "a route named for a payment credential", + credentials: [ + { authorizerType: "PaymentCredentialProvider", name: "github", provider: "StripePrivy" }, + ], + routes: [GITHUB], + added: [], + warning: + "skipping box egress 'github' (env://GITHUB_TOKEN): credential 'github' is a " + + "PaymentCredentialProvider credential, not an API key", + }, + ])("reports, but does not add, $label", ({ credentials, routes, added, warning }) => { const plan = planBoxProfileCredentials( - spec(), - [route("git-hub", "GITHUB_TOKEN"), route("git_hub", "GITHUB_TOKEN")], - shell({ GITHUB_TOKEN: "k" }), + spec(credentials), + routes, + shell({ SOME_KEY: "k", GITHUB_ID: "k", GITHUB_TOKEN: "k" }), ); - expect(plan.added.map(({ name }) => name)).toEqual(["git-hub"]); - expect(plan.warnings[0]).toContain("as credential 'git-hub'"); - }); - - test("reports, but does not use, a route named for a credential that is not an API key", () => { - const s = spec([ - { - authorizerType: "OAuthCredentialProvider", - name: "github", - discoveryUrl: "https://example.com/.well-known/openid-configuration", - }, - ] as unknown as ProjectSpec["credentials"]); - - const plan = planBoxProfileCredentials(s, [GITHUB], shell({ GITHUB_TOKEN: "k" })); - - expect(plan.added).toEqual([]); - expect(plan.entries).toEqual([]); - expect(plan.warnings).toEqual([ - "skipping box egress 'github' (env://GITHUB_TOKEN): credential 'github' is an " + - "OAuthCredentialProvider credential, not an API key", - ]); + expect(plan.added.map(({ name }) => name)).toEqual(added); + expect(plan.entries.map(({ key }) => key)).toEqual( + added.map((name) => credentialEnvVarName(name)), + ); + expect(plan.warnings).toEqual([warning]); }); }); From 3e19603a073a0f1e01f52f5df7fbb77fb45bd998 Mon Sep 17 00:00:00 2001 From: Varun Gunda Date: Fri, 20 Nov 2026 17:29:22 -0800 Subject: [PATCH 09/10] fix(build): warn when the shell's reserved credential variable differs from the box route's key Deploy provisions the reserved variable, but agentcore dev hands box the route's variable. Build now warns when the two hold different keys. --- .../project/boxProfileCredentials.test.ts | 32 +++++++++++++++++++ src/core/project/boxProfileCredentials.ts | 17 +++++++--- .../project/manager.boxCredentials.test.ts | 9 ++++++ 3 files changed, 54 insertions(+), 4 deletions(-) diff --git a/src/core/project/boxProfileCredentials.test.ts b/src/core/project/boxProfileCredentials.test.ts index d86bcf8d4..7124ac30c 100644 --- a/src/core/project/boxProfileCredentials.test.ts +++ b/src/core/project/boxProfileCredentials.test.ts @@ -146,6 +146,38 @@ describe("planBoxProfileCredentials", () => { expect(plan.entries).toEqual([]); }); + test("warns when the shell's reserved variable and the route's variable hold different keys", () => { + // Deploy provisions the reserved variable, but agentcore dev hands box the route's variable. + const plan = planBoxProfileCredentials(spec([API_KEY]), [GITHUB], { + env: { [RESERVED]: "ghp_explicit" }, + envLocal: { GITHUB_TOKEN: "ghp_dev" }, + }); + + expect(plan.warnings).toEqual([ + `box egress 'github': deploy provisions ${RESERVED} from the environment, but agentcore ` + + "dev uses env://GITHUB_TOKEN, which holds a different key, so dev and deploy can differ. " + + `Unset ${RESERVED}, or set it to the key in GITHUB_TOKEN`, + ]); + expect(plan.messages).toEqual([]); + }); + + test.each([ + ["holds the same key", { GITHUB_TOKEN: "ghp_explicit" }], + ["is not set", {}], + ["is blank", { GITHUB_TOKEN: " " }], + ])( + "does not warn about the shell's reserved variable when the route's variable %s", + (_label, routeEnv: NodeJS.ProcessEnv) => { + const plan = planBoxProfileCredentials( + spec([API_KEY]), + [GITHUB], + shell({ ...routeEnv, [RESERVED]: "ghp_explicit" }), + ); + + expect(plan.warnings).toEqual([]); + }, + ); + test("keeps an earlier build's credential and says what to set when its key has gone", () => { const plan = planBoxProfileCredentials(spec([API_KEY]), [GITHUB], shell({})); diff --git a/src/core/project/boxProfileCredentials.ts b/src/core/project/boxProfileCredentials.ts index 645a35277..e0b9dcaff 100644 --- a/src/core/project/boxProfileCredentials.ts +++ b/src/core/project/boxProfileCredentials.ts @@ -135,14 +135,23 @@ export function planBoxProfileCredentials( * route's variable from the environment, else from `.env.local`. A stored key that differs is * replaced, so dev and deploy use the same key after a rotation. False when there is none. */ - const seed = ({ variable }: BoxEnvRoute, credential: string): boolean => { + const seed = ({ route, variable }: BoxEnvRoute, credential: string): boolean => { const key = credentialEnvVarName(credential); - // Set in the environment itself, it is what deploy provisions; nothing to store. - if (hasValue(sources.env[key])) return true; - if (entries.some((entry) => entry.key === key)) return true; const value = hasValue(sources.env[variable]) ? sources.env[variable] : sources.envLocal[variable]; + // Set in the environment itself, it is what deploy provisions; nothing to store. + if (hasValue(sources.env[key])) { + if (hasValue(value) && value !== sources.env[key]) { + warnings.push( + `box egress '${route}': deploy provisions ${key} from the environment, but agentcore ` + + `dev uses env://${variable}, which holds a different key, so dev and deploy can ` + + `differ. Unset ${key}, or set it to the key in ${variable}`, + ); + } + return true; + } + if (entries.some((entry) => entry.key === key)) return true; const stored = sources.envLocal[key]; if (!hasValue(value)) return hasValue(stored); if (value === stored) return true; diff --git a/src/core/project/manager.boxCredentials.test.ts b/src/core/project/manager.boxCredentials.test.ts index 7e736e19b..0ed61c92f 100644 --- a/src/core/project/manager.boxCredentials.test.ts +++ b/src/core/project/manager.boxCredentials.test.ts @@ -172,6 +172,15 @@ describe("FsProjectManager.build: box env:// credentials", () => { expect(await storedKey(created.rootPath)).toBe("ghp_shell"); }); + test("warns when the shell's reserved variable holds a key other than the route's", async () => { + const { subject } = manager({ GITHUB_TOKEN: "ghp_dev", [RESERVED]: "ghp_explicit" }); + const created = await project(subject, GITHUB_PROFILE); + + const { warnings } = await drain(subject.build(created)); + + expect(warnings).toContainEqual(expect.stringContaining("so dev and deploy can differ")); + }); + test("seeds the key that agentcore dev stored in .env.local under the box variable", async () => { const { subject } = manager({}); const created = await project(subject, GITHUB_PROFILE); From 76bbfd09df4bed192f4a26669136b84178a464a6 Mon Sep 17 00:00:00 2001 From: Varun Gunda Date: Fri, 20 Nov 2026 17:29:41 -0800 Subject: [PATCH 10/10] fix(build): say when build fills in a blank stored box credential key --- src/core/project/boxProfileCredentials.test.ts | 13 +++++++++++++ src/core/project/boxProfileCredentials.ts | 7 ++++++- src/core/project/manager.boxCredentials.test.ts | 6 +++++- 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/core/project/boxProfileCredentials.test.ts b/src/core/project/boxProfileCredentials.test.ts index 7124ac30c..37c38ea25 100644 --- a/src/core/project/boxProfileCredentials.test.ts +++ b/src/core/project/boxProfileCredentials.test.ts @@ -124,6 +124,19 @@ describe("planBoxProfileCredentials", () => { ]); }); + test("fills in a blank stored key, and says so", () => { + const plan = planBoxProfileCredentials(spec([API_KEY]), [GITHUB], { + env: { GITHUB_TOKEN: "ghp_new" }, + envLocal: { [RESERVED]: "" }, + }); + + expect(plan.entries.map(({ key, value }) => [key, value])).toEqual([[RESERVED, "ghp_new"]]); + expect(plan.messages).toEqual([ + `filling in the blank ${RESERVED} in ${ENV_LOCAL_RELATIVE_PATH} with the key in ` + + "GITHUB_TOKEN, so deploy provisions it", + ]); + }); + test("leaves a stored key alone when the variable holds it, or when nothing sets the variable", () => { for (const env of [{ GITHUB_TOKEN: "ghp_same" }, {}]) { const plan = planBoxProfileCredentials(spec([API_KEY]), [GITHUB], { diff --git a/src/core/project/boxProfileCredentials.ts b/src/core/project/boxProfileCredentials.ts index e0b9dcaff..f5dc1bdca 100644 --- a/src/core/project/boxProfileCredentials.ts +++ b/src/core/project/boxProfileCredentials.ts @@ -22,7 +22,7 @@ export type BoxKeySources = { /** What {@link planBoxProfileCredentials} did with the box profile's `env://` routes. */ export type BoxCredentialPlan = { - /** One step message for each credential added, and for each stored key replaced. */ + /** One step message for each credential added, and for each stored key replaced or filled in. */ messages: string[]; /** * One warning for each route skipped for a reason to report, and for each route whose key is in @@ -160,6 +160,11 @@ export function planBoxProfileCredentials( `updating ${key} in ${ENV_LOCAL_RELATIVE_PATH}: ${variable} holds a different key, which ` + "agentcore dev uses, so deploy provisions it too", ); + } else if (stored !== undefined) { + messages.push( + `filling in the blank ${key} in ${ENV_LOCAL_RELATIVE_PATH} with the key in ${variable}, ` + + "so deploy provisions it", + ); } entries.push({ key, diff --git a/src/core/project/manager.boxCredentials.test.ts b/src/core/project/manager.boxCredentials.test.ts index 0ed61c92f..f2339d31b 100644 --- a/src/core/project/manager.boxCredentials.test.ts +++ b/src/core/project/manager.boxCredentials.test.ts @@ -233,9 +233,13 @@ describe("FsProjectManager.build: box env:// credentials", () => { await writeFile(join(created.rootPath, ENV_LOCAL_RELATIVE_PATH), `${RESERVED}=\n`); await appendEnvLocal(created.rootPath, `OTHER_API_KEY='${UNDECRYPTABLE}'`); - await drain(subject.build(created)); + const { steps } = await drain(subject.build(created)); expect(await storedKey(created.rootPath)).toBe("ghp_shell"); + expect(steps).toContain( + `filling in the blank ${RESERVED} in ${ENV_LOCAL_RELATIVE_PATH} with the key in ` + + "GITHUB_TOKEN, so deploy provisions it", + ); }); test("builds when .env.local holds an undecryptable key of a model-provider route", async () => {