cdk-real-drift 0.28.2 → 0.29.0

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
@@ -1061,7 +1061,11 @@ covers them. **If you never run `revert`, cdkrd needs no write permissions at al
1061
1061
  "changed since record". A **legitimate** `cdk deploy` that updates the code
1062
1062
  does NOT re-surface it: `record` also fingerprints the declared `Code`, so a
1063
1063
  hash that moved because the template's code changed folds into a re-record
1064
- nudge instead of false drift (same for the Glue script hash below). The old
1064
+ nudge instead of false drift (same for the Glue script hash below). With
1065
+ `s3:GetObject` on the CDK asset bucket, cdkrd also hashes the asset the template
1066
+ now deploys, so an out-of-band swap made AFTER such a redeploy still surfaces
1067
+ before the re-record (without it, a note says the new code could not be
1068
+ verified). The old
1065
1069
  code bytes are gone, so it is detect-only (not revertable — redeploy with a
1066
1070
  forced code update). Without the permission the signal is skipped, never
1067
1071
  false-flagged.
@@ -1074,6 +1078,15 @@ covers them. **If you never run `revert`, cdkrd needs no write permissions at al
1074
1078
  deploy, `record` snapshots it, a swap re-surfaces as "changed since record",
1075
1079
  detect-only (re-upload the intended script). Without the permission (or on any S3
1076
1080
  read failure / a non-`s3://` location) the signal is skipped, never false-flagged.
1081
+ After a legitimate `cdk deploy` of a NEW script (and likewise a new TrustStore CA
1082
+ bundle), the deployed object is checked against the matching asset in the locally
1083
+ synthesized app, so an overwrite after that deploy still surfaces before the
1084
+ re-record. When it cannot be checked (the local app no longer contains that asset,
1085
+ the source is not a CDK asset, or the file is over 16 MiB), a note says so on each
1086
+ check until the re-record. An asset with a custom `assetHash` edited locally without
1087
+ changing that hash reads as an out-of-band change; the local and deployed bytes
1088
+ really differ there (`cdk deploy` skips the upload because the key already exists),
1089
+ but the cause is the unchanged hash, not an edit made out of band.
1077
1090
  - Optional: `kms:ListAliases` enables strict verification that a declared
1078
1091
  `alias/aws/*` key was not swapped for a customer-managed key. Without it that case
1079
1092
  is conservatively suppressed AND cdkrd prints a one-line warning per region (the
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { existsSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
3
3
  import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
4
- import { dirname, join, resolve } from "node:path";
4
+ import { dirname, isAbsolute, join, resolve } from "node:path";
5
5
  import { pid } from "node:process";
6
6
  import { YAMLSeq, isSeq, parse, parseDocument } from "yaml";
7
7
  import { GetCallerIdentityCommand, STSClient } from "@aws-sdk/client-sts";
@@ -16,6 +16,7 @@ import { getProxyForUrl } from "proxy-from-env";
16
16
  import { CloudControlClient, DeleteResourceCommand, GetResourceCommand, GetResourceRequestStatusCommand, UpdateResourceCommand } from "@aws-sdk/client-cloudcontrol";
17
17
  import { homedir } from "node:os";
18
18
  import { BaseCredentials, CdkAppMultiContext, NonInteractiveIoHost, StackSelectionStrategy, Toolkit } from "@aws-cdk/toolkit-lib";
19
+ import { createHash } from "node:crypto";
19
20
  import { CloudFormationClient, DescribeStackResourcesCommand, DescribeStacksCommand, DescribeTypeCommand, GetTemplateCommand, ListExportsCommand, ListStackResourcesCommand } from "@aws-sdk/client-cloudformation";
20
21
  import { DescribeAddressesCommand, DescribeClientVpnAuthorizationRulesCommand, DescribeClientVpnEndpointsCommand, DescribeClientVpnTargetNetworksCommand, DescribeFlowLogsCommand, DescribeInternetGatewaysCommand, DescribeLaunchTemplateVersionsCommand, DescribeNatGatewaysCommand, DescribeNetworkAclsCommand, DescribeRegionsCommand, DescribeRouteTablesCommand, DescribeSecurityGroupsCommand, DescribeSubnetsCommand, DescribeTransitGatewayAttachmentsCommand, DescribeTransitGatewayRouteTablesCommand, DescribeVpcEndpointsCommand, DescribeVpcsCommand, EC2Client, GetDefaultCreditSpecificationCommand, GetEbsEncryptionByDefaultCommand, GetInstanceMetadataDefaultsCommand, ModifyClientVpnEndpointCommand } from "@aws-sdk/client-ec2";
21
22
  import { DescribeServicesCommand, ECSClient, ListAccountSettingsCommand, ListServicesCommand, UpdateServiceCommand } from "@aws-sdk/client-ecs";
@@ -68,7 +69,6 @@ import { DescribeReceiptRuleCommand, DescribeReceiptRuleSetCommand, ListReceiptF
68
69
  import { GetConfigurationSetEventDestinationsCommand, SESv2Client, UpdateConfigurationSetEventDestinationCommand } from "@aws-sdk/client-sesv2";
69
70
  import { DescribeEndpointConfigCommand, DescribeMonitoringScheduleCommand, ListTagsCommand as ListTagsCommand$1, SageMakerClient, UpdateMonitoringScheduleCommand } from "@aws-sdk/client-sagemaker";
70
71
  import { GetNamespaceCommand, GetServiceCommand, ListTagsForResourceCommand as ListTagsForResourceCommand$4, ServiceDiscoveryClient, UpdateHttpNamespaceCommand, UpdateServiceCommand as UpdateServiceCommand$1 } from "@aws-sdk/client-servicediscovery";
71
- import { createHash } from "node:crypto";
72
72
  import { S_BAR, S_BAR_END, S_BAR_START, S_CHECKBOX_INACTIVE, S_CHECKBOX_SELECTED, confirm, isCancel, select, spinner } from "@clack/prompts";
73
73
  import pc from "picocolors";
74
74
  import { MultiSelectPrompt, Prompt, isCancel as isCancel$1 } from "@clack/core";
@@ -1317,6 +1317,69 @@ var QuietIoHost = class extends NonInteractiveIoHost {
1317
1317
  }
1318
1318
  };
1319
1319
 
1320
+ // src/read/pem.ts
1321
+ function hashCaBundle(pem) {
1322
+ if (typeof pem !== "string") return void 0;
1323
+ const bodies = [];
1324
+ const re = /-----BEGIN CERTIFICATE-----([\s\S]*?)-----END CERTIFICATE-----/g;
1325
+ for (let m = re.exec(pem); m !== null; m = re.exec(pem)) {
1326
+ const body = (m[1] ?? "").replace(/\s+/g, "");
1327
+ if (body.length > 0) bodies.push(body);
1328
+ }
1329
+ if (bodies.length === 0) return void 0;
1330
+ bodies.sort();
1331
+ return createHash("sha256").update(bodies.join("\n")).digest("hex");
1332
+ }
1333
+ function sha256Hex(bytes) {
1334
+ if (bytes === void 0 || bytes.length === 0) return void 0;
1335
+ return createHash("sha256").update(bytes).digest("hex");
1336
+ }
1337
+
1338
+ // src/synth/local-assets.ts
1339
+ const MAX_ASSET_BYTES = 16777216;
1340
+ /** Hash the `file`-packaged assets of the given asset manifest files (absolute paths). */
1341
+ function localFileAssetHashes(manifestFiles) {
1342
+ const out = {};
1343
+ for (const manifestFile of manifestFiles) {
1344
+ let files;
1345
+ try {
1346
+ files = JSON.parse(readFileSync(manifestFile, "utf8")).files ?? {};
1347
+ } catch {
1348
+ continue;
1349
+ }
1350
+ for (const asset of Object.values(files)) {
1351
+ const { path, packaging } = asset.source ?? {};
1352
+ if (typeof path !== "string" || packaging !== void 0 && packaging !== "file") continue;
1353
+ const abs = isAbsolute(path) ? path : join(dirname(manifestFile), path);
1354
+ let bytes;
1355
+ try {
1356
+ if (statSync(abs).size > MAX_ASSET_BYTES) continue;
1357
+ bytes = readFileSync(abs);
1358
+ } catch {
1359
+ continue;
1360
+ }
1361
+ const hex = sha256Hex(bytes);
1362
+ if (hex === void 0) continue;
1363
+ const ca = hashCaBundle(bytes.toString("utf8"));
1364
+ const hash = {
1365
+ sha256Hex: hex,
1366
+ ...ca !== void 0 && { caBundleSha256: ca }
1367
+ };
1368
+ for (const d of Object.values(asset.destinations ?? {})) if (typeof d.objectKey === "string") out[d.objectKey] = hash;
1369
+ }
1370
+ }
1371
+ return out;
1372
+ }
1373
+ function assetManifestFilesOf(stack) {
1374
+ const out = [];
1375
+ for (const d of stack.dependencies ?? []) {
1376
+ const file = d.file;
1377
+ const type = d.manifest?.type;
1378
+ if (typeof file === "string" && type === "cdk:asset-manifest") out.push(file);
1379
+ }
1380
+ return out;
1381
+ }
1382
+
1320
1383
  // src/synth/missing-context.ts
1321
1384
  /**
1322
1385
  * Collect `missing` context entries across the top-level assembly AND every nested assembly
@@ -1536,7 +1599,8 @@ async function synthApp(app, opts = {}) {
1536
1599
  region: CONCRETE_REGION.test(s.environment.region) ? s.environment.region : void 0,
1537
1600
  account: concreteAccount(s.environment.account),
1538
1601
  errorMessages: stackErrorMessages(s.messages),
1539
- template: s.template
1602
+ template: s.template,
1603
+ localAssetHashes: localFileAssetHashes(assetManifestFilesOf(s))
1540
1604
  }));
1541
1605
  } finally {
1542
1606
  await cached.dispose();
@@ -1554,7 +1618,8 @@ async function discoverStacks(app, opts = {}) {
1554
1618
  region: s.region,
1555
1619
  account: s.account,
1556
1620
  errorMessages: s.errorMessages,
1557
- template: s.template
1621
+ template: s.template,
1622
+ ...s.localAssetHashes !== void 0 && { localAssetHashes: s.localAssetHashes }
1558
1623
  }));
1559
1624
  }
1560
1625
 
@@ -1674,13 +1739,14 @@ async function resolveStacks(a) {
1674
1739
  stackName: s.stackName,
1675
1740
  region: s.region ?? fallbackRegion,
1676
1741
  account: s.account,
1677
- template: s.template
1742
+ template: s.template,
1743
+ ...s.localAssetHashes !== void 0 && { localAssetHashes: s.localAssetHashes }
1678
1744
  }));
1679
1745
  }
1680
1746
  const seen = /* @__PURE__ */ new Set();
1681
1747
  const out = [];
1682
1748
  const selectedByKey = /* @__PURE__ */ new Map();
1683
- const add = (stackName, region, account, template) => {
1749
+ const add = (stackName, region, account, template, localAssetHashes) => {
1684
1750
  const key = `${stackName}\0${region ?? ""}\0${account ?? ""}`;
1685
1751
  if (seen.has(key)) return;
1686
1752
  seen.add(key);
@@ -1688,12 +1754,13 @@ async function resolveStacks(a) {
1688
1754
  stackName,
1689
1755
  region,
1690
1756
  account,
1691
- template
1757
+ template,
1758
+ ...localAssetHashes !== void 0 && { localAssetHashes }
1692
1759
  });
1693
1760
  };
1694
1761
  const known = () => discovered.map((s) => s.hierarchicalId === s.stackName ? s.stackName : `${s.hierarchicalId} (${s.stackName})`).join(", ") || "none";
1695
1762
  const select = (s) => {
1696
- add(s.stackName, s.region ?? fallbackRegion, s.account, s.template);
1763
+ add(s.stackName, s.region ?? fallbackRegion, s.account, s.template, s.localAssetHashes);
1697
1764
  selectedByKey.set(`${s.stackName}\0${s.region ?? ""}\0${s.account ?? ""}`, s);
1698
1765
  };
1699
1766
  for (const name of a.stackNames) {
@@ -12441,24 +12508,6 @@ async function enumerateElasticBeanstalkApplicationChildren(ctx) {
12441
12508
  });
12442
12509
  }
12443
12510
 
12444
- // src/read/pem.ts
12445
- function hashCaBundle(pem) {
12446
- if (typeof pem !== "string") return void 0;
12447
- const bodies = [];
12448
- const re = /-----BEGIN CERTIFICATE-----([\s\S]*?)-----END CERTIFICATE-----/g;
12449
- for (let m = re.exec(pem); m !== null; m = re.exec(pem)) {
12450
- const body = (m[1] ?? "").replace(/\s+/g, "");
12451
- if (body.length > 0) bodies.push(body);
12452
- }
12453
- if (bodies.length === 0) return void 0;
12454
- bodies.sort();
12455
- return createHash("sha256").update(bodies.join("\n")).digest("hex");
12456
- }
12457
- function sha256Hex(bytes) {
12458
- if (bytes === void 0 || bytes.length === 0) return void 0;
12459
- return createHash("sha256").update(bytes).digest("hex");
12460
- }
12461
-
12462
12511
  // src/read/overrides.ts
12463
12512
  const OVERRIDE_READ_GAP = Symbol.for("cdkrd.overrideReadGap");
12464
12513
  function overrideReadGap(model, readGapPaths) {
@@ -17368,6 +17417,28 @@ function declaredSourceFingerprint(resourceType, path, declared) {
17368
17417
  return node === void 0 ? void 0 : stableValueHash(node);
17369
17418
  }
17370
17419
  /**
17420
+ * The recorded keys whose content hash is VOID because its declared source was redeployed
17421
+ * through CloudFormation since record (the #1606 stale-source void): a stored fingerprint
17422
+ * EXISTS and the current declared source RESOLVES to a different one. Shared by
17423
+ * `applyBaseline` and the #1958 deployed-source verifier, which fetches only these.
17424
+ */
17425
+ function sourceRedeployedKeys(baseline, declaredByLogical) {
17426
+ const out = /* @__PURE__ */ new Set();
17427
+ const stored = baseline.recordedSourceFingerprints ?? {};
17428
+ for (const e of baseline.recorded) {
17429
+ const storedFp = stored[recordedKey(e)];
17430
+ if (storedFp === void 0) continue;
17431
+ const currentFp = declaredSourceFingerprint(e.resourceType, e.path, declaredByLogical?.get(e.logicalId));
17432
+ if (currentFp !== void 0 && currentFp !== storedFp) out.add(recordedKey(e));
17433
+ }
17434
+ return out;
17435
+ }
17436
+ const DEPLOYED_SOURCE_VERIFIABLE = {
17437
+ "AWS::Lambda::Function": "CodeSha256",
17438
+ "AWS::Glue::Job": "ScriptSha256",
17439
+ "AWS::ElasticLoadBalancingV2::TrustStore": "CaCertificatesBundleSha256"
17440
+ };
17441
+ /**
17371
17442
  * Build the `recordedSourceFingerprints` map for the entries being written. For each entry
17372
17443
  * with a source mapping: prefer the PREVIOUS baseline's fingerprint when the entry's VALUE
17373
17444
  * was carried forward unchanged from it (a resource unread this run — e.g. skipped — must
@@ -17753,14 +17824,9 @@ function applyBaseline(findings, baseline, opts = {}) {
17753
17824
  const liveId = opts.physicalIdByLogical?.get(logicalId);
17754
17825
  if (liveId !== void 0 && liveId !== recordedId) replacedLogical.add(logicalId);
17755
17826
  }
17756
- const sourceRedeployedVoid = /* @__PURE__ */ new Set();
17757
- const recordedSourceFps = baseline.recordedSourceFingerprints ?? {};
17758
- for (const e of recorded) {
17759
- const storedFp = recordedSourceFps[recordedKey(e)];
17760
- if (storedFp === void 0) continue;
17761
- const currentFp = declaredSourceFingerprint(e.resourceType, e.path, opts.declaredByLogical?.get(e.logicalId));
17762
- if (currentFp !== void 0 && currentFp !== storedFp) sourceRedeployedVoid.add(recordedKey(e));
17763
- }
17827
+ const sourceRedeployedVoid = sourceRedeployedKeys(baseline, opts.declaredByLogical);
17828
+ const sourceSwapped = /* @__PURE__ */ new Set();
17829
+ const sourceVerified = /* @__PURE__ */ new Set();
17764
17830
  const liveTypeByLogical = /* @__PURE__ */ new Map();
17765
17831
  for (const f of findings) if (f.resourceType) liveTypeByLogical.set(f.logicalId, f.resourceType);
17766
17832
  const isTypeVoid = (e) => {
@@ -17768,7 +17834,13 @@ function applyBaseline(findings, baseline, opts = {}) {
17768
17834
  return liveType !== void 0 && liveType !== e.resourceType;
17769
17835
  };
17770
17836
  const entryMatches = (a, f) => a.logicalId === f.logicalId && a.path === f.path && a.resourceType === f.resourceType;
17771
- for (const f of findings) {
17837
+ for (const stamped of findings) {
17838
+ const deployedSourceHash = stamped.deployedSourceHash;
17839
+ let f = stamped;
17840
+ if (deployedSourceHash !== void 0) {
17841
+ f = { ...stamped };
17842
+ delete f.deployedSourceHash;
17843
+ }
17772
17844
  if (f.tier === "added") {
17773
17845
  const entry = recorded.find((a) => entryMatches(a, f));
17774
17846
  if (f.modelReadFailed) {
@@ -17807,6 +17879,21 @@ function applyBaseline(findings, baseline, opts = {}) {
17807
17879
  }
17808
17880
  const matched = replacedLogical.has(f.logicalId) ? void 0 : recorded.find((a) => entryMatches(a, f));
17809
17881
  const sourceRedeployVoided = matched !== void 0 && sourceRedeployedVoid.has(recordedKey(matched));
17882
+ if (matched !== void 0 && sourceRedeployVoided && deployedSourceHash !== void 0) {
17883
+ if (f.actual === deployedSourceHash) {
17884
+ sourceVerified.add(recordedKey(matched));
17885
+ if (f.tier !== "undeclared") kept.push(f);
17886
+ } else {
17887
+ sourceSwapped.add(recordedKey(matched));
17888
+ kept.push({
17889
+ ...f,
17890
+ tier: "undeclared",
17891
+ desired: deployedSourceHash,
17892
+ note: "differs from the content the template deploys (changed out of band since the last deploy of it)"
17893
+ });
17894
+ }
17895
+ continue;
17896
+ }
17810
17897
  if (sourceRedeployVoided && f.tier === "undeclared") continue;
17811
17898
  const entry = sourceRedeployVoided ? void 0 : matched;
17812
17899
  if (entry && baselineValueMatches(entry.value, f.actual, f.resourceType, f.path)) continue;
@@ -17853,6 +17940,7 @@ function applyBaseline(findings, baseline, opts = {}) {
17853
17940
  const adoptedStale = [];
17854
17941
  const nameStrippedStale = [];
17855
17942
  const sourceRedeployedStale = [];
17943
+ const sourceUnverified = [];
17856
17944
  for (const a of recorded) {
17857
17945
  if (a.path === "") {
17858
17946
  if (presentAddedLogical.has(a.logicalId)) continue;
@@ -17881,7 +17969,9 @@ function applyBaseline(findings, baseline, opts = {}) {
17881
17969
  continue;
17882
17970
  }
17883
17971
  if (sourceRedeployedVoid.has(recordedKey(a))) {
17972
+ if (sourceSwapped.has(recordedKey(a))) continue;
17884
17973
  sourceRedeployedStale.push(`${a.logicalId}.${a.path}`);
17974
+ if (!sourceVerified.has(recordedKey(a)) && DEPLOYED_SOURCE_VERIFIABLE[a.resourceType] === a.path) sourceUnverified.push(`${a.logicalId}.${a.path}`);
17885
17975
  continue;
17886
17976
  }
17887
17977
  if (currentPaths.has(`${a.logicalId}.${a.path}`)) continue;
@@ -17944,6 +18034,7 @@ function applyBaseline(findings, baseline, opts = {}) {
17944
18034
  if (adoptedStale.length > 0) opts.warn?.(formatAdoptedStaleNote(adoptedStale));
17945
18035
  if (nameStrippedStale.length > 0) opts.warn?.(formatNameStrippedStaleNote(nameStrippedStale));
17946
18036
  if (sourceRedeployedStale.length > 0) opts.warn?.(formatSourceRedeployedStaleNote(sourceRedeployedStale));
18037
+ if (sourceUnverified.length > 0) opts.warn?.(formatSourceUnverifiedNote(sourceUnverified));
17947
18038
  return kept;
17948
18039
  }
17949
18040
  /**
@@ -17958,6 +18049,15 @@ function formatSourceRedeployedStaleNote(paths) {
17958
18049
  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.`;
17959
18050
  }
17960
18051
  /**
18052
+ * #1958: the coverage note for stale-source voids whose live hash could NOT be verified
18053
+ * against the deployed source (the asset object was unreadable, or the source is not an S3
18054
+ * object) — an out-of-band swap since that redeploy goes unseen until a re-record, and the
18055
+ * user must know the CLEAN verdict does not cover it. Pure + exported for unit tests.
18056
+ */
18057
+ function formatSourceUnverifiedNote(paths) {
18058
+ return `note: could not verify ${paths.join(", ")} against the content the template deploys (the deployed asset could not be read or matched to a local synthesized asset, or the live hash was not read) — an out-of-band change since that deploy is not detected until \`cdkrd record\` re-runs.`;
18059
+ }
18060
+ /**
17961
18061
  * The folded one-line note for baseline entries now declared in the template (R134). One
17962
18062
  * line with a count instead of one line per entry; `record` re-snapshots to clear them.
17963
18063
  * Pure + exported for unit tests.
@@ -18057,6 +18157,108 @@ function warnTemplateHashDrift(baseline, rawTemplate, stackName, warn = console.
18057
18157
  if (baseline.templateHash !== hashTemplate(rawTemplate)) warn(`note: ${stackName}: baseline was captured against a different template version — consider re-running \`cdkrd record\`.`);
18058
18158
  }
18059
18159
 
18160
+ // src/read/deployed-source-hash.ts
18161
+ const s3Clients = /* @__PURE__ */ new Map();
18162
+ const fetchS3Sha256Base64 = async (ref, region) => {
18163
+ let s3 = s3Clients.get(region);
18164
+ if (s3 === void 0) {
18165
+ s3 = new S3Client({
18166
+ region,
18167
+ followRegionRedirects: true,
18168
+ ...READ_RETRY
18169
+ });
18170
+ s3Clients.set(region, s3);
18171
+ }
18172
+ const body = (await s3.send(new GetObjectCommand({
18173
+ Bucket: ref.bucket,
18174
+ Key: ref.key,
18175
+ ...ref.versionId !== void 0 && { VersionId: ref.versionId }
18176
+ }))).Body;
18177
+ if (body === void 0) throw new Error("empty S3 object body");
18178
+ const h = createHash("sha256");
18179
+ for await (const chunk of body) h.update(chunk);
18180
+ return h.digest("base64");
18181
+ };
18182
+ const FETCH_CONCURRENCY = 4;
18183
+ function lambdaCodeS3Ref(declared) {
18184
+ const code = declared?.["Code"];
18185
+ if (code === null || typeof code !== "object" || Array.isArray(code)) return void 0;
18186
+ const { S3Bucket, S3Key, S3ObjectVersion } = code;
18187
+ if (typeof S3Bucket !== "string" || typeof S3Key !== "string") return void 0;
18188
+ if (S3ObjectVersion !== void 0 && typeof S3ObjectVersion !== "string") return void 0;
18189
+ return {
18190
+ bucket: S3Bucket,
18191
+ key: S3Key,
18192
+ versionId: S3ObjectVersion
18193
+ };
18194
+ }
18195
+ function localAssetHash(f, declared, localAssets) {
18196
+ if (localAssets === void 0 || declared === void 0) return void 0;
18197
+ if (f.resourceType === "AWS::Glue::Job") {
18198
+ const loc = declared["Command"]?.["ScriptLocation"];
18199
+ const m = typeof loc === "string" ? /^s3:\/\/[^/]+\/(.+)$/.exec(loc) : null;
18200
+ return m === null ? void 0 : localAssets[m[1]]?.sha256Hex;
18201
+ }
18202
+ if (f.resourceType === "AWS::ElasticLoadBalancingV2::TrustStore") {
18203
+ const key = declared["CaCertificatesBundleS3Key"];
18204
+ return typeof key === "string" ? localAssets[key]?.caBundleSha256 : void 0;
18205
+ }
18206
+ }
18207
+ /**
18208
+ * #1958: stamp `deployedSourceHash` on each live content-hash finding whose recorded entry
18209
+ * the stale-source void (#1606) would drop — a legit code redeploy since record — so
18210
+ * `applyBaseline` can still catch an out-of-band swap made AFTER that redeploy instead of
18211
+ * reading CLEAN until the next `record`. Only the voided entries are fetched (an S3 read of
18212
+ * every function's package on every check would be the wrong cost). Fail-safe: any read
18213
+ * failure (no s3:GetObject on the asset bucket, a lifecycle-expired asset) or a non-S3 source
18214
+ * leaves the finding unstamped, which keeps today's void plus a coverage note. #1960: Glue
18215
+ * ScriptSha256 / TrustStore CaCertificatesBundleSha256 take their expected hash from the
18216
+ * local synthesized asset instead (no fetch).
18217
+ */
18218
+ async function annotateDeployedSourceHashes(findings, baseline, resources, region, opts = {}) {
18219
+ const fetch = opts.fetch ?? fetchS3Sha256Base64;
18220
+ if (!baseline) return findings;
18221
+ const declaredByLogical = new Map(resources.map((r) => [r.logicalId, r.declared]));
18222
+ const voided = sourceRedeployedKeys(baseline, declaredByLogical);
18223
+ if (voided.size === 0) return findings;
18224
+ const jobs = [];
18225
+ const hashes = /* @__PURE__ */ new Map();
18226
+ findings.forEach((f, i) => {
18227
+ if (f.deployedSourceHash !== void 0) return;
18228
+ if (DEPLOYED_SOURCE_VERIFIABLE[f.resourceType] !== f.path) return;
18229
+ if (!voided.has(recordedKey(f))) return;
18230
+ const declared = declaredByLogical.get(f.logicalId);
18231
+ if (f.resourceType !== "AWS::Lambda::Function") {
18232
+ const h = localAssetHash(f, declared, opts.localAssets);
18233
+ if (h !== void 0) hashes.set(i, h);
18234
+ return;
18235
+ }
18236
+ const ref = lambdaCodeS3Ref(declared);
18237
+ if (ref !== void 0) jobs.push({
18238
+ i,
18239
+ ref
18240
+ });
18241
+ });
18242
+ let next = 0;
18243
+ const worker = async () => {
18244
+ while (next < jobs.length) {
18245
+ const { i, ref } = jobs[next++];
18246
+ try {
18247
+ hashes.set(i, await fetch(ref, region));
18248
+ } catch {}
18249
+ }
18250
+ };
18251
+ if (jobs.length > 0) await Promise.all(Array.from({ length: Math.min(FETCH_CONCURRENCY, jobs.length) }, worker));
18252
+ if (hashes.size === 0) return findings;
18253
+ return findings.map((f, i) => {
18254
+ const h = hashes.get(i);
18255
+ return h === void 0 ? f : {
18256
+ ...f,
18257
+ deployedSourceHash: h
18258
+ };
18259
+ });
18260
+ }
18261
+
18060
18262
  // src/diff/hints.ts
18061
18263
  const APP_SIGNALS_HINT = "looks like CloudWatch Application Signals / Lambda Insights auto-instrumentation — typically enabled at the account/region level (a CloudWatch setting), not a per-resource edit; declare it in CDK to make it intent, or record/ignore to accept it";
18062
18264
  const INSIGHTS_LAYER = /:layer:LambdaInsightsExtension(-Arm64)?:/;
@@ -22115,11 +22317,15 @@ function changedRecordLabel(entry, recordedValue, sourceRedeployed = false) {
22115
22317
  * change out of band (the IaC deploy moved the live hash with the template), so record must
22116
22318
  * label and summarize it as a legit refresh, not "CHANGED out of band". Fail-safe: false when
22117
22319
  * no source fingerprint was stored (an old baseline, or a path with no source mapping) or the
22118
- * current declared source does not resolve — exactly the void's own gates. Pure + exported.
22320
+ * current declared source does not resolve — exactly the void's own gates. #1958: also
22321
+ * false when the entry's live finding carries a `deployedSourceHash` that differs from its
22322
+ * live value — the code was swapped out of band AFTER the redeploy. Pure + exported.
22119
22323
  */
22120
- function isRecordedSourceRedeployed(entry, existing, declaredByLogical) {
22324
+ function isRecordedSourceRedeployed(entry, existing, declaredByLogical, findings = []) {
22121
22325
  const storedFp = existing?.recordedSourceFingerprints?.[recordedKey(entry)];
22122
22326
  if (storedFp === void 0) return false;
22327
+ const live = findings.find((f) => f.logicalId === entry.logicalId && f.path === entry.path && f.resourceType === entry.resourceType);
22328
+ if (live?.deployedSourceHash !== void 0 && live.actual !== live.deployedSourceHash) return false;
22123
22329
  const currentFp = declaredSourceFingerprint(entry.resourceType, entry.path, declaredByLogical.get(entry.logicalId));
22124
22330
  return currentFp !== void 0 && currentFp !== storedFp;
22125
22331
  }
@@ -22267,8 +22473,9 @@ function realOpCount(plan) {
22267
22473
  * interactive prompt — neither re-gathers.)
22268
22474
  */
22269
22475
  async function recordStack(p) {
22270
- const { stackName, region, desired, findings, yes, interactive, preselectedKeys, expandNested } = p;
22476
+ const { stackName, region, desired, yes, interactive, preselectedKeys, expandNested } = p;
22271
22477
  const existing = await loadBaseline(stackName, desired.accountId, region);
22478
+ const findings = await annotateDeployedSourceHashes(p.findings, existing, desired.resources, region, { localAssets: p.localAssets });
22272
22479
  if (existing) checkBaselineAccount(existing, desired.accountId, stackName);
22273
22480
  if (!yes && existing) console.error(`note: ${stackLabel$1(stackName, region)}: will overwrite the existing baseline file on confirm (nothing written yet; it is git-tracked — review the diff afterwards). Pass --yes to silence.`);
22274
22481
  let recorded = carryForwardIgnored(carryForwardUnreadable(buildRecorded(findings), existing, findings), existing, findings);
@@ -22281,7 +22488,7 @@ async function recordStack(p) {
22281
22488
  const declaredModel = declaredKeysByLogical(desired.resources);
22282
22489
  const { changed } = splitRecordedByBaseline(recorded, existing);
22283
22490
  const changedExisting = changed.filter((e) => recordedValueForChanged(e, existing).hasRecorded);
22284
- const redeployedViaCfn = changedExisting.filter((e) => isRecordedSourceRedeployed(e, existing, declaredModel));
22491
+ const redeployedViaCfn = changedExisting.filter((e) => isRecordedSourceRedeployed(e, existing, declaredModel, findings));
22285
22492
  const redeployedKeys = new Set(redeployedViaCfn.map((e) => recordedKey(e)));
22286
22493
  const changedOob = changedExisting.filter((e) => !redeployedKeys.has(recordedKey(e)));
22287
22494
  if (changedOob.length > 0) console.error(`note: ${stackName}: --yes accepted ${changedOob.length} recorded value(s) CHANGED out of band since record (review the baseline diff): ` + changedOob.map((e) => `${e.logicalId}.${e.path}`).join(", "));
@@ -22324,7 +22531,7 @@ async function recordStack(p) {
22324
22531
  const declaredModel = declaredKeysByLogical(desired.resources);
22325
22532
  const fromPrompt = await bulkMultiselect(recordSelectMessage(stackName, region, folded.length), standout.map((e) => {
22326
22533
  const rec = recordedValueForChanged(e, existing);
22327
- const redeployed = isRecordedSourceRedeployed(e, existing, declaredModel);
22534
+ const redeployed = isRecordedSourceRedeployed(e, existing, declaredModel, findings);
22328
22535
  return {
22329
22536
  value: recordedKey(e),
22330
22537
  label: changedRecordLabel(e, rec, redeployed),
@@ -22844,10 +23051,11 @@ async function revertStack(p) {
22844
23051
  region
22845
23052
  }, config);
22846
23053
  const readdFailedDeletes = (findings) => failedDeleteIds.size === 0 ? findings : [...findings, ...gathered.findings.filter((f) => failedDeleteIds.has(f.logicalId))];
22847
- let post = readdFailedDeletes(reconcile(await regatherTouched(gathered, touched, region)));
23054
+ const regather = async () => annotateDeployedSourceHashes(await regatherTouched(gathered, touched, region), baseline, gathered.desired.resources, region, { localAssets: p.localAssets });
23055
+ let post = readdFailedDeletes(reconcile(await regather()));
22848
23056
  if (driftCount(post.filter((f) => touched.has(f.logicalId))) > 0) {
22849
23057
  await sleep(p.convergeRetryDelayMs ?? CONVERGE_RETRY_DELAY_MS);
22850
- post = readdFailedDeletes(reconcile(await regatherTouched(gathered, touched, region)));
23058
+ post = readdFailedDeletes(reconcile(await regather()));
22851
23059
  }
22852
23060
  const remainingDrift = post.filter(isDrift);
22853
23061
  const remaining = remainingDrift.length;
@@ -22951,7 +23159,7 @@ async function runRecord(args) {
22951
23159
  let wroteAny = false;
22952
23160
  const showProgress = !a.json && isInteractive();
22953
23161
  const accountGate = createAccountGate("record");
22954
- for (const [idx, { stackName, region, account, template }] of stacks.entries()) {
23162
+ for (const [idx, { stackName, region, account, template, localAssetHashes }] of stacks.entries()) {
22955
23163
  if (!region) {
22956
23164
  const msg = "no region — set env on the stack, pass --region, or set a region for the AWS profile";
22957
23165
  console.error(`error: ${stackName}: ${msg}`);
@@ -22990,6 +23198,7 @@ async function runRecord(args) {
22990
23198
  }
22991
23199
  warnStackStatus(stackName, desired.stackStatusWarning);
22992
23200
  const result = await recordStack({
23201
+ localAssets: localAssetHashes,
22993
23202
  stackName,
22994
23203
  region,
22995
23204
  desired,
@@ -23091,7 +23300,7 @@ async function runIgnore(args) {
23091
23300
  let wroteAny = false;
23092
23301
  const showProgress = !a.json && isInteractive();
23093
23302
  const accountGate = createAccountGate("ignore");
23094
- for (const [idx, { stackName, region, account, template }] of stacks.entries()) {
23303
+ for (const [idx, { stackName, region, account, template, localAssetHashes }] of stacks.entries()) {
23095
23304
  if (!region) {
23096
23305
  const msg = "no region — set env on the stack, pass --region, or set a region for the AWS profile";
23097
23306
  console.error(`error: ${stackName}: ${msg}`);
@@ -23131,7 +23340,8 @@ async function runIgnore(args) {
23131
23340
  warnStackStatus(stackName, desired.stackStatusWarning);
23132
23341
  const baseline = await loadBaseline(stackName, desired.accountId, region);
23133
23342
  if (baseline) checkBaselineAccount(baseline, desired.accountId, stackName);
23134
- const reconciled = applyIgnores(applyBaseline(findings, baseline, ignoreApplyBaselineOpts(desired)), {
23343
+ const verified = await annotateDeployedSourceHashes(findings, baseline, desired.resources, region, { localAssets: localAssetHashes });
23344
+ const reconciled = applyIgnores(applyBaseline(verified, baseline, ignoreApplyBaselineOpts(desired)), {
23135
23345
  stackName,
23136
23346
  accountId: desired.accountId,
23137
23347
  region
@@ -23548,6 +23758,7 @@ async function resolveInteractively(p) {
23548
23758
  }
23549
23759
  async function recordAll(p) {
23550
23760
  if (!(await recordStack({
23761
+ localAssets: p.localAssets,
23551
23762
  stackName: p.stackName,
23552
23763
  region: p.region,
23553
23764
  desired: p.desired,
@@ -23594,6 +23805,7 @@ async function ignoreAll(p) {
23594
23805
  }
23595
23806
  async function revertAll(p) {
23596
23807
  const outcome = await revertStack({
23808
+ localAssets: p.localAssets,
23597
23809
  stackName: p.stackName,
23598
23810
  region: p.region,
23599
23811
  gathered: {
@@ -23643,6 +23855,7 @@ async function perFinding(p, decidable) {
23643
23855
  const preselectedKeys = new Set(buildRecorded(groups.record).map(recordedKey));
23644
23856
  const recordConfig = groups.ignore.length > 0 ? await loadConfig() : p.config;
23645
23857
  await recordStack({
23858
+ localAssets: p.localAssets,
23646
23859
  stackName: p.stackName,
23647
23860
  region: p.region,
23648
23861
  desired: p.desired,
@@ -23662,6 +23875,7 @@ async function perFinding(p, decidable) {
23662
23875
  if (groups.revert.length > 0) {
23663
23876
  const revertKeys = new Set(groups.revert.map(keyOf));
23664
23877
  const outcome = await revertStack({
23878
+ localAssets: p.localAssets,
23665
23879
  stackName: p.stackName,
23666
23880
  region: p.region,
23667
23881
  gathered: {
@@ -23926,7 +24140,7 @@ async function runCheck(args) {
23926
24140
  }
23927
24141
  return callerAccount;
23928
24142
  };
23929
- for (const [idx, { stackName, region, account, template }] of stacks.entries()) {
24143
+ for (const [idx, { stackName, region, account, template, localAssetHashes }] of stacks.entries()) {
23930
24144
  if (!region) {
23931
24145
  const msg = "no region — set env on the stack, pass --region, or set a region for the AWS profile";
23932
24146
  console.error(`error: ${stackName}: ${msg}`);
@@ -24007,6 +24221,7 @@ async function runCheck(args) {
24007
24221
  if (baseline) checkBaselineAccount(baseline, desired.accountId, stackName);
24008
24222
  if (baseline) warnTemplateHashDrift(baseline, desired.rawTemplate, stackName);
24009
24223
  if (baseline) warnBaselineSchemaV1(baseline, stackName);
24224
+ if (!a.declaredOnly) findings = await annotateDeployedSourceHashes(findings, baseline, desired.resources, region, { localAssets: localAssetHashes });
24010
24225
  const reconciled = applyIgnores(reconcileBaseline(findings, baseline, {
24011
24226
  declaredOnly: a.declaredOnly,
24012
24227
  applyOpts: {
@@ -24040,6 +24255,7 @@ async function runCheck(args) {
24040
24255
  hasBaseline: baseline !== void 0,
24041
24256
  interactive: isInteractive()
24042
24257
  })) code = await resolveInteractively({
24258
+ localAssets: localAssetHashes,
24043
24259
  stackName,
24044
24260
  region,
24045
24261
  desired,
@@ -24122,7 +24338,7 @@ async function runRevert(args) {
24122
24338
  let worst = 0;
24123
24339
  const showProgress = !a.json && isInteractive();
24124
24340
  const accountGate = createAccountGate("revert");
24125
- for (const [idx, { stackName, region, account, template }] of stacks.entries()) {
24341
+ for (const [idx, { stackName, region, account, template, localAssetHashes }] of stacks.entries()) {
24126
24342
  if (!region) {
24127
24343
  const msg = "no region — set env on the stack, pass --region, or set a region for the AWS profile";
24128
24344
  console.error(`error: ${stackName}: ${msg}`);
@@ -24152,7 +24368,7 @@ async function runRevert(args) {
24152
24368
  worst = Math.max(worst, 2);
24153
24369
  continue;
24154
24370
  }
24155
- const gathered = await gatherWithProgress(showProgress, progressLabel(idx, stacks.length, stackName, region), () => gatherFindings(stackName, region, void 0, template));
24371
+ let gathered = await gatherWithProgress(showProgress, progressLabel(idx, stacks.length, stackName, region), () => gatherFindings(stackName, region, void 0, template));
24156
24372
  const readMismatch = accountGate.postRead(account, gathered.desired.accountId);
24157
24373
  if (readMismatch.skip) {
24158
24374
  console.error(`error: ${stackName}: ${readMismatch.message}`);
@@ -24169,8 +24385,13 @@ async function runRevert(args) {
24169
24385
  }
24170
24386
  const baseline = await loadBaseline(stackName, gathered.desired.accountId, region);
24171
24387
  if (baseline) checkBaselineAccount(baseline, gathered.desired.accountId, stackName);
24388
+ gathered = {
24389
+ ...gathered,
24390
+ findings: await annotateDeployedSourceHashes(gathered.findings, baseline, gathered.desired.resources, region, { localAssets: localAssetHashes })
24391
+ };
24172
24392
  warnStackStatus(stackName, gathered.desired.stackStatusWarning);
24173
24393
  const outcome = await revertStack({
24394
+ localAssets: localAssetHashes,
24174
24395
  stackName,
24175
24396
  region,
24176
24397
  gathered,