cdk-real-drift 0.2.50 → 0.2.52

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
@@ -462,13 +462,17 @@ ignore:
462
462
  ```
463
463
 
464
464
  - Every rule is a mapping `{ path, stack?, account?, region? }`. `cdkrd ignore`
465
- writes the unscoped form (and is **comment-preserving and append-only**: it keeps
466
- your existing comments and layout, and appends new rules at the end — you own the
467
- order). `path` is an exact `<constructPath>.<path>` — the construct path WITHIN the
468
- stack (the stack/Stage prefix stripped), byte-identical to what `cdkrd check` prints, so
469
- you can copy what you see (or `<logicalId>.<path>` on a non-CDK stack). Rules written with
470
- the older full `<stack>/<constructPath>.<path>` form still match. The optional `stack` /
471
- `account` / `region` scopes are a hand-edit.
465
+ stamps the current **stack / account / region** onto each rule it writes (the same
466
+ three identity axes a baseline file is keyed on), so ignoring a within-stack path on
467
+ one stack never leaks to a same-named twin stack in another account/region — an
468
+ unscoped `{ path }` was match-all (#757). The verb is **comment-preserving and
469
+ append-only**: it keeps your existing comments and layout, and appends new rules at
470
+ the end — you own the order. `path` is an exact `<constructPath>.<path>` — the
471
+ construct path WITHIN the stack (the stack/Stage prefix stripped), byte-identical to
472
+ what `cdkrd check` prints, so you can copy what you see (or `<logicalId>.<path>` on a
473
+ non-CDK stack). Rules written with the older full `<stack>/<constructPath>.<path>`
474
+ form still match. Widening a stamped scope to a `*` glob (to intentionally ignore a
475
+ path across every stack/account/region) stays a hand-edit.
472
476
  - All four fields accept the same `*` / `?` glob, and a parent `path` covers child
473
477
  paths. The three scope axes — **stack, account, region** — are exactly the
474
478
  baseline file's identity axes. **Account** keeps a `stack: "Prod*"` rule from
@@ -533,13 +537,67 @@ reserved for picker rows you aren't on. Piped / CI / `--json` output is plain te
533
537
 
534
538
  ### JSON output contract
535
539
 
536
- `--json` emits
537
- `{ "stack": "<name> (<region>)", "drifted": <n>, "findings": [...] }`.
538
- Each finding has a stable shape: `tier` (`deleted` | `declared` | `undeclared` |
539
- `readGap` | `unresolved` | `skipped` | `ignored`), `logicalId`, `resourceType`,
540
- `path`, `desired`, `actual`, `note`, `physicalId`, `constructPath`. An unrecorded
541
- value keeps `tier: "undeclared"` and carries `"unrecorded": true`; `drifted`
542
- excludes it. The output always carries every finding regardless of `--verbose`.
540
+ `--json` emits **one top-level JSON array for the whole invocation — one element per
541
+ stack**:
542
+
543
+ ```json
544
+ [
545
+ { "stack": "stackA (us-east-1)", "drifted": 1, "findings": [ ... ] },
546
+ { "stack": "stackB (us-east-1)", "drifted": 0, "findings": [] }
547
+ ]
548
+ ```
549
+
550
+ The whole stdout stream is a single `JSON.parse`-able value. This holds even for a
551
+ single-stack run — it is an **array of one** (never a bare object), so a consumer's
552
+ `JSON.parse` always yields an array and never has to special-case the count. (Earlier
553
+ builds printed one pretty-printed `{...}` per stack back-to-back, which was neither one
554
+ valid JSON value nor JSONL; multi-stack `--json` was unparseable — issue #755.) All
555
+ `note` / `warning` / progress lines go to **stderr**, so stdout stays pure JSON.
556
+
557
+ A **stack that errored or was skipped** before it could be checked still appears as an
558
+ element so a consumer sees which stacks ran: it carries `"error": "<reason>"` alongside
559
+ `"drifted": 0` and an empty `"findings": []`. (`error` is absent on a
560
+ successfully-checked stack.)
561
+
562
+ Each stack element is `{ "stack": "<name> (<region>)", "drifted": <n>, "findings": [...] }`
563
+ (`error` added only on failure). Each **finding** has a stable shape:
564
+
565
+ - Always present: `tier`, `logicalId`, `resourceType`, `path`.
566
+ - Usually present: `desired`, `actual`, `note`, `physicalId`, `constructPath` (any of
567
+ these may be omitted when it doesn't apply — e.g. an undeclared finding has no
568
+ `desired`).
569
+ - `tier` is one of `deleted` | `added` | `declared` | `undeclared` | `atDefault` |
570
+ `generated` | `ignored` | `readGap` | `unresolved` | `skipped`. The output carries
571
+ **every** finding of every tier (including the informational `atDefault` / `generated`
572
+ / `ignored` / `readGap` / `unresolved` / `skipped` ones the text report folds into its
573
+ `info:` footer), regardless of `--verbose`.
574
+ - `drifted` counts only confirmed-drift tiers (`deleted` / `declared` / `undeclared` /
575
+ `added`) that are not `unrecorded`; the informational tiers and unrecorded values are
576
+ excluded.
577
+
578
+ Optional per-finding fields, present only when they apply:
579
+
580
+ - `hint` — a non-classifying, human-facing note on where a live value likely came from
581
+ (e.g. an account/region-level auto-instrumentation footprint). Display-only; it never
582
+ changes the tier.
583
+ - `unrecorded` (`true`) — a live-only value (`undeclared` or `added`) with no baseline
584
+ entry yet: **potential drift**, not confirmed drift. Excluded from `drifted`.
585
+ - `attributeKey` — for a `declared` drift inside an identity-keyed attribute bag (ELB
586
+ `LoadBalancerAttributes` / `TargetGroupAttributes`), the `Key` of the changed
587
+ attribute (`path` stays at the bag property; `desired`/`actual` are the scalar value).
588
+ - `arrayDelta` — for an `undeclared` recorded identity-keyed array that changed vs the
589
+ baseline, the element-level delta (`{ identityField, added, changed, removed }`) so a
590
+ consumer sees which element(s) differ, not the whole-array dump.
591
+ - `nested` (`true`) — an `undeclared` value is a live sub-key inside a property you
592
+ _did_ declare (dotted `path`). `freeFormKey` (`true`) additionally marks it as living
593
+ inside a free-form map (e.g. a Lambda env var).
594
+ - `modelReadFailed` (`true`) — an `added` resource whose full live model could not be
595
+ read this run (`actual` is only the enumerator's identity snippet); it exists but is
596
+ not change-watchable until the next check.
597
+ - On an `added` finding, `desired` carries the **recorded baseline model** and `actual`
598
+ the live one (so a recorded `added` resource that changed shows the delta), and
599
+ `unrecorded` marks a never-recorded one as potential drift.
600
+
543
601
  After publication this shape is a backward-compatible API.
544
602
 
545
603
  ## IAM permissions
package/dist/cli.js CHANGED
@@ -76,6 +76,10 @@ function classifyStackStatus(status) {
76
76
  kind: "skip",
77
77
  message: "is being deleted (DELETE_IN_PROGRESS) — nothing stable to check"
78
78
  };
79
+ if (s === "ROLLBACK_COMPLETE") return {
80
+ kind: "skip",
81
+ message: "in ROLLBACK_COMPLETE — the initial create failed and rolled back, deleting every resource, so there is no deployed state to check; delete and re-deploy"
82
+ };
79
83
  if (s.endsWith("_IN_PROGRESS")) return {
80
84
  kind: "warn",
81
85
  message: `stack is mid-operation (${s}) — live state is in flux, so drift results may be transient`
@@ -433,21 +437,29 @@ function validateIgnoreEntry(entry, index) {
433
437
  ]) if (obj[k] !== void 0 && typeof obj[k] !== "string") throw new Error(`${at}: "${k}" must be a string`);
434
438
  }
435
439
  /**
436
- * The exact ignore rule the `ignore` verb writes for a finding — always the unscoped
437
- * rule (just `path`); the optional `stack` / `region` scopes stay hand-authored (the
438
- * verb writes the simplest rule; narrowing is a manual edit). Prefer the human-friendly
439
- * `<constructPath>.<path>` when present (CDK stacks): it is what `cdk-local` targets on
440
- * and readable in the git-committed config diff. The construct path is written WITHIN the
441
- * stack (the stack/Stage prefix stripped, given `stackName`) so it is byte-identical to
442
- * what the report prints for the finding — copy what you see. Naturally stack-scoped even
443
- * without the prefix (a `stack:` scope narrows further). Falls back to `<logicalId>.<path>`,
444
- * ALWAYS present (the CloudFormation key) so a rule is writable even on a non-CDK /
445
- * metadata-stripped stack. Pure + exported; `applyIgnores` matches the within-stack path,
446
- * the full construct path (older rules), AND the logicalId, so every form works.
440
+ * The exact ignore rule the `ignore` verb (and check's inline ignore) writes for a
441
+ * finding. The rule is STAMPED with the current stack / account / region scope (the same
442
+ * three identity axes a baseline file is keyed on), so ignoring a within-stack path on one
443
+ * stack does NOT leak to a same-named twin stack in another account/region — an unscoped
444
+ * `{ path }` was match-all, silently silencing the identical path everywhere (issue #757).
445
+ * The literal identity values are valid exact globs; hand-widening to a `*` glob stays a
446
+ * manual edit. A scope field is omitted only when genuinely unavailable (empty string).
447
+ * Prefer the human-friendly `<constructPath>.<path>` for `path` when present (CDK stacks):
448
+ * it is what `cdk-local` targets on and readable in the git-committed config diff. The
449
+ * construct path is written WITHIN the stack (the stack/Stage prefix stripped, given
450
+ * `stackName`) so it is byte-identical to what the report prints for the finding — copy
451
+ * what you see. Falls back to `<logicalId>.<path>`, ALWAYS present (the CloudFormation
452
+ * key) so a rule is writable even on a non-CDK / metadata-stripped stack. Pure + exported;
453
+ * `applyIgnores` matches the within-stack path, the full construct path (older rules), AND
454
+ * the logicalId, so every form works.
447
455
  */
448
- function ignoreRuleFor(finding, stackName = "") {
456
+ function ignoreRuleFor(finding, stackName = "", accountId = "", region = "") {
449
457
  const id = finding.constructPath ? withinStackPath(finding.constructPath, stackName) : finding.logicalId;
450
- return { path: finding.path ? `${id}.${finding.path}` : id };
458
+ const rule = { path: finding.path ? `${id}.${finding.path}` : id };
459
+ if (stackName) rule.stack = stackName;
460
+ if (accountId) rule.account = accountId;
461
+ if (region) rule.region = region;
462
+ return rule;
451
463
  }
452
464
  /** Canonical identity of a rule (path + the three optional scopes), for dedupe. */
453
465
  function ruleKey(r) {
@@ -9295,7 +9307,7 @@ function splitRecordedByBaseline(recorded, baseline) {
9295
9307
  function selectRecorded(findings, selectedKeys) {
9296
9308
  return buildRecorded(findings).filter((e) => selectedKeys.has(recordedKey(e)));
9297
9309
  }
9298
- const topSegment = (p) => p.split(".")[0] ?? p;
9310
+ const isTopLevelPath = (p) => !p.includes(".") && !p.includes("[");
9299
9311
  /**
9300
9312
  * Reconcile undeclared findings against the recorded baseline (per ENTRY, R62):
9301
9313
  * - an undeclared finding matching an recorded entry (same value) is suppressed;
@@ -9409,7 +9421,7 @@ function applyBaseline(findings, baseline, opts = {}) {
9409
9421
  removedFromTemplate.push(`${a.logicalId}.${a.path}`);
9410
9422
  continue;
9411
9423
  }
9412
- if (opts.declaredByLogical?.get(a.logicalId)?.has(topSegment(a.path))) {
9424
+ if (isTopLevelPath(a.path) && opts.declaredByLogical?.get(a.logicalId)?.has(a.path)) {
9413
9425
  promotedStale.push(`${a.logicalId}.${a.path}`);
9414
9426
  continue;
9415
9427
  }
@@ -11953,7 +11965,7 @@ function ignoreSelectOptions(ignorable, stackName = "") {
11953
11965
  * ignore` and (PR-B2) check's interactive flow, so both write rules identically.
11954
11966
  */
11955
11967
  async function ignoreStack(p) {
11956
- const { stackName, findings, yes, interactive } = p;
11968
+ const { stackName, findings, yes, interactive, accountId = "", region = "" } = p;
11957
11969
  const ignorable = findings.filter((f) => f.tier === "declared" || f.tier === "undeclared" || f.tier === "added");
11958
11970
  if (ignorable.length === 0) {
11959
11971
  console.log(style.clean(`${stackName}: no ignorable drift to ignore.`));
@@ -11993,7 +12005,7 @@ async function ignoreStack(p) {
11993
12005
  };
11994
12006
  }
11995
12007
  }
11996
- const { path, added, alreadyPresent } = await addIgnoreRules(chosen.map((f) => ignoreRuleFor(f, stackName)));
12008
+ const { path, added, alreadyPresent } = await addIgnoreRules(chosen.map((f) => ignoreRuleFor(f, stackName, accountId, region)));
11997
12009
  if (added.length > 0) {
11998
12010
  const dup = alreadyPresent.length > 0 ? `, ${alreadyPresent.length} already present` : "";
11999
12011
  console.log(style.ok(`ignore rule(s) added: ${path} (${added.length} new${dup})`));
@@ -12437,7 +12449,9 @@ async function runIgnore(args) {
12437
12449
  region
12438
12450
  }, config),
12439
12451
  yes: a.yes,
12440
- interactive: isInteractive()
12452
+ interactive: isInteractive(),
12453
+ accountId: desired.accountId,
12454
+ region
12441
12455
  });
12442
12456
  if (result.wrote) wroteAny = true;
12443
12457
  if (result.refused) worst = Math.max(worst, 2);
@@ -12622,6 +12636,19 @@ function groupReasons(items) {
12622
12636
  }
12623
12637
  return [...counts.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).map(([k, c]) => `${k} ${c}`).join(", ");
12624
12638
  }
12639
+ function buildStackJson(rawFindings, header) {
12640
+ const findings = annotateHints(rawFindings);
12641
+ const isDriftHere = (f) => DRIFT_TIERS.includes(f.tier) && !f.unrecorded;
12642
+ const drifted = findings.filter(isDriftHere).length;
12643
+ return {
12644
+ json: {
12645
+ stack: header,
12646
+ drifted,
12647
+ findings
12648
+ },
12649
+ code: drifted === 0 ? 0 : 1
12650
+ };
12651
+ }
12625
12652
  function report(rawFindings, header, opts = {}) {
12626
12653
  const log = opts.log ?? console.log;
12627
12654
  const stackName = stackNameFromHeader(header);
@@ -12629,11 +12656,7 @@ function report(rawFindings, header, opts = {}) {
12629
12656
  const isDriftHere = (f) => DRIFT_TIERS.includes(f.tier) && !f.unrecorded;
12630
12657
  const drifted = findings.filter(isDriftHere).length;
12631
12658
  if (opts.json) {
12632
- log(JSON.stringify({
12633
- stack: header,
12634
- drifted,
12635
- findings
12636
- }, null, 2));
12659
+ log(JSON.stringify(buildStackJson(rawFindings, header).json, null, 2));
12637
12660
  return drifted === 0 ? 0 : 1;
12638
12661
  }
12639
12662
  const byTier = (t) => findings.filter((f) => f.tier === t && !f.unrecorded);
@@ -13137,7 +13160,9 @@ async function ignoreAll(p) {
13137
13160
  stackName: p.stackName,
13138
13161
  findings,
13139
13162
  yes: p.yes,
13140
- interactive: true
13163
+ interactive: true,
13164
+ accountId: p.desired.accountId,
13165
+ region: p.region
13141
13166
  })).wrote ? {
13142
13167
  exit: await recomputeExit(p, /* @__PURE__ */ new Set()),
13143
13168
  awsMutated: false
@@ -13202,7 +13227,9 @@ async function perFinding(p, decidable) {
13202
13227
  stackName: p.stackName,
13203
13228
  findings: groups.ignore,
13204
13229
  yes: true,
13205
- interactive: true
13230
+ interactive: true,
13231
+ accountId: p.desired.accountId,
13232
+ region: p.region
13206
13233
  });
13207
13234
  let revertResolved = /* @__PURE__ */ new Set();
13208
13235
  let revertExit = 0;
@@ -13323,11 +13350,22 @@ async function runCheck(args) {
13323
13350
  }
13324
13351
  let worst = 0;
13325
13352
  let anyDrift = false;
13353
+ const jsonReports = [];
13354
+ const jsonError = (stackName, region, message) => {
13355
+ if (a.json) jsonReports.push({
13356
+ stack: region ? `${stackName} (${region})` : stackName,
13357
+ drifted: 0,
13358
+ findings: [],
13359
+ error: message
13360
+ });
13361
+ };
13326
13362
  const separate = stackSeparator();
13327
13363
  const showProgress = !a.json && isInteractive();
13328
13364
  for (const [idx, { stackName, region, template }] of stacks.entries()) {
13329
13365
  if (!region) {
13330
- console.error(`error: ${stackName}: no region — set env on the stack, pass --region, or set a region for the AWS profile`);
13366
+ const msg = "no region — set env on the stack, pass --region, or set a region for the AWS profile";
13367
+ console.error(`error: ${stackName}: ${msg}`);
13368
+ jsonError(stackName, region, msg);
13331
13369
  worst = Math.max(worst, 2);
13332
13370
  continue;
13333
13371
  }
@@ -13336,6 +13374,7 @@ async function runCheck(args) {
13336
13374
  const sKey = synthKey(stackName, region);
13337
13375
  if (synthTemplates && !synthTemplates.has(sKey)) {
13338
13376
  console.error(`note: ${stackName}: not in the synth output — skipped (--pre-deploy)`);
13377
+ jsonError(stackName, region, "not in the synth output — skipped (--pre-deploy)");
13339
13378
  continue;
13340
13379
  }
13341
13380
  const gathered = await gatherWithProgress(showProgress, progressLabel(idx, stacks.length, stackName, region), () => gatherFindings(stackName, region, synthTemplates?.get(sKey), template));
@@ -13360,14 +13399,18 @@ async function runCheck(args) {
13360
13399
  const declaredOnly = preDeployFindings(findings);
13361
13400
  if (!a.json) console.error(`note: ${stackName}: --pre-deploy reports declared drift only (undeclared tiers are evaluated against the deployed template — run check without --pre-deploy)`);
13362
13401
  if (!a.json) separate();
13363
- const preDeployCode = report(applyIgnores(declaredOnly, {
13402
+ const preDeployReconciled = applyIgnores(declaredOnly, {
13364
13403
  stackName,
13365
13404
  accountId: desired.accountId,
13366
13405
  region
13367
- }, config), `${posPrefix}${stackName} (${region})`, {
13368
- json: a.json,
13369
- verbose: a.verbose
13370
- });
13406
+ }, config);
13407
+ const preDeployHeader = `${posPrefix}${stackName} (${region})`;
13408
+ let preDeployCode;
13409
+ if (a.json) {
13410
+ const { json, code } = buildStackJson(preDeployReconciled, preDeployHeader);
13411
+ jsonReports.push(json);
13412
+ preDeployCode = code;
13413
+ } else preDeployCode = report(preDeployReconciled, preDeployHeader, { verbose: a.verbose });
13371
13414
  if (preDeployCode === 1) anyDrift = true;
13372
13415
  worst = Math.max(worst, finalCheckExit(preDeployCode, a.fail));
13373
13416
  worst = Math.max(worst, strictCoverageExit(a.strict, gathered.findings, desired.resources));
@@ -13394,8 +13437,13 @@ async function runCheck(args) {
13394
13437
  region
13395
13438
  }, config);
13396
13439
  if (!a.json) separate();
13397
- let code = report(reconciled, `${posPrefix}${stackName} (${region})`, {
13398
- json: a.json,
13440
+ const reportHeader = `${posPrefix}${stackName} (${region})`;
13441
+ let code;
13442
+ if (a.json) {
13443
+ const { json, code: jsonCode } = buildStackJson(reconciled, reportHeader);
13444
+ jsonReports.push(json);
13445
+ code = jsonCode;
13446
+ } else code = report(reconciled, reportHeader, {
13399
13447
  verbose: a.verbose,
13400
13448
  expandAtDefault: a.showAll
13401
13449
  });
@@ -13423,16 +13471,20 @@ async function runCheck(args) {
13423
13471
  } catch (e) {
13424
13472
  if (isStackNotDeployed(e)) {
13425
13473
  console.error(`note: ${stackName}: not deployed yet — skipped`);
13474
+ jsonError(stackName, region, "not deployed yet — skipped");
13426
13475
  continue;
13427
13476
  }
13428
13477
  if (e instanceof StackNotCheckableError) {
13429
13478
  console.error(`note: ${stackName}: ${e.message} — skipped`);
13479
+ jsonError(stackName, region, `${e.message} — skipped`);
13430
13480
  continue;
13431
13481
  }
13432
13482
  console.error(`error: ${stackName}: ${e.message}`);
13483
+ jsonError(stackName, region, e.message);
13433
13484
  worst = Math.max(worst, 2);
13434
13485
  }
13435
13486
  }
13487
+ if (a.json) console.log(JSON.stringify(jsonReports, null, 2));
13436
13488
  if (anyDrift && !a.fail && !a.json) console.error("note: drift found — exit 0 (report-only). Pass --fail to make drift fail this command.");
13437
13489
  return worst;
13438
13490
  }