cdk-real-drift 0.18.11 → 0.18.12

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
@@ -1024,9 +1024,13 @@ covers them. **If you never run `revert`, cdkrd needs no write permissions at al
1024
1024
  re-surfaces as drift — otherwise invisible (the function `Code` is write-only and
1025
1025
  a later `cdk deploy` does not heal it). It folds silently on a clean deploy
1026
1026
  (zero first-run noise), `record` snapshots it, and a later change re-surfaces as
1027
- "changed since record". The old code bytes are gone, so it is detect-only (not
1028
- revertable — redeploy with a forced code update). Without the permission the
1029
- signal is skipped, never false-flagged.
1027
+ "changed since record". A **legitimate** `cdk deploy` that updates the code
1028
+ does NOT re-surface it: `record` also fingerprints the declared `Code`, so a
1029
+ hash that moved because the template's code changed folds into a re-record
1030
+ nudge instead of false drift (same for the Glue script hash below). The old
1031
+ code bytes are gone, so it is detect-only (not revertable — redeploy with a
1032
+ forced code update). Without the permission the signal is skipped, never
1033
+ false-flagged.
1030
1034
  - Optional: `glue:GetJob` + `s3:GetObject` (on the script bucket) record a content
1031
1035
  hash of an `AWS::Glue::Job`'s ETL script (`ScriptSha256`, fetched from
1032
1036
  `Command.ScriptLocation`) so an out-of-band script swap at the **same S3 key**
package/dist/cli.js CHANGED
@@ -15251,6 +15251,9 @@ function hashOfCanonical(canonicalValue) {
15251
15251
  function redactedHashSentinel(canonicalValue) {
15252
15252
  return { [REDACTION_HASH_KEY]: hashOfCanonical(canonicalValue) };
15253
15253
  }
15254
+ function stableValueHash(value) {
15255
+ return hashOfCanonical(value);
15256
+ }
15254
15257
  function isRedactedHashSentinel(v) {
15255
15258
  return !!v && typeof v === "object" && !Array.isArray(v) && Object.keys(v).length === 1 && typeof v[REDACTION_HASH_KEY] === "string";
15256
15259
  }
@@ -15269,7 +15272,8 @@ const KNOWN_BASELINE_KEYS = new Set([
15269
15272
  "templateHash",
15270
15273
  "recorded",
15271
15274
  "completeResources",
15272
- "recordedPhysicalIds"
15275
+ "recordedPhysicalIds",
15276
+ "recordedSourceFingerprints"
15273
15277
  ]);
15274
15278
  const KNOWN_RECORDED_ENTRY_KEYS = new Set([
15275
15279
  "logicalId",
@@ -15329,6 +15333,7 @@ async function loadBaseline(stackName, accountId, region) {
15329
15333
  validateRecordedUniqueness(parsed.recorded, path);
15330
15334
  validateCompleteResources(parsed.completeResources, path);
15331
15335
  validateRecordedPhysicalIds(parsed.recordedPhysicalIds, path);
15336
+ validateRecordedSourceFingerprints(parsed.recordedSourceFingerprints, path);
15332
15337
  return parsed;
15333
15338
  }
15334
15339
  /**
@@ -15407,6 +15412,18 @@ function validateRecordedPhysicalIds(value, path) {
15407
15412
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${at} must be an object mapping logicalId to physical id`);
15408
15413
  for (const [key, v] of Object.entries(value)) if (typeof v !== "string") throw new Error(`${at}: "${key}" must map to a string`);
15409
15414
  }
15415
+ /**
15416
+ * Validate `recordedSourceFingerprints` (optional). When present it must be a plain object
15417
+ * mapping string recordedKey -> string fingerprint — a non-object or a non-string value would
15418
+ * otherwise mis-drive the stale-source void silently (the same loud-vs-silent principle as
15419
+ * validateRecordedPhysicalIds). Reject bad shapes loudly, naming the file + key.
15420
+ */
15421
+ function validateRecordedSourceFingerprints(value, path) {
15422
+ if (value === void 0) return;
15423
+ const at = `baseline file ${path}: \`recordedSourceFingerprints\``;
15424
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${at} must be an object mapping "<logicalId>::<path>" to a fingerprint`);
15425
+ for (const [key, v] of Object.entries(value)) if (typeof v !== "string") throw new Error(`${at}: "${key}" must map to a string`);
15426
+ }
15410
15427
  /** Deterministic order for `recorded` entries: lexicographic by (logicalId, path).
15411
15428
  * The single point where order is imposed — read/compare logic is order-independent,
15412
15429
  * so this only affects the bytes on disk. Without it the entries inherit findings
@@ -15429,6 +15446,12 @@ function sortedPhysicalIds(ids, recorded, complete) {
15429
15446
  for (const key of Object.keys(ids).sort()) if (persist.has(key) && ids[key] !== void 0) out[key] = ids[key];
15430
15447
  return out;
15431
15448
  }
15449
+ function sortedSourceFingerprints(fps, recorded) {
15450
+ const persist = new Set(recorded.map((e) => recordedKey(e)));
15451
+ const out = {};
15452
+ for (const key of Object.keys(fps).sort()) if (persist.has(key) && fps[key] !== void 0) out[key] = fps[key];
15453
+ return out;
15454
+ }
15432
15455
  async function writeBaselineFile(b) {
15433
15456
  const p = baselinePath(b.stackName, b.accountId, b.region);
15434
15457
  await mkdir(dirname(p), { recursive: true });
@@ -15436,7 +15459,8 @@ async function writeBaselineFile(b) {
15436
15459
  ...b,
15437
15460
  recorded: sortRecorded(b.recorded),
15438
15461
  ...b.completeResources ? { completeResources: [...b.completeResources].sort() } : {},
15439
- ...b.recordedPhysicalIds ? { recordedPhysicalIds: sortedPhysicalIds(b.recordedPhysicalIds, b.recorded, b.completeResources ?? []) } : {}
15462
+ ...b.recordedPhysicalIds ? { recordedPhysicalIds: sortedPhysicalIds(b.recordedPhysicalIds, b.recorded, b.completeResources ?? []) } : {},
15463
+ ...b.recordedSourceFingerprints ? { recordedSourceFingerprints: sortedSourceFingerprints(b.recordedSourceFingerprints, b.recorded) } : {}
15440
15464
  };
15441
15465
  await writeFile(p, JSON.stringify(stable, null, 2) + "\n", "utf8");
15442
15466
  return p;
@@ -15506,7 +15530,8 @@ async function writeBaseline(stackName, region, accountId, findings, rawTemplate
15506
15530
  templateHash: hashTemplate(rawTemplate),
15507
15531
  recorded,
15508
15532
  completeResources,
15509
- ...buildRecordedPhysicalIds(recorded, completeResources, opts.physicalIdByLogical, opts.previous)
15533
+ ...buildRecordedPhysicalIds(recorded, completeResources, opts.physicalIdByLogical, opts.previous),
15534
+ ...buildRecordedSourceFingerprints(recorded, opts.declaredByLogical, opts.previous)
15510
15535
  }),
15511
15536
  count: recorded.length
15512
15537
  };
@@ -15556,6 +15581,48 @@ const RECORDABLE_GENERATED_PATHS = {
15556
15581
  function isRecordableGenerated(f) {
15557
15582
  return f.tier === "generated" && (RECORDABLE_GENERATED_PATHS[f.resourceType]?.has(f.path) ?? false);
15558
15583
  }
15584
+ const RECORDABLE_GENERATED_SOURCE_PATHS = {
15585
+ "AWS::Lambda::Function": { CodeSha256: "Code" },
15586
+ "AWS::Glue::Job": { ScriptSha256: "Command.ScriptLocation" }
15587
+ };
15588
+ /**
15589
+ * Fingerprint of a recordable-generated entry's DECLARED SOURCE value (deep key-sorted
15590
+ * content hash), or undefined when the (resourceType, path) has no source mapping, no
15591
+ * declared model is available, or the source path does not resolve in it — the undefined
15592
+ * cases all fall back to today's behavior (never void on unknown).
15593
+ */
15594
+ function declaredSourceFingerprint(resourceType, path, declared) {
15595
+ const sourcePath = RECORDABLE_GENERATED_SOURCE_PATHS[resourceType]?.[path];
15596
+ if (sourcePath === void 0 || declared === void 0) return void 0;
15597
+ let node = declared;
15598
+ for (const seg of pathSegments$1(sourcePath)) {
15599
+ node = descendDeclared(node, seg);
15600
+ if (node === void 0) return void 0;
15601
+ }
15602
+ return stableValueHash(node);
15603
+ }
15604
+ /**
15605
+ * Build the `recordedSourceFingerprints` map for the entries being written. For each entry
15606
+ * with a source mapping: prefer the PREVIOUS baseline's fingerprint when the entry's VALUE
15607
+ * was carried forward unchanged from it (a resource unread this run — e.g. skipped — must
15608
+ * keep its hash paired with the template that deployed it, else a re-record after a legit
15609
+ * code deploy would pair the OLD hash with the NEW template and resurface the FP);
15610
+ * otherwise stamp the CURRENT declared source's fingerprint (falling back to the previous
15611
+ * one when the source does not resolve). Returns `{}` (spread to nothing) when no
15612
+ * fingerprint is known, so the field stays absent on baselines without any.
15613
+ */
15614
+ function buildRecordedSourceFingerprints(recorded, declaredByLogical, previous) {
15615
+ const out = {};
15616
+ for (const e of recorded) {
15617
+ if (RECORDABLE_GENERATED_SOURCE_PATHS[e.resourceType]?.[e.path] === void 0) continue;
15618
+ const key = recordedKey(e);
15619
+ const prevFp = previous?.recordedSourceFingerprints?.[key];
15620
+ const prevEntry = previous?.recorded.find((a) => a.logicalId === e.logicalId && a.path === e.path && a.resourceType === e.resourceType);
15621
+ const fp = prevFp !== void 0 && prevEntry !== void 0 && deepEqual(prevEntry.value, e.value) ? prevFp : declaredSourceFingerprint(e.resourceType, e.path, declaredByLogical?.get(e.logicalId)) ?? prevFp;
15622
+ if (fp !== void 0) out[key] = fp;
15623
+ }
15624
+ return Object.keys(out).length > 0 ? { recordedSourceFingerprints: out } : {};
15625
+ }
15559
15626
  /** Build the recorded set from a check run's findings: undeclared PROPERTIES plus
15560
15627
  * out-of-band `added` RESOURCES (PR4 — `added` is the resource-granularity sibling of
15561
15628
  * undeclared, so `record` snapshots its full live model and a later change to it
@@ -15919,6 +15986,14 @@ function applyBaseline(findings, baseline, opts = {}) {
15919
15986
  const liveId = opts.physicalIdByLogical?.get(logicalId);
15920
15987
  if (liveId !== void 0 && liveId !== recordedId) replacedLogical.add(logicalId);
15921
15988
  }
15989
+ const sourceRedeployedVoid = /* @__PURE__ */ new Set();
15990
+ const recordedSourceFps = baseline.recordedSourceFingerprints ?? {};
15991
+ for (const e of recorded) {
15992
+ const storedFp = recordedSourceFps[recordedKey(e)];
15993
+ if (storedFp === void 0) continue;
15994
+ const currentFp = declaredSourceFingerprint(e.resourceType, e.path, opts.declaredByLogical?.get(e.logicalId));
15995
+ if (currentFp !== void 0 && currentFp !== storedFp) sourceRedeployedVoid.add(recordedKey(e));
15996
+ }
15922
15997
  const liveTypeByLogical = /* @__PURE__ */ new Map();
15923
15998
  for (const f of findings) if (f.resourceType) liveTypeByLogical.set(f.logicalId, f.resourceType);
15924
15999
  const isTypeVoid = (e) => {
@@ -15956,7 +16031,8 @@ function applyBaseline(findings, baseline, opts = {}) {
15956
16031
  kept.push(f);
15957
16032
  continue;
15958
16033
  }
15959
- const entry = replacedLogical.has(f.logicalId) ? void 0 : recorded.find((a) => entryMatches(a, f));
16034
+ const matched = replacedLogical.has(f.logicalId) ? void 0 : recorded.find((a) => entryMatches(a, f));
16035
+ const entry = matched !== void 0 && sourceRedeployedVoid.has(recordedKey(matched)) ? void 0 : matched;
15960
16036
  if (entry && baselineValueMatches(entry.value, f.actual, f.resourceType, f.path)) continue;
15961
16037
  if (entry) {
15962
16038
  const delta = identityArrayDelta(canonicalizeForCompare(entry.value, f.resourceType), f.actual);
@@ -16000,6 +16076,7 @@ function applyBaseline(findings, baseline, opts = {}) {
16000
16076
  const typeMismatchStale = [];
16001
16077
  const adoptedStale = [];
16002
16078
  const nameStrippedStale = [];
16079
+ const sourceRedeployedStale = [];
16003
16080
  for (const a of recorded) {
16004
16081
  if (a.path === "") {
16005
16082
  if (presentAddedLogical.has(a.logicalId)) continue;
@@ -16027,6 +16104,10 @@ function applyBaseline(findings, baseline, opts = {}) {
16027
16104
  replacedStale.push(`${a.logicalId}.${a.path}`);
16028
16105
  continue;
16029
16106
  }
16107
+ if (sourceRedeployedVoid.has(recordedKey(a))) {
16108
+ sourceRedeployedStale.push(`${a.logicalId}.${a.path}`);
16109
+ continue;
16110
+ }
16030
16111
  if (currentPaths.has(`${a.logicalId}.${a.path}`)) continue;
16031
16112
  if (skippedLogical.has(a.logicalId)) continue;
16032
16113
  if (deletedLogical.has(a.logicalId)) continue;
@@ -16061,9 +16142,21 @@ function applyBaseline(findings, baseline, opts = {}) {
16061
16142
  if (typeMismatchStale.length > 0) opts.warn?.(formatTypeMismatchStaleNote(typeMismatchStale));
16062
16143
  if (adoptedStale.length > 0) opts.warn?.(formatAdoptedStaleNote(adoptedStale));
16063
16144
  if (nameStrippedStale.length > 0) opts.warn?.(formatNameStrippedStaleNote(nameStrippedStale));
16145
+ if (sourceRedeployedStale.length > 0) opts.warn?.(formatSourceRedeployedStaleNote(sourceRedeployedStale));
16064
16146
  return kept;
16065
16147
  }
16066
16148
  /**
16149
+ * The folded one-line note for recorded content-hash entries whose DECLARED SOURCE was
16150
+ * redeployed through CloudFormation since record (a legit IaC code update — the recorded
16151
+ * hash is stale, not violated). Until the user re-records, the new code's hash is not
16152
+ * being watched, so the nudge matters: a swap AFTER the redeploy is invisible until then.
16153
+ * Mirror of formatReplacedStaleNote. Pure + exported for unit tests.
16154
+ */
16155
+ function formatSourceRedeployedStaleNote(paths) {
16156
+ const n = paths.length;
16157
+ return `note: ${n === 1 ? `baseline entry (${paths[0]}) is a content hash whose` : `${n} baseline entries are content hashes whose`} declared code was redeployed via CloudFormation since record — re-run \`cdkrd record\` to watch the new code.`;
16158
+ }
16159
+ /**
16067
16160
  * The folded one-line note for baseline entries now declared in the template (R134). One
16068
16161
  * line with a count instead of one line per entry; `record` re-snapshots to clear them.
16069
16162
  * Pure + exported for unit tests.
@@ -19987,7 +20080,8 @@ async function recordStack(p) {
19987
20080
  const { path, count } = await writeBaseline(stackName, region, desired.accountId, findings, desired.rawTemplate, recorded, {
19988
20081
  allLogicalIds: desired.resources.map((r) => r.logicalId),
19989
20082
  previous: existing,
19990
- physicalIdByLogical: physicalIdsByLogical(desired.resources)
20083
+ physicalIdByLogical: physicalIdsByLogical(desired.resources),
20084
+ declaredByLogical: declaredKeysByLogical(desired.resources)
19991
20085
  });
19992
20086
  if (!p.json) console.log(style.ok(recordOutcomeMessage(stackName, path, count, refreshedOnly, !!existing)));
19993
20087
  const scopeNote = recordScopeNote(stackName, findings);