Repository navigation
Description
Describe the bug
In packages/@aws-cdk/toolkit-lib/lib/actions/refactor/private/mapping-helpers.ts (lines 28-35), parseMappingGroups validates the parsed --override-file JSON in doParse() using an inverted boolean condition:
function doParse(): MappingGroup[] {
const content = JSON.parse(s);
if (content.environments || !Array.isArray(content.environments)) {
return content.environments;
} else {
throw new ToolkitError('MissingEnvironmentsArray', "Expected an 'environments' array");
}
}Because if (content.environments || !Array.isArray(content.environments)) is evaluated:
- When
environmentsis missing (such as{}) or falsy (such asnullorfalse),!Array.isArray(content.environments)istrue, sodoParse()returnsundefined/null/falseinstead of throwingToolkitError('MissingEnvironmentsArray', ...), and line 12 (for (let group of mappingGroups)) crashes withTypeError: mappingGroups is not iterable. - When
environmentsis a truthy non-array (such as{}or"bad"),content.environmentsshort-circuits totrue, sodoParse()returns the non-array and line 12/15 crashes withTypeError: mappingGroups is not iterableorTypeError: Cannot convert undefined or null to object. - The
elsebranch (throw new ToolkitError('MissingEnvironmentsArray', "Expected an 'environments' array")) is unreachable for every possible JavaScript value, because no falsy value passesArray.isArray(x).
Separately, packages/aws-cdk/README.md (lines 1552-1564) documents --override-file with "mappings": [...] instead of "environments": [...], so copying the documented example causes parseMappingGroups (called from packages/aws-cdk/lib/cli/cdk-toolkit.ts line 1454) to fail with TypeError: mappingGroups is not iterable instead of raising MissingEnvironmentsArray.
Regression Issue
- Select this option if this issue appears to be a regression.
Last Known Working CDK Version
No response
Expected Behavior
- Passing JSON without an
environmentsarray (for example{},{"mappings": [...]},{"environments": null}, or{"environments": {}}) throwsToolkitError('MissingEnvironmentsArray', "Expected an 'environments' array"). packages/aws-cdk/README.md(lines 1552-1564) documents the"environments"top-level key matchingparseMappingGroups,packages/aws-cdk/test/commands/refactor.test.ts(lines 310-318), andcdk-refactor-with-ambiguities-execution.integtest.ts.
Current Behavior
Running parseMappingGroups (verified against origin/main commit d71c502b1827637f70a29765e8926e21658dedf7 in Node v26.13.1) never throws MissingEnvironmentsArray and crashes with TypeError:
README example with mappings key -> TypeError: mappingGroups is not iterable
missing key {} -> TypeError: mappingGroups is not iterable
environments null -> TypeError: mappingGroups is not iterable
environments object {} -> TypeError: mappingGroups is not iterable
environments string "bad" -> TypeError: Cannot convert undefined or null to object
environments boolean false -> TypeError: mappingGroups is not iterable
Reproduction Steps
Run the following script with Node (v26.13.1) from the repository root on main:
import fs from 'node:fs';
import vm from 'node:vm';
import { stripTypeScriptTypes } from 'node:module';
const src = fs.readFileSync(
'packages/@aws-cdk/toolkit-lib/lib/actions/refactor/private/mapping-helpers.ts',
'utf8',
);
const stripped = stripTypeScriptTypes(src, { mode: 'strip' })
.replace(/import [\s\S]*?from ['"].*?['"];\r?\n/g, '')
.replace(/export async function /g, 'async function ')
.replace(/export function /g, 'function ');
class ToolkitError extends Error {
constructor(type, message) {
super(message);
this.type = type;
}
}
const mod = { exports: {} };
vm.runInNewContext(stripped + '\nexports.parseMappingGroups = parseMappingGroups;', {
exports: mod.exports,
ToolkitError,
groupStacks: async () => [],
RefactoringContext: class {},
Object,
Array,
Set,
JSON,
});
const { parseMappingGroups } = mod.exports;
for (const [label, input] of [
[
'README example with mappings key',
JSON.stringify({
mappings: [
{
account: '123456789012',
region: 'us-east-1',
resources: { 'Stack2.OldName': 'Stack2.NewName' },
},
],
}),
],
['missing key {}', '{}'],
['environments null', '{"environments": null}'],
['environments object {}', '{"environments": {}}'],
['environments string "bad"', '{"environments": "bad"}'],
['environments boolean false', '{"environments": false}'],
]) {
try {
parseMappingGroups(input);
console.log(label, '-> returned normally');
} catch (err) {
console.log(label, '->', `${err.constructor.name}: ${err.message}`);
}
}Possible Solution
In packages/@aws-cdk/toolkit-lib/lib/actions/refactor/private/mapping-helpers.ts, check Array.isArray(content?.environments) (and ensure content is a non-null plain object before reading content.environments, plus validate each element is an object with resources):
if (!content || typeof content !== 'object' || !Array.isArray(content.environments)) {
throw new ToolkitError('MissingEnvironmentsArray', "Expected an 'environments' array");
}
return content.environments;And update the example JSON key in packages/aws-cdk/README.md (line 1554) from "mappings" to "environments" if environments is the canonical schema.
I would be happy to submit a PR with regression unit tests for invalid --override-file inputs once maintainers confirm the expected schema and README update.
Additional Information/Context
- Caller in CLI:
packages/aws-cdk/lib/cli/cdk-toolkit.ts:1454(readOverrides) - Tests only pass valid
environmentsarrays inpackages/aws-cdk/test/commands/refactor.test.ts:310-318and345-353.
CDK CLI Version
origin/main (d71c502; latest release tag [email protected])
Framework Version
No response
Node.js Version
v26.13.1
OS
Windows 11
Language
TypeScript
Language Version
No response
Other information
No response
Activity
sai-ray commentedon Dec 4, 2026
Hey @mayankcodes-dev, truly appreciate the detailed report and the repro, they made this quick to confirm. The fix, including the README example, is in #2201. Thanks :)