Skip to content

(refactor): parseMappingGroups uses inverted condition, making MissingEnvironmentsArray unreachable #2200

In review

Description

@mayankcodes-dev

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:

  1. When environments is missing (such as {}) or falsy (such as null or false), !Array.isArray(content.environments) is true, so doParse() returns undefined/null/false instead of throwing ToolkitError('MissingEnvironmentsArray', ...), and line 12 (for (let group of mappingGroups)) crashes with TypeError: mappingGroups is not iterable.
  2. When environments is a truthy non-array (such as {} or "bad"), content.environments short-circuits to true, so doParse() returns the non-array and line 12/15 crashes with TypeError: mappingGroups is not iterable or TypeError: Cannot convert undefined or null to object.
  3. The else branch (throw new ToolkitError('MissingEnvironmentsArray', "Expected an 'environments' array")) is unreachable for every possible JavaScript value, because no falsy value passes Array.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 environments array (for example {}, {"mappings": [...]}, {"environments": null}, or {"environments": {}}) throws ToolkitError('MissingEnvironmentsArray', "Expected an 'environments' array").
  • packages/aws-cdk/README.md (lines 1552-1564) documents the "environments" top-level key matching parseMappingGroups, packages/aws-cdk/test/commands/refactor.test.ts (lines 310-318), and cdk-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 environments arrays in packages/aws-cdk/test/commands/refactor.test.ts:310-318 and 345-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

  1. sai-ray commented on Dec 4, 2026

    @sai-ray
    Contributor

    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 :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions