cdk-real-drift 0.18.10 → 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
@@ -3108,7 +3108,8 @@ const KNOWN_DEFAULT_PATHS = {
3108
3108
  "AWS::OpenSearchService::Domain": {
3109
3109
  "EBSOptions.Iops": 3e3,
3110
3110
  "EBSOptions.Throughput": 125,
3111
- "ClusterConfig.ZoneAwarenessConfig": { AvailabilityZoneCount: 2 }
3111
+ "ClusterConfig.ZoneAwarenessConfig": { AvailabilityZoneCount: 2 },
3112
+ "ClusterConfig.DedicatedMasterCount": 3
3112
3113
  },
3113
3114
  "AWS::KinesisFirehose::DeliveryStream": {
3114
3115
  "ExtendedS3DestinationConfiguration.S3BackupMode": "Disabled",
@@ -6223,6 +6224,33 @@ function clbDefaultSslPoliciesAtDefault(resourceType, key, value) {
6223
6224
  if (!Array.isArray(value) || value.length === 0) return false;
6224
6225
  return value.every((el) => isNestedObject(el) && el["PolicyType"] === "SSLNegotiationPolicyType" && el["PolicyName"] === CLB_DEFAULT_SSL_POLICY_NAME);
6225
6226
  }
6227
+ const VPN_TUNNEL_EMPTY_LIST_KEYS = new Set([
6228
+ "Phase1EncryptionAlgorithms",
6229
+ "Phase1IntegrityAlgorithms",
6230
+ "Phase1DHGroupNumbers",
6231
+ "Phase2EncryptionAlgorithms",
6232
+ "Phase2IntegrityAlgorithms",
6233
+ "Phase2DHGroupNumbers",
6234
+ "IKEVersions"
6235
+ ]);
6236
+ const VPN_TUNNEL_INSIDE_CIDR = /^169\.254\.\d{1,3}\.\d{1,3}\/30$/;
6237
+ function vpnTunnelOptionsAtDefault(resourceType, key, value) {
6238
+ if (resourceType !== "AWS::EC2::VPNConnection" || key !== "VpnTunnelOptionsSpecifications") return false;
6239
+ if (!Array.isArray(value) || value.length === 0) return false;
6240
+ return value.every((el) => {
6241
+ if (!isNestedObject(el)) return false;
6242
+ return Object.entries(el).every(([k, v]) => {
6243
+ if (VPN_TUNNEL_EMPTY_LIST_KEYS.has(k)) return Array.isArray(v) && v.length === 0;
6244
+ if (k === "TunnelInsideCidr") return typeof v === "string" && VPN_TUNNEL_INSIDE_CIDR.test(v);
6245
+ if (k === "TunnelInsideIpv6Cidr") return typeof v === "string";
6246
+ if (k === "LogOptions") return deepEqual(v, { CloudwatchLogOptions: {
6247
+ BgpLogEnabled: false,
6248
+ LogEnabled: false
6249
+ } });
6250
+ return false;
6251
+ });
6252
+ });
6253
+ }
6226
6254
  const CFN_RANDOM_SUFFIX = /-[0-9A-Za-z]{12,}$/;
6227
6255
  function stripInjectedJsonStringDefaults(declared, live, defaults) {
6228
6256
  const stripObject = (d, l) => {
@@ -7631,7 +7659,7 @@ function classifyResource(resource, liveRaw, schema, opts = {}) {
7631
7659
  continue;
7632
7660
  }
7633
7661
  }
7634
- if (k in schema.defaults && matchesKnownDefault(v, schema.defaults[k]) || k in schema.defaultPaths && matchesKnownDefault(v, schema.defaultPaths[k]) || k in knownDef && matchesKnownDefault(v, knownDef[k]) || KNOWN_DEFAULT_ONE_OF[resourceType]?.[k]?.some((d) => matchesKnownDefault(v, d)) || VALUE_INDEPENDENT_DEFAULT_TOPLEVEL_PATHS[resourceType]?.has(k) && !isTrivialEmpty(v) && !(k in knownDef) || clbDefaultSslPoliciesAtDefault(resourceType, k, v)) {
7662
+ if (k in schema.defaults && matchesKnownDefault(v, schema.defaults[k]) || k in schema.defaultPaths && matchesKnownDefault(v, schema.defaultPaths[k]) || k in knownDef && matchesKnownDefault(v, knownDef[k]) || KNOWN_DEFAULT_ONE_OF[resourceType]?.[k]?.some((d) => matchesKnownDefault(v, d)) || VALUE_INDEPENDENT_DEFAULT_TOPLEVEL_PATHS[resourceType]?.has(k) && !isTrivialEmpty(v) && !(k in knownDef) || clbDefaultSslPoliciesAtDefault(resourceType, k, v) || vpnTunnelOptionsAtDefault(resourceType, k, v)) {
7635
7663
  findings.push({
7636
7664
  tier: "atDefault",
7637
7665
  logicalId,
@@ -15223,6 +15251,9 @@ function hashOfCanonical(canonicalValue) {
15223
15251
  function redactedHashSentinel(canonicalValue) {
15224
15252
  return { [REDACTION_HASH_KEY]: hashOfCanonical(canonicalValue) };
15225
15253
  }
15254
+ function stableValueHash(value) {
15255
+ return hashOfCanonical(value);
15256
+ }
15226
15257
  function isRedactedHashSentinel(v) {
15227
15258
  return !!v && typeof v === "object" && !Array.isArray(v) && Object.keys(v).length === 1 && typeof v[REDACTION_HASH_KEY] === "string";
15228
15259
  }
@@ -15241,7 +15272,8 @@ const KNOWN_BASELINE_KEYS = new Set([
15241
15272
  "templateHash",
15242
15273
  "recorded",
15243
15274
  "completeResources",
15244
- "recordedPhysicalIds"
15275
+ "recordedPhysicalIds",
15276
+ "recordedSourceFingerprints"
15245
15277
  ]);
15246
15278
  const KNOWN_RECORDED_ENTRY_KEYS = new Set([
15247
15279
  "logicalId",
@@ -15301,6 +15333,7 @@ async function loadBaseline(stackName, accountId, region) {
15301
15333
  validateRecordedUniqueness(parsed.recorded, path);
15302
15334
  validateCompleteResources(parsed.completeResources, path);
15303
15335
  validateRecordedPhysicalIds(parsed.recordedPhysicalIds, path);
15336
+ validateRecordedSourceFingerprints(parsed.recordedSourceFingerprints, path);
15304
15337
  return parsed;
15305
15338
  }
15306
15339
  /**
@@ -15379,6 +15412,18 @@ function validateRecordedPhysicalIds(value, path) {
15379
15412
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${at} must be an object mapping logicalId to physical id`);
15380
15413
  for (const [key, v] of Object.entries(value)) if (typeof v !== "string") throw new Error(`${at}: "${key}" must map to a string`);
15381
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
+ }
15382
15427
  /** Deterministic order for `recorded` entries: lexicographic by (logicalId, path).
15383
15428
  * The single point where order is imposed — read/compare logic is order-independent,
15384
15429
  * so this only affects the bytes on disk. Without it the entries inherit findings
@@ -15401,6 +15446,12 @@ function sortedPhysicalIds(ids, recorded, complete) {
15401
15446
  for (const key of Object.keys(ids).sort()) if (persist.has(key) && ids[key] !== void 0) out[key] = ids[key];
15402
15447
  return out;
15403
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
+ }
15404
15455
  async function writeBaselineFile(b) {
15405
15456
  const p = baselinePath(b.stackName, b.accountId, b.region);
15406
15457
  await mkdir(dirname(p), { recursive: true });
@@ -15408,7 +15459,8 @@ async function writeBaselineFile(b) {
15408
15459
  ...b,
15409
15460
  recorded: sortRecorded(b.recorded),
15410
15461
  ...b.completeResources ? { completeResources: [...b.completeResources].sort() } : {},
15411
- ...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) } : {}
15412
15464
  };
15413
15465
  await writeFile(p, JSON.stringify(stable, null, 2) + "\n", "utf8");
15414
15466
  return p;
@@ -15478,7 +15530,8 @@ async function writeBaseline(stackName, region, accountId, findings, rawTemplate
15478
15530
  templateHash: hashTemplate(rawTemplate),
15479
15531
  recorded,
15480
15532
  completeResources,
15481
- ...buildRecordedPhysicalIds(recorded, completeResources, opts.physicalIdByLogical, opts.previous)
15533
+ ...buildRecordedPhysicalIds(recorded, completeResources, opts.physicalIdByLogical, opts.previous),
15534
+ ...buildRecordedSourceFingerprints(recorded, opts.declaredByLogical, opts.previous)
15482
15535
  }),
15483
15536
  count: recorded.length
15484
15537
  };
@@ -15528,6 +15581,48 @@ const RECORDABLE_GENERATED_PATHS = {
15528
15581
  function isRecordableGenerated(f) {
15529
15582
  return f.tier === "generated" && (RECORDABLE_GENERATED_PATHS[f.resourceType]?.has(f.path) ?? false);
15530
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
+ }
15531
15626
  /** Build the recorded set from a check run's findings: undeclared PROPERTIES plus
15532
15627
  * out-of-band `added` RESOURCES (PR4 — `added` is the resource-granularity sibling of
15533
15628
  * undeclared, so `record` snapshots its full live model and a later change to it
@@ -15891,6 +15986,14 @@ function applyBaseline(findings, baseline, opts = {}) {
15891
15986
  const liveId = opts.physicalIdByLogical?.get(logicalId);
15892
15987
  if (liveId !== void 0 && liveId !== recordedId) replacedLogical.add(logicalId);
15893
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
+ }
15894
15997
  const liveTypeByLogical = /* @__PURE__ */ new Map();
15895
15998
  for (const f of findings) if (f.resourceType) liveTypeByLogical.set(f.logicalId, f.resourceType);
15896
15999
  const isTypeVoid = (e) => {
@@ -15928,7 +16031,8 @@ function applyBaseline(findings, baseline, opts = {}) {
15928
16031
  kept.push(f);
15929
16032
  continue;
15930
16033
  }
15931
- 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;
15932
16036
  if (entry && baselineValueMatches(entry.value, f.actual, f.resourceType, f.path)) continue;
15933
16037
  if (entry) {
15934
16038
  const delta = identityArrayDelta(canonicalizeForCompare(entry.value, f.resourceType), f.actual);
@@ -15972,6 +16076,7 @@ function applyBaseline(findings, baseline, opts = {}) {
15972
16076
  const typeMismatchStale = [];
15973
16077
  const adoptedStale = [];
15974
16078
  const nameStrippedStale = [];
16079
+ const sourceRedeployedStale = [];
15975
16080
  for (const a of recorded) {
15976
16081
  if (a.path === "") {
15977
16082
  if (presentAddedLogical.has(a.logicalId)) continue;
@@ -15999,6 +16104,10 @@ function applyBaseline(findings, baseline, opts = {}) {
15999
16104
  replacedStale.push(`${a.logicalId}.${a.path}`);
16000
16105
  continue;
16001
16106
  }
16107
+ if (sourceRedeployedVoid.has(recordedKey(a))) {
16108
+ sourceRedeployedStale.push(`${a.logicalId}.${a.path}`);
16109
+ continue;
16110
+ }
16002
16111
  if (currentPaths.has(`${a.logicalId}.${a.path}`)) continue;
16003
16112
  if (skippedLogical.has(a.logicalId)) continue;
16004
16113
  if (deletedLogical.has(a.logicalId)) continue;
@@ -16033,9 +16142,21 @@ function applyBaseline(findings, baseline, opts = {}) {
16033
16142
  if (typeMismatchStale.length > 0) opts.warn?.(formatTypeMismatchStaleNote(typeMismatchStale));
16034
16143
  if (adoptedStale.length > 0) opts.warn?.(formatAdoptedStaleNote(adoptedStale));
16035
16144
  if (nameStrippedStale.length > 0) opts.warn?.(formatNameStrippedStaleNote(nameStrippedStale));
16145
+ if (sourceRedeployedStale.length > 0) opts.warn?.(formatSourceRedeployedStaleNote(sourceRedeployedStale));
16036
16146
  return kept;
16037
16147
  }
16038
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
+ /**
16039
16160
  * The folded one-line note for baseline entries now declared in the template (R134). One
16040
16161
  * line with a count instead of one line per entry; `record` re-snapshots to clear them.
16041
16162
  * Pure + exported for unit tests.
@@ -19959,7 +20080,8 @@ async function recordStack(p) {
19959
20080
  const { path, count } = await writeBaseline(stackName, region, desired.accountId, findings, desired.rawTemplate, recorded, {
19960
20081
  allLogicalIds: desired.resources.map((r) => r.logicalId),
19961
20082
  previous: existing,
19962
- physicalIdByLogical: physicalIdsByLogical(desired.resources)
20083
+ physicalIdByLogical: physicalIdsByLogical(desired.resources),
20084
+ declaredByLogical: declaredKeysByLogical(desired.resources)
19963
20085
  });
19964
20086
  if (!p.json) console.log(style.ok(recordOutcomeMessage(stackName, path, count, refreshedOnly, !!existing)));
19965
20087
  const scopeNote = recordScopeNote(stackName, findings);