cdk-real-drift 0.2.56 → 0.2.57

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/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
3
  import { mkdir, readFile, writeFile } from "node:fs/promises";
4
4
  import { dirname, join, resolve } from "node:path";
5
5
  import { YAMLSeq, isSeq, parse, parseDocument } from "yaml";
@@ -9162,12 +9162,16 @@ function validateRecordedPhysicalIds(value, path) {
9162
9162
  function sortRecorded(recorded) {
9163
9163
  return [...recorded].sort((a, b) => (a.logicalId < b.logicalId ? -1 : a.logicalId > b.logicalId ? 1 : 0) || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
9164
9164
  }
9165
- /** #674: keep only physical ids for logicalIds that still carry a recorded entry, with
9166
- * sorted keys, so the baseline JSON is byte-stable and free of dead entries. */
9167
- function sortedPhysicalIds(ids, recorded) {
9168
- const live = new Set(recorded.map((e) => e.logicalId));
9165
+ /** #674/#792: keep physical ids for logicalIds that either carry a recorded entry OR
9166
+ * are snapshot-`complete` (a complete resource with ZERO undeclared entries has nothing
9167
+ * in `recorded`, but its physical id must still be persisted so #674's replacement void
9168
+ * fires for it — else an out-of-band REPLACEMENT of a zero-entry complete resource, whose
9169
+ * fresh AWS defaults now "appear since record", surfaces as false drift). Sorted keys keep
9170
+ * the JSON byte-stable; a logicalId neither recorded nor complete is dropped as dead. */
9171
+ function sortedPhysicalIds(ids, recorded, complete) {
9172
+ const persist = new Set([...recorded.map((e) => e.logicalId), ...complete]);
9169
9173
  const out = {};
9170
- for (const key of Object.keys(ids).sort()) if (live.has(key) && ids[key] !== void 0) out[key] = ids[key];
9174
+ for (const key of Object.keys(ids).sort()) if (persist.has(key) && ids[key] !== void 0) out[key] = ids[key];
9171
9175
  return out;
9172
9176
  }
9173
9177
  async function writeBaselineFile(b) {
@@ -9177,7 +9181,7 @@ async function writeBaselineFile(b) {
9177
9181
  ...b,
9178
9182
  recorded: sortRecorded(b.recorded),
9179
9183
  ...b.completeResources ? { completeResources: [...b.completeResources].sort() } : {},
9180
- ...b.recordedPhysicalIds ? { recordedPhysicalIds: sortedPhysicalIds(b.recordedPhysicalIds, b.recorded) } : {}
9184
+ ...b.recordedPhysicalIds ? { recordedPhysicalIds: sortedPhysicalIds(b.recordedPhysicalIds, b.recorded, b.completeResources ?? []) } : {}
9181
9185
  };
9182
9186
  await writeFile(p, JSON.stringify(stable, null, 2) + "\n", "utf8");
9183
9187
  return p;
@@ -9213,7 +9217,7 @@ function computeCompleteResources(allLogicalIds, findings, recorded, previousCom
9213
9217
  * (read clean) would be invisible here; `opts.previous` keeps completeness
9214
9218
  * monotonic across re-records. */
9215
9219
  async function writeBaseline(stackName, region, accountId, findings, rawTemplate, recorded = buildRecorded(findings), opts = {}) {
9216
- const allIds = opts.allLogicalIds ?? [...new Set([...findings.map((f) => f.logicalId), ...recorded.map((a) => a.logicalId)])];
9220
+ const completeResources = computeCompleteResources(opts.allLogicalIds ?? [...new Set([...findings.map((f) => f.logicalId), ...recorded.map((a) => a.logicalId)])], findings, recorded, opts.previous?.completeResources ?? []);
9217
9221
  return {
9218
9222
  path: await writeBaselineFile({
9219
9223
  schemaVersion: 2,
@@ -9223,26 +9227,32 @@ async function writeBaseline(stackName, region, accountId, findings, rawTemplate
9223
9227
  capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
9224
9228
  templateHash: hashTemplate(rawTemplate),
9225
9229
  recorded,
9226
- completeResources: computeCompleteResources(allIds, findings, recorded, opts.previous?.completeResources ?? []),
9227
- ...buildRecordedPhysicalIds(recorded, opts.physicalIdByLogical, opts.previous)
9230
+ completeResources,
9231
+ ...buildRecordedPhysicalIds(recorded, completeResources, opts.physicalIdByLogical, opts.previous)
9228
9232
  }),
9229
9233
  count: recorded.length
9230
9234
  };
9231
9235
  }
9232
9236
  /**
9233
- * #674: build the `recordedPhysicalIds` map (logicalId -> physical id) for the entries
9234
- * being written. Prefers the physical id resolved THIS run; falls back to the previous
9235
- * baseline's stored id when this run did not resolve one (a resource skipped / with no
9236
- * physical id must not lose its previously-captured id on re-record — else a later
9237
- * replacement could not be detected). Returns `{}` (spread to nothing) when no id is
9238
- * known, so the field stays absent on baselines with no physical ids at all.
9237
+ * #674/#792: build the `recordedPhysicalIds` map (logicalId -> physical id) for the
9238
+ * resources being written. Covers every RECORDED logicalId PLUS every snapshot-`complete`
9239
+ * resource — the latter so a resource recorded as complete but with ZERO undeclared
9240
+ * entries (nothing in `recorded`) still carries its physical id, letting #674's replacement
9241
+ * void fire for it too (an out-of-band REPLACEMENT of such a resource must not surface as
9242
+ * false "appeared since record" drift; see #792). Prefers the physical id resolved THIS
9243
+ * run; falls back to the previous baseline's stored id when this run did not resolve one
9244
+ * (a resource skipped / with no physical id must not lose its previously-captured id on
9245
+ * re-record — else a later replacement could not be detected). A resource with no known
9246
+ * physical id (this run or prior) is simply absent — today's behavior, never invented.
9247
+ * Returns `{}` (spread to nothing) when no id is known, so the field stays absent on
9248
+ * baselines with no physical ids at all.
9239
9249
  */
9240
- function buildRecordedPhysicalIds(recorded, live, previous) {
9250
+ function buildRecordedPhysicalIds(recorded, complete, live, previous) {
9241
9251
  const prior = previous?.recordedPhysicalIds ?? {};
9242
9252
  const out = {};
9243
- for (const e of recorded) {
9244
- const id = live?.get(e.logicalId) ?? prior[e.logicalId];
9245
- if (id !== void 0) out[e.logicalId] = id;
9253
+ for (const logicalId of new Set([...recorded.map((e) => e.logicalId), ...complete])) {
9254
+ const id = live?.get(logicalId) ?? prior[logicalId];
9255
+ if (id !== void 0) out[logicalId] = id;
9246
9256
  }
9247
9257
  return Object.keys(out).length > 0 ? { recordedPhysicalIds: out } : {};
9248
9258
  }
@@ -11746,16 +11756,40 @@ function rejectedEmptyStripOps(resourceType, ops, liveRaw) {
11746
11756
  }
11747
11757
  return out;
11748
11758
  }
11749
- /** Serialize a RevertItem's ops to an RFC6902 PatchDocument string for Cloud Control. */
11759
+ function hasArrayIndexSegment(pointer) {
11760
+ return pointer.split("/").some((seg) => /^\d+$/.test(seg));
11761
+ }
11762
+ /**
11763
+ * Serialize a RevertItem's ops to an RFC6902 PatchDocument string for Cloud Control.
11764
+ *
11765
+ * #762: the Cloud Control path had no analogue of the SDK-writer guard (writers.ts
11766
+ * `desiredModel` re-reads + re-canonicalizes the live model so an indexed op lands on the
11767
+ * SAME element classify diffed). For an INDEX-BEARING pointer we emit a preceding RFC6902
11768
+ * `test` precondition asserting the addressed location still equals the value classify saw
11769
+ * (`op.prior` = the finding's live `actual`). Cloud Control accepts standard RFC6902 and
11770
+ * evaluates `test` atomically before the mutation, so a shifted index makes it REJECT the
11771
+ * whole patch instead of writing the wrong element — fail-closed, the same intent as the
11772
+ * writer-path re-read. Scalar non-indexed pointers carry no aliasing risk (a named property
11773
+ * is stable regardless of array order), so they get NO `test` op — the patch stays minimal.
11774
+ */
11750
11775
  function toPatchDocument(item) {
11751
- return JSON.stringify(item.ops.map(({ op, path, value }) => op === "remove" ? {
11752
- op,
11753
- path
11754
- } : {
11755
- op,
11756
- path,
11757
- value
11758
- }));
11776
+ const doc = [];
11777
+ for (const { op, path, value, prior } of item.ops) {
11778
+ if (hasArrayIndexSegment(path) && prior !== void 0) doc.push({
11779
+ op: "test",
11780
+ path,
11781
+ value: prior
11782
+ });
11783
+ doc.push(op === "remove" ? {
11784
+ op,
11785
+ path
11786
+ } : {
11787
+ op,
11788
+ path,
11789
+ value
11790
+ });
11791
+ }
11792
+ return JSON.stringify(doc);
11759
11793
  }
11760
11794
 
11761
11795
  //#endregion
@@ -13440,6 +13474,28 @@ function strictCoverageExit(strict, findings, resources) {
13440
13474
  function finalCheckExit(code, fail) {
13441
13475
  return fail || code !== 1 ? code : 0;
13442
13476
  }
13477
+ /**
13478
+ * #781: does a committed baseline exist for this stack, under ANY account/region axis?
13479
+ * When a stack is gone (a DescribeStacks "does not exist"), we do NOT know the
13480
+ * account/region it was deployed to, so we cannot construct the exact baseline path.
13481
+ * A committed baseline is named `<stackName>.<accountId>.<region>.json` under
13482
+ * `.cdkrd/baselines/`, so match by the `<stackName>.` filename prefix across the whole
13483
+ * directory — a prior baseline is PROOF the stack was once deployed, which distinguishes
13484
+ * "deleted out of band" (real drift) from "never deployed yet" (a benign skip). The
13485
+ * baselines directory is derived from `baselinePath` so the layout stays single-sourced.
13486
+ * Pure (filesystem-only, no AWS) + exported for unit tests. Missing dir → false.
13487
+ */
13488
+ function hasBaselineForStack(stackName) {
13489
+ const dir = dirname(baselinePath(stackName, "a", "r"));
13490
+ let entries;
13491
+ try {
13492
+ entries = readdirSync(dir);
13493
+ } catch {
13494
+ return false;
13495
+ }
13496
+ const prefix = `${stackName}.`;
13497
+ return entries.some((f) => f.startsWith(prefix) && f.endsWith(".json"));
13498
+ }
13443
13499
  async function runCheck(args) {
13444
13500
  const a = parseCommonArgs(args, "check");
13445
13501
  if (a.profile) process.env.AWS_PROFILE = a.profile;
@@ -13602,6 +13658,14 @@ async function runCheck(args) {
13602
13658
  worst = Math.max(worst, strictCoverageExit(a.strict, gathered.findings, desired.resources));
13603
13659
  } catch (e) {
13604
13660
  if (isStackNotDeployed(e)) {
13661
+ if (hasBaselineForStack(stackName)) {
13662
+ const msg = "deployed baseline exists but the stack is gone — deleted out of band";
13663
+ console.error(`[Drift] ${stackName} (${region}): ${msg}`);
13664
+ jsonError(stackName, region, msg);
13665
+ worst = Math.max(worst, finalCheckExit(1, a.fail), a.strict ? 1 : 0);
13666
+ anyDrift = true;
13667
+ continue;
13668
+ }
13605
13669
  console.error(`note: ${stackName}: not deployed yet — skipped`);
13606
13670
  jsonError(stackName, region, "not deployed yet — skipped");
13607
13671
  continue;