cdk-real-drift 0.12.48 → 0.12.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -670,14 +670,19 @@ If the whole invocation fails before any stack is reached (bad config, an
670
670
  un-synthesizable app, or a zero-stack app), stdout is still a valid empty array
671
671
  `[]` (exit code non-zero, the reason on stderr) — never empty bytes.
672
672
 
673
- Every successfully-checked stack element carries a `"baseline": <bool>` flag —
673
+ Every successfully-checked stack element of a baseline-consulting `check` carries a
674
+ `"baseline": <bool>` flag —
674
675
  `true` when the stack has a committed `.cdkrd` baseline (its undeclared dimension is
675
676
  **watched**), `false` when it has never been recorded. Without a baseline the
676
677
  classification shifts: appeared-since-record out-of-band values read as `unrecorded`
677
678
  and are excluded from `drifted`, so a QUIET never-recorded stack emits the
678
679
  byte-identical `"drifted": 0` of a watched-clean one. A consumer summing `drifted`
679
680
  uses `baseline` to tell an UNWATCHED stack from a watched-clean one (#1095). It is
680
- omitted on the `error` / `stackDeleted` shapes (never reconciled against a baseline).
681
+ omitted whenever the baseline was **not consulted**: on the `error` / `stackDeleted`
682
+ shapes (never reconciled against a baseline), and on every element of a
683
+ `--pre-deploy` or `--show-all` run (both are baseline-untouched modes, so they
684
+ cannot claim `false` — a committed baseline may well exist; #1335). Absent means
685
+ "not consulted"; `false` means "consulted, never recorded".
681
686
 
682
687
  Each stack element is `{ "stack": "<name> (<region>)", "drifted": <n>, "baseline": <bool>, "findings": [...] }`
683
688
  (`error` added only on a pre-check failure; `stackDeleted: true` only on a deleted
@@ -737,9 +742,10 @@ mode: a `record` / `ignore` that would need the selection prompt refuses without
737
742
  `--yes` (`"refused": true`), and `revert` refuses the AWS write without `--yes`
738
743
  (`"exit": 2`). Per-verb element:
739
744
 
740
- - `record` → `{ "stack", "recorded": <n>, "wrote": <bool>, "baseline"?: "<path>",
745
+ - `record` → `{ "stack", "recorded": <n>, "wrote": <bool>, "baselinePath"?: "<path>",
741
746
  "refused"?: true, "error"?: "<reason>" }` — `recorded` is how many undeclared
742
- value(s) were written.
747
+ value(s) were written; `baselinePath` is the baseline file written (a path string,
748
+ deliberately NOT named `baseline` — that key is check's boolean flag; #1336).
743
749
  - `ignore` → `{ "stack", "added": <n>, "wrote": <bool>, "config"?:
744
750
  ".cdkrd/ignore.yaml", "refused"?: true, "error"?: "<reason>" }` — `added` is how
745
751
  many new rules were appended.
package/dist/cli.js CHANGED
@@ -1089,6 +1089,26 @@ function buildStackSelector(patterns) {
1089
1089
  }
1090
1090
  const CONCRETE_REGION = /^[a-z]{2}(-[a-z]+)+-\d+$/;
1091
1091
  const CONCRETE_ACCOUNT = /^\d{12}$/;
1092
+ const SYNTHESIS_ERROR_LEVEL = "error";
1093
+ /**
1094
+ * Extract the ERROR-level synthesis messages of a single stack artifact (#1316).
1095
+ *
1096
+ * A stack's `Annotations.addError(...)` (cdk-nag, a security aspect, a "do not deploy" guard)
1097
+ * surfaces as a `messages` entry with `level === 'error'`. toolkit.synth's own
1098
+ * `validateStacksMetadata` aborts on these — but ONLY for the SELECTOR-matched stacks, and the
1099
+ * #905 selector matches on hierarchicalId, so a stackName-form positional (`Dev-Net`) that
1100
+ * matches zero hierarchicalIds skips that validation entirely. We re-collect them here so
1101
+ * resolveStacks can abort on the SELECTED stacks, restoring the no-args abort behavior for the
1102
+ * named case. Pure + exported for unit tests. Returns the human-readable error strings (empty
1103
+ * when the stack has no error annotation).
1104
+ */
1105
+ function stackErrorMessages(messages) {
1106
+ if (!messages) return [];
1107
+ return messages.filter((m) => m.level === SYNTHESIS_ERROR_LEVEL).map((m) => {
1108
+ const data = m.entry?.data;
1109
+ return typeof data === "string" && data.length > 0 ? data : "error";
1110
+ });
1111
+ }
1092
1112
  function concreteAccount(raw) {
1093
1113
  return raw && CONCRETE_ACCOUNT.test(raw) ? raw : void 0;
1094
1114
  }
@@ -1216,8 +1236,10 @@ async function synthApp(app, opts = {}) {
1216
1236
  }
1217
1237
  return cached.cloudAssembly.stacksRecursively.map((s) => ({
1218
1238
  stackName: s.stackName,
1239
+ hierarchicalId: s.hierarchicalId,
1219
1240
  region: CONCRETE_REGION.test(s.environment.region) ? s.environment.region : void 0,
1220
1241
  account: concreteAccount(s.environment.account),
1242
+ errorMessages: stackErrorMessages(s.messages),
1221
1243
  template: s.template
1222
1244
  }));
1223
1245
  } finally {
@@ -1232,8 +1254,10 @@ async function synthApp(app, opts = {}) {
1232
1254
  async function discoverStacks(app, opts = {}) {
1233
1255
  return (await synthApp(app, opts)).map((s) => ({
1234
1256
  stackName: s.stackName,
1257
+ hierarchicalId: s.hierarchicalId,
1235
1258
  region: s.region,
1236
1259
  account: s.account,
1260
+ errorMessages: s.errorMessages,
1237
1261
  template: s.template
1238
1262
  }));
1239
1263
  }
@@ -1303,6 +1327,39 @@ async function resolveProfileRegion(profile) {
1303
1327
  } catch {}
1304
1328
  return defaultProfileRegionFromIni() ?? await regionFromImds();
1305
1329
  }
1330
+ /**
1331
+ * #1316: does a CLI positional select this discovered stack? A positional matches against BOTH
1332
+ * the deployed CloudFormation `stackName` AND the toolkit `hierarchicalId` (`Stage/Stack` for a
1333
+ * stack nested in a CDK `Stage`), so BOTH `check Dev-Net` (the stage-qualified stackName cdkrd
1334
+ * historically accepted) AND the cdk-native `check Dev/Net` (what `cdk ls`/`cdk synth` show, and
1335
+ * what the #905 selector actually matches on) resolve to the staged stack. A positional with a
1336
+ * glob metachar (`*`/`?`) is matched as a glob against each identifier; a plain positional matches
1337
+ * either identifier EXACTLY (equivalent to a metachar-free glob, but kept as `===` for clarity and
1338
+ * to preserve the exact-name semantics). For a top-level stack the two identifiers are identical,
1339
+ * so behavior there is unchanged. Pure + exported for unit tests.
1340
+ */
1341
+ function positionalMatchesStack(positional, stack) {
1342
+ const hierarchicalId = stack.hierarchicalId ?? stack.stackName;
1343
+ if (isGlob(positional)) return matchesGlob(positional, stack.stackName) || matchesGlob(positional, hierarchicalId);
1344
+ return positional === stack.stackName || positional === hierarchicalId;
1345
+ }
1346
+ /**
1347
+ * #1316: the residual-hole guard. toolkit.synth's metadata validation aborts on a stack's
1348
+ * error-level annotations (`Annotations.addError(...)` — cdk-nag, a security aspect, a
1349
+ * "do not deploy" guard), but ONLY for the SELECTOR-matched collection, and the #905 selector
1350
+ * matches on hierarchicalId. A stackName-form positional (`Dev-Net`) matches zero hierarchicalIds,
1351
+ * so that validation is silently skipped — cdkrd would then read (and `revert --yes` write back)
1352
+ * a template from an app in an error state. After selecting the target stacks, re-check THEIR
1353
+ * error annotations and throw so the caller aborts (check maps a resolveStacks throw to exit 2),
1354
+ * restoring the no-args abort behavior for the named case. The no-args / --all path already had
1355
+ * toolkit.synth validate every stack (no selector), so this is a belt for the named case.
1356
+ * Aggregates messages across every selected stack. Pure + exported for unit tests.
1357
+ */
1358
+ function assertNoStackErrors(selected) {
1359
+ const lines = [];
1360
+ for (const s of selected) for (const msg of s.errorMessages ?? []) lines.push(` ${s.stackName}: ${msg}`);
1361
+ if (lines.length > 0) throw new Error(`the CDK app synthesized with ${lines.length} error(s) (an Annotations.addError — cdk-nag / security aspect / do-not-deploy guard) on the selected stack(s); refusing to read or revert an app in an error state:\n${lines.join("\n")}`);
1362
+ }
1306
1363
  async function resolveStacks(a) {
1307
1364
  const app = resolveApp(a.app);
1308
1365
  if (!app) throw new Error("cdkrd needs a CDK app: run in a directory with cdk.json, pass --app \"<cmd>\" or --app <cdk.out> (a pre-synthesized assembly), or set $CDKRD_APP");
@@ -1315,14 +1372,18 @@ async function resolveStacks(a) {
1315
1372
  context: a.context,
1316
1373
  stackPatterns: scopePatterns
1317
1374
  });
1318
- if (a.all || a.stackNames.length === 0) return discovered.map((s) => ({
1319
- stackName: s.stackName,
1320
- region: s.region ?? fallbackRegion,
1321
- account: s.account,
1322
- template: s.template
1323
- }));
1375
+ if (a.all || a.stackNames.length === 0) {
1376
+ assertNoStackErrors(discovered);
1377
+ return discovered.map((s) => ({
1378
+ stackName: s.stackName,
1379
+ region: s.region ?? fallbackRegion,
1380
+ account: s.account,
1381
+ template: s.template
1382
+ }));
1383
+ }
1324
1384
  const seen = /* @__PURE__ */ new Set();
1325
1385
  const out = [];
1386
+ const selectedByKey = /* @__PURE__ */ new Map();
1326
1387
  const add = (stackName, region, account, template) => {
1327
1388
  const key = `${stackName}\0${region ?? ""}\0${account ?? ""}`;
1328
1389
  if (seen.has(key)) return;
@@ -1334,19 +1395,22 @@ async function resolveStacks(a) {
1334
1395
  template
1335
1396
  });
1336
1397
  };
1337
- const known = () => discovered.map((s) => s.stackName).join(", ") || "none";
1338
- for (const name of a.stackNames) if (isGlob(name)) {
1339
- let matched = 0;
1340
- for (const s of discovered) if (matchesGlob(name, s.stackName)) {
1341
- matched++;
1342
- add(s.stackName, s.region ?? fallbackRegion, s.account, s.template);
1398
+ const known = () => discovered.map((s) => s.hierarchicalId === s.stackName ? s.stackName : `${s.hierarchicalId} (${s.stackName})`).join(", ") || "none";
1399
+ const select = (s) => {
1400
+ add(s.stackName, s.region ?? fallbackRegion, s.account, s.template);
1401
+ selectedByKey.set(`${s.stackName}\0${s.region ?? ""}\0${s.account ?? ""}`, s);
1402
+ };
1403
+ for (const name of a.stackNames) {
1404
+ const hits = discovered.filter((s) => positionalMatchesStack(name, s));
1405
+ if (isGlob(name)) {
1406
+ if (hits.length === 0) throw new Error(`glob "${name}" matched no stacks defined by the CDK app (found: ${known()})`);
1407
+ for (const hit of hits) select(hit);
1408
+ } else {
1409
+ if (hits.length === 0) throw new Error(`stack "${name}" is not defined by the CDK app (found: ${known()})`);
1410
+ for (const hit of hits) select(hit);
1343
1411
  }
1344
- if (matched === 0) throw new Error(`glob "${name}" matched no stacks defined by the CDK app (found: ${known()})`);
1345
- } else {
1346
- const hits = discovered.filter((s) => s.stackName === name);
1347
- if (hits.length === 0) throw new Error(`stack "${name}" is not defined by the CDK app (found: ${known()})`);
1348
- for (const hit of hits) add(hit.stackName, hit.region ?? fallbackRegion, hit.account, hit.template);
1349
1412
  }
1413
+ assertNoStackErrors([...selectedByKey.values()]);
1350
1414
  if (out.length === 0) throw new Error(`no stacks match ${a.stackNames.join(", ")} (found: ${known()})`);
1351
1415
  return out;
1352
1416
  }
@@ -13811,7 +13875,7 @@ function buildStackJson(rawFindings, header, hasBaseline) {
13811
13875
  stack: header,
13812
13876
  drifted,
13813
13877
  findings: findings.map((f) => redactFinding(f)),
13814
- baseline: hasBaseline === true
13878
+ ...hasBaseline === void 0 ? {} : { baseline: hasBaseline }
13815
13879
  },
13816
13880
  code: drifted === 0 ? 0 : 1
13817
13881
  };
@@ -17689,7 +17753,7 @@ async function runRecord(args) {
17689
17753
  recorded: result.count ?? 0,
17690
17754
  wrote: result.wrote,
17691
17755
  ...result.refused && { refused: true },
17692
- ...result.path !== void 0 && { baseline: result.path }
17756
+ ...result.path !== void 0 && { baselinePath: result.path }
17693
17757
  });
17694
17758
  } catch (e) {
17695
17759
  if (isStackNotDeployed(e)) {
@@ -18729,7 +18793,7 @@ async function runCheck(args) {
18729
18793
  const reportHeader = `${posPrefix}${stackName} (${region})`;
18730
18794
  let code;
18731
18795
  if (a.json) {
18732
- const { json, code: jsonCode } = buildStackJson(reconciled, reportHeader, baseline !== void 0);
18796
+ const { json, code: jsonCode } = buildStackJson(reconciled, reportHeader, a.showAll ? void 0 : baseline !== void 0);
18733
18797
  jsonReports.push(json);
18734
18798
  code = jsonCode;
18735
18799
  } else code = report(reconciled, reportHeader, {