cdk-real-drift 0.2.50 → 0.2.51

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
@@ -433,21 +433,29 @@ function validateIgnoreEntry(entry, index) {
433
433
  ]) if (obj[k] !== void 0 && typeof obj[k] !== "string") throw new Error(`${at}: "${k}" must be a string`);
434
434
  }
435
435
  /**
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.
436
+ * The exact ignore rule the `ignore` verb (and check's inline ignore) writes for a
437
+ * finding. The rule is STAMPED with the current stack / account / region scope (the same
438
+ * three identity axes a baseline file is keyed on), so ignoring a within-stack path on one
439
+ * stack does NOT leak to a same-named twin stack in another account/region — an unscoped
440
+ * `{ path }` was match-all, silently silencing the identical path everywhere (issue #757).
441
+ * The literal identity values are valid exact globs; hand-widening to a `*` glob stays a
442
+ * manual edit. A scope field is omitted only when genuinely unavailable (empty string).
443
+ * Prefer the human-friendly `<constructPath>.<path>` for `path` when present (CDK stacks):
444
+ * it is what `cdk-local` targets on and readable in the git-committed config diff. The
445
+ * construct path is written WITHIN the stack (the stack/Stage prefix stripped, given
446
+ * `stackName`) so it is byte-identical to what the report prints for the finding — copy
447
+ * what you see. Falls back to `<logicalId>.<path>`, ALWAYS present (the CloudFormation
448
+ * key) so a rule is writable even on a non-CDK / metadata-stripped stack. Pure + exported;
449
+ * `applyIgnores` matches the within-stack path, the full construct path (older rules), AND
450
+ * the logicalId, so every form works.
447
451
  */
448
- function ignoreRuleFor(finding, stackName = "") {
452
+ function ignoreRuleFor(finding, stackName = "", accountId = "", region = "") {
449
453
  const id = finding.constructPath ? withinStackPath(finding.constructPath, stackName) : finding.logicalId;
450
- return { path: finding.path ? `${id}.${finding.path}` : id };
454
+ const rule = { path: finding.path ? `${id}.${finding.path}` : id };
455
+ if (stackName) rule.stack = stackName;
456
+ if (accountId) rule.account = accountId;
457
+ if (region) rule.region = region;
458
+ return rule;
451
459
  }
452
460
  /** Canonical identity of a rule (path + the three optional scopes), for dedupe. */
453
461
  function ruleKey(r) {
@@ -9295,7 +9303,7 @@ function splitRecordedByBaseline(recorded, baseline) {
9295
9303
  function selectRecorded(findings, selectedKeys) {
9296
9304
  return buildRecorded(findings).filter((e) => selectedKeys.has(recordedKey(e)));
9297
9305
  }
9298
- const topSegment = (p) => p.split(".")[0] ?? p;
9306
+ const isTopLevelPath = (p) => !p.includes(".") && !p.includes("[");
9299
9307
  /**
9300
9308
  * Reconcile undeclared findings against the recorded baseline (per ENTRY, R62):
9301
9309
  * - an undeclared finding matching an recorded entry (same value) is suppressed;
@@ -9409,7 +9417,7 @@ function applyBaseline(findings, baseline, opts = {}) {
9409
9417
  removedFromTemplate.push(`${a.logicalId}.${a.path}`);
9410
9418
  continue;
9411
9419
  }
9412
- if (opts.declaredByLogical?.get(a.logicalId)?.has(topSegment(a.path))) {
9420
+ if (isTopLevelPath(a.path) && opts.declaredByLogical?.get(a.logicalId)?.has(a.path)) {
9413
9421
  promotedStale.push(`${a.logicalId}.${a.path}`);
9414
9422
  continue;
9415
9423
  }
@@ -11953,7 +11961,7 @@ function ignoreSelectOptions(ignorable, stackName = "") {
11953
11961
  * ignore` and (PR-B2) check's interactive flow, so both write rules identically.
11954
11962
  */
11955
11963
  async function ignoreStack(p) {
11956
- const { stackName, findings, yes, interactive } = p;
11964
+ const { stackName, findings, yes, interactive, accountId = "", region = "" } = p;
11957
11965
  const ignorable = findings.filter((f) => f.tier === "declared" || f.tier === "undeclared" || f.tier === "added");
11958
11966
  if (ignorable.length === 0) {
11959
11967
  console.log(style.clean(`${stackName}: no ignorable drift to ignore.`));
@@ -11993,7 +12001,7 @@ async function ignoreStack(p) {
11993
12001
  };
11994
12002
  }
11995
12003
  }
11996
- const { path, added, alreadyPresent } = await addIgnoreRules(chosen.map((f) => ignoreRuleFor(f, stackName)));
12004
+ const { path, added, alreadyPresent } = await addIgnoreRules(chosen.map((f) => ignoreRuleFor(f, stackName, accountId, region)));
11997
12005
  if (added.length > 0) {
11998
12006
  const dup = alreadyPresent.length > 0 ? `, ${alreadyPresent.length} already present` : "";
11999
12007
  console.log(style.ok(`ignore rule(s) added: ${path} (${added.length} new${dup})`));
@@ -12437,7 +12445,9 @@ async function runIgnore(args) {
12437
12445
  region
12438
12446
  }, config),
12439
12447
  yes: a.yes,
12440
- interactive: isInteractive()
12448
+ interactive: isInteractive(),
12449
+ accountId: desired.accountId,
12450
+ region
12441
12451
  });
12442
12452
  if (result.wrote) wroteAny = true;
12443
12453
  if (result.refused) worst = Math.max(worst, 2);
@@ -12622,6 +12632,19 @@ function groupReasons(items) {
12622
12632
  }
12623
12633
  return [...counts.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).map(([k, c]) => `${k} ${c}`).join(", ");
12624
12634
  }
12635
+ function buildStackJson(rawFindings, header) {
12636
+ const findings = annotateHints(rawFindings);
12637
+ const isDriftHere = (f) => DRIFT_TIERS.includes(f.tier) && !f.unrecorded;
12638
+ const drifted = findings.filter(isDriftHere).length;
12639
+ return {
12640
+ json: {
12641
+ stack: header,
12642
+ drifted,
12643
+ findings
12644
+ },
12645
+ code: drifted === 0 ? 0 : 1
12646
+ };
12647
+ }
12625
12648
  function report(rawFindings, header, opts = {}) {
12626
12649
  const log = opts.log ?? console.log;
12627
12650
  const stackName = stackNameFromHeader(header);
@@ -12629,11 +12652,7 @@ function report(rawFindings, header, opts = {}) {
12629
12652
  const isDriftHere = (f) => DRIFT_TIERS.includes(f.tier) && !f.unrecorded;
12630
12653
  const drifted = findings.filter(isDriftHere).length;
12631
12654
  if (opts.json) {
12632
- log(JSON.stringify({
12633
- stack: header,
12634
- drifted,
12635
- findings
12636
- }, null, 2));
12655
+ log(JSON.stringify(buildStackJson(rawFindings, header).json, null, 2));
12637
12656
  return drifted === 0 ? 0 : 1;
12638
12657
  }
12639
12658
  const byTier = (t) => findings.filter((f) => f.tier === t && !f.unrecorded);
@@ -13137,7 +13156,9 @@ async function ignoreAll(p) {
13137
13156
  stackName: p.stackName,
13138
13157
  findings,
13139
13158
  yes: p.yes,
13140
- interactive: true
13159
+ interactive: true,
13160
+ accountId: p.desired.accountId,
13161
+ region: p.region
13141
13162
  })).wrote ? {
13142
13163
  exit: await recomputeExit(p, /* @__PURE__ */ new Set()),
13143
13164
  awsMutated: false
@@ -13202,7 +13223,9 @@ async function perFinding(p, decidable) {
13202
13223
  stackName: p.stackName,
13203
13224
  findings: groups.ignore,
13204
13225
  yes: true,
13205
- interactive: true
13226
+ interactive: true,
13227
+ accountId: p.desired.accountId,
13228
+ region: p.region
13206
13229
  });
13207
13230
  let revertResolved = /* @__PURE__ */ new Set();
13208
13231
  let revertExit = 0;
@@ -13323,11 +13346,22 @@ async function runCheck(args) {
13323
13346
  }
13324
13347
  let worst = 0;
13325
13348
  let anyDrift = false;
13349
+ const jsonReports = [];
13350
+ const jsonError = (stackName, region, message) => {
13351
+ if (a.json) jsonReports.push({
13352
+ stack: region ? `${stackName} (${region})` : stackName,
13353
+ drifted: 0,
13354
+ findings: [],
13355
+ error: message
13356
+ });
13357
+ };
13326
13358
  const separate = stackSeparator();
13327
13359
  const showProgress = !a.json && isInteractive();
13328
13360
  for (const [idx, { stackName, region, template }] of stacks.entries()) {
13329
13361
  if (!region) {
13330
- console.error(`error: ${stackName}: no region — set env on the stack, pass --region, or set a region for the AWS profile`);
13362
+ const msg = "no region — set env on the stack, pass --region, or set a region for the AWS profile";
13363
+ console.error(`error: ${stackName}: ${msg}`);
13364
+ jsonError(stackName, region, msg);
13331
13365
  worst = Math.max(worst, 2);
13332
13366
  continue;
13333
13367
  }
@@ -13336,6 +13370,7 @@ async function runCheck(args) {
13336
13370
  const sKey = synthKey(stackName, region);
13337
13371
  if (synthTemplates && !synthTemplates.has(sKey)) {
13338
13372
  console.error(`note: ${stackName}: not in the synth output — skipped (--pre-deploy)`);
13373
+ jsonError(stackName, region, "not in the synth output — skipped (--pre-deploy)");
13339
13374
  continue;
13340
13375
  }
13341
13376
  const gathered = await gatherWithProgress(showProgress, progressLabel(idx, stacks.length, stackName, region), () => gatherFindings(stackName, region, synthTemplates?.get(sKey), template));
@@ -13360,14 +13395,18 @@ async function runCheck(args) {
13360
13395
  const declaredOnly = preDeployFindings(findings);
13361
13396
  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
13397
  if (!a.json) separate();
13363
- const preDeployCode = report(applyIgnores(declaredOnly, {
13398
+ const preDeployReconciled = applyIgnores(declaredOnly, {
13364
13399
  stackName,
13365
13400
  accountId: desired.accountId,
13366
13401
  region
13367
- }, config), `${posPrefix}${stackName} (${region})`, {
13368
- json: a.json,
13369
- verbose: a.verbose
13370
- });
13402
+ }, config);
13403
+ const preDeployHeader = `${posPrefix}${stackName} (${region})`;
13404
+ let preDeployCode;
13405
+ if (a.json) {
13406
+ const { json, code } = buildStackJson(preDeployReconciled, preDeployHeader);
13407
+ jsonReports.push(json);
13408
+ preDeployCode = code;
13409
+ } else preDeployCode = report(preDeployReconciled, preDeployHeader, { verbose: a.verbose });
13371
13410
  if (preDeployCode === 1) anyDrift = true;
13372
13411
  worst = Math.max(worst, finalCheckExit(preDeployCode, a.fail));
13373
13412
  worst = Math.max(worst, strictCoverageExit(a.strict, gathered.findings, desired.resources));
@@ -13394,8 +13433,13 @@ async function runCheck(args) {
13394
13433
  region
13395
13434
  }, config);
13396
13435
  if (!a.json) separate();
13397
- let code = report(reconciled, `${posPrefix}${stackName} (${region})`, {
13398
- json: a.json,
13436
+ const reportHeader = `${posPrefix}${stackName} (${region})`;
13437
+ let code;
13438
+ if (a.json) {
13439
+ const { json, code: jsonCode } = buildStackJson(reconciled, reportHeader);
13440
+ jsonReports.push(json);
13441
+ code = jsonCode;
13442
+ } else code = report(reconciled, reportHeader, {
13399
13443
  verbose: a.verbose,
13400
13444
  expandAtDefault: a.showAll
13401
13445
  });
@@ -13423,16 +13467,20 @@ async function runCheck(args) {
13423
13467
  } catch (e) {
13424
13468
  if (isStackNotDeployed(e)) {
13425
13469
  console.error(`note: ${stackName}: not deployed yet — skipped`);
13470
+ jsonError(stackName, region, "not deployed yet — skipped");
13426
13471
  continue;
13427
13472
  }
13428
13473
  if (e instanceof StackNotCheckableError) {
13429
13474
  console.error(`note: ${stackName}: ${e.message} — skipped`);
13475
+ jsonError(stackName, region, `${e.message} — skipped`);
13430
13476
  continue;
13431
13477
  }
13432
13478
  console.error(`error: ${stackName}: ${e.message}`);
13479
+ jsonError(stackName, region, e.message);
13433
13480
  worst = Math.max(worst, 2);
13434
13481
  }
13435
13482
  }
13483
+ if (a.json) console.log(JSON.stringify(jsonReports, null, 2));
13436
13484
  if (anyDrift && !a.fail && !a.json) console.error("note: drift found — exit 0 (report-only). Pass --fail to make drift fail this command.");
13437
13485
  return worst;
13438
13486
  }