cdk-real-drift 0.28.2 → 0.29.1

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,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) {
@@ -2128,6 +2195,7 @@ function buildCorpusCase(resource, liveRaw, schema, opts, findings) {
2128
2195
  ...echoModel && resource.physicalId ? { clusterEchoModel: { [resource.physicalId]: echoModel } } : {},
2129
2196
  ...rdsOptCatalog && resource.physicalId ? { rdsOptionSettingDefaults: { [resource.physicalId]: rdsOptCatalog } } : {},
2130
2197
  ...gaListenerPort ? { siblingListenerPorts: gaListenerPort } : {},
2198
+ ...opts.supplementReadGapPaths && opts.supplementReadGapPaths.length > 0 ? { supplementReadGapPaths: [...opts.supplementReadGapPaths] } : {},
2131
2199
  ...dmsStorageDefault || ebsEncDefault ? { accountDefaults: {
2132
2200
  ...dmsStorageDefault ?? {},
2133
2201
  ...ebsEncDefault ?? {}
@@ -12441,24 +12509,6 @@ async function enumerateElasticBeanstalkApplicationChildren(ctx) {
12441
12509
  });
12442
12510
  }
12443
12511
 
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
12512
  // src/read/overrides.ts
12463
12513
  const OVERRIDE_READ_GAP = Symbol.for("cdkrd.overrideReadGap");
12464
12514
  function overrideReadGap(model, readGapPaths) {
@@ -14655,7 +14705,13 @@ const supplementLambdaFunction = async ({ physicalId, region }) => {
14655
14705
  ...READ_RETRY
14656
14706
  }).send(new GetFunctionCommand({ FunctionName: name }));
14657
14707
  const sha = str$1(r.Configuration?.CodeSha256);
14658
- return sha !== void 0 ? { CodeSha256: sha } : void 0;
14708
+ const extra = sha !== void 0 ? { CodeSha256: sha } : void 0;
14709
+ const envError = r.Configuration?.Environment?.Error;
14710
+ if (envError === void 0) return extra;
14711
+ const code = envError.ErrorCode ?? "unknown error";
14712
+ const cause = /AccessDenied/i.test(code) ? "the caller likely lacks kms:Decrypt on the function's key" : "the function's KMS key is unusable";
14713
+ process.stderr.write(`[cdkrd] warning: AWS::Lambda::Function ${name}: environment variables unreadable (${code} — ${cause}) — treating Environment as an unverifiable read-gap\n`);
14714
+ return overrideReadGap(extra ?? {}, ["Environment"]);
14659
14715
  };
14660
14716
  const supplementGlueJob = async ({ physicalId, region }) => {
14661
14717
  const name = str$1(physicalId);
@@ -15402,6 +15458,14 @@ async function readLive(cc, resource, region, accountId) {
15402
15458
  region,
15403
15459
  accountId
15404
15460
  });
15461
+ if (isOverrideReadResult(extra)) {
15462
+ Object.assign(live, extra.model);
15463
+ for (const p of extra.readGapPaths) delete live[p];
15464
+ return {
15465
+ live,
15466
+ readGapPaths: extra.readGapPaths
15467
+ };
15468
+ }
15405
15469
  if (extra) Object.assign(live, extra);
15406
15470
  } catch (e) {
15407
15471
  return {
@@ -16649,9 +16713,13 @@ async function gatherFindings(stackName, region, templateOverride, recoveryTempl
16649
16713
  for (const r of desired.resources) {
16650
16714
  const resourceFindings = await classifyRead(cfn, r, reads.get(r.logicalId), schemas, classifyOpts);
16651
16715
  findings.push(...resourceFindings);
16652
- const live = reads.get(r.logicalId)?.live;
16716
+ const read = reads.get(r.logicalId);
16717
+ const live = read?.live;
16653
16718
  const schema = schemas.get(r.resourceType);
16654
- if (corpusDir && live && schema) await recordCorpusCase(corpusDir, buildCorpusCase(r, live, schema, classifyOpts, resourceFindings));
16719
+ if (corpusDir && live && schema) await recordCorpusCase(corpusDir, buildCorpusCase(r, live, schema, {
16720
+ ...classifyOpts,
16721
+ supplementReadGapPaths: read?.readGapPaths
16722
+ }, resourceFindings));
16655
16723
  }
16656
16724
  return {
16657
16725
  desired,
@@ -17368,6 +17436,28 @@ function declaredSourceFingerprint(resourceType, path, declared) {
17368
17436
  return node === void 0 ? void 0 : stableValueHash(node);
17369
17437
  }
17370
17438
  /**
17439
+ * The recorded keys whose content hash is VOID because its declared source was redeployed
17440
+ * through CloudFormation since record (the #1606 stale-source void): a stored fingerprint
17441
+ * EXISTS and the current declared source RESOLVES to a different one. Shared by
17442
+ * `applyBaseline` and the #1958 deployed-source verifier, which fetches only these.
17443
+ */
17444
+ function sourceRedeployedKeys(baseline, declaredByLogical) {
17445
+ const out = /* @__PURE__ */ new Set();
17446
+ const stored = baseline.recordedSourceFingerprints ?? {};
17447
+ for (const e of baseline.recorded) {
17448
+ const storedFp = stored[recordedKey(e)];
17449
+ if (storedFp === void 0) continue;
17450
+ const currentFp = declaredSourceFingerprint(e.resourceType, e.path, declaredByLogical?.get(e.logicalId));
17451
+ if (currentFp !== void 0 && currentFp !== storedFp) out.add(recordedKey(e));
17452
+ }
17453
+ return out;
17454
+ }
17455
+ const DEPLOYED_SOURCE_VERIFIABLE = {
17456
+ "AWS::Lambda::Function": "CodeSha256",
17457
+ "AWS::Glue::Job": "ScriptSha256",
17458
+ "AWS::ElasticLoadBalancingV2::TrustStore": "CaCertificatesBundleSha256"
17459
+ };
17460
+ /**
17371
17461
  * Build the `recordedSourceFingerprints` map for the entries being written. For each entry
17372
17462
  * with a source mapping: prefer the PREVIOUS baseline's fingerprint when the entry's VALUE
17373
17463
  * was carried forward unchanged from it (a resource unread this run — e.g. skipped — must
@@ -17753,14 +17843,9 @@ function applyBaseline(findings, baseline, opts = {}) {
17753
17843
  const liveId = opts.physicalIdByLogical?.get(logicalId);
17754
17844
  if (liveId !== void 0 && liveId !== recordedId) replacedLogical.add(logicalId);
17755
17845
  }
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
- }
17846
+ const sourceRedeployedVoid = sourceRedeployedKeys(baseline, opts.declaredByLogical);
17847
+ const sourceSwapped = /* @__PURE__ */ new Set();
17848
+ const sourceVerified = /* @__PURE__ */ new Set();
17764
17849
  const liveTypeByLogical = /* @__PURE__ */ new Map();
17765
17850
  for (const f of findings) if (f.resourceType) liveTypeByLogical.set(f.logicalId, f.resourceType);
17766
17851
  const isTypeVoid = (e) => {
@@ -17768,7 +17853,13 @@ function applyBaseline(findings, baseline, opts = {}) {
17768
17853
  return liveType !== void 0 && liveType !== e.resourceType;
17769
17854
  };
17770
17855
  const entryMatches = (a, f) => a.logicalId === f.logicalId && a.path === f.path && a.resourceType === f.resourceType;
17771
- for (const f of findings) {
17856
+ for (const stamped of findings) {
17857
+ const deployedSourceHash = stamped.deployedSourceHash;
17858
+ let f = stamped;
17859
+ if (deployedSourceHash !== void 0) {
17860
+ f = { ...stamped };
17861
+ delete f.deployedSourceHash;
17862
+ }
17772
17863
  if (f.tier === "added") {
17773
17864
  const entry = recorded.find((a) => entryMatches(a, f));
17774
17865
  if (f.modelReadFailed) {
@@ -17807,6 +17898,21 @@ function applyBaseline(findings, baseline, opts = {}) {
17807
17898
  }
17808
17899
  const matched = replacedLogical.has(f.logicalId) ? void 0 : recorded.find((a) => entryMatches(a, f));
17809
17900
  const sourceRedeployVoided = matched !== void 0 && sourceRedeployedVoid.has(recordedKey(matched));
17901
+ if (matched !== void 0 && sourceRedeployVoided && deployedSourceHash !== void 0) {
17902
+ if (f.actual === deployedSourceHash) {
17903
+ sourceVerified.add(recordedKey(matched));
17904
+ if (f.tier !== "undeclared") kept.push(f);
17905
+ } else {
17906
+ sourceSwapped.add(recordedKey(matched));
17907
+ kept.push({
17908
+ ...f,
17909
+ tier: "undeclared",
17910
+ desired: deployedSourceHash,
17911
+ note: "differs from the content the template deploys (changed out of band since the last deploy of it)"
17912
+ });
17913
+ }
17914
+ continue;
17915
+ }
17810
17916
  if (sourceRedeployVoided && f.tier === "undeclared") continue;
17811
17917
  const entry = sourceRedeployVoided ? void 0 : matched;
17812
17918
  if (entry && baselineValueMatches(entry.value, f.actual, f.resourceType, f.path)) continue;
@@ -17853,6 +17959,7 @@ function applyBaseline(findings, baseline, opts = {}) {
17853
17959
  const adoptedStale = [];
17854
17960
  const nameStrippedStale = [];
17855
17961
  const sourceRedeployedStale = [];
17962
+ const sourceUnverified = [];
17856
17963
  for (const a of recorded) {
17857
17964
  if (a.path === "") {
17858
17965
  if (presentAddedLogical.has(a.logicalId)) continue;
@@ -17881,7 +17988,9 @@ function applyBaseline(findings, baseline, opts = {}) {
17881
17988
  continue;
17882
17989
  }
17883
17990
  if (sourceRedeployedVoid.has(recordedKey(a))) {
17991
+ if (sourceSwapped.has(recordedKey(a))) continue;
17884
17992
  sourceRedeployedStale.push(`${a.logicalId}.${a.path}`);
17993
+ if (!sourceVerified.has(recordedKey(a)) && DEPLOYED_SOURCE_VERIFIABLE[a.resourceType] === a.path) sourceUnverified.push(`${a.logicalId}.${a.path}`);
17885
17994
  continue;
17886
17995
  }
17887
17996
  if (currentPaths.has(`${a.logicalId}.${a.path}`)) continue;
@@ -17944,6 +18053,7 @@ function applyBaseline(findings, baseline, opts = {}) {
17944
18053
  if (adoptedStale.length > 0) opts.warn?.(formatAdoptedStaleNote(adoptedStale));
17945
18054
  if (nameStrippedStale.length > 0) opts.warn?.(formatNameStrippedStaleNote(nameStrippedStale));
17946
18055
  if (sourceRedeployedStale.length > 0) opts.warn?.(formatSourceRedeployedStaleNote(sourceRedeployedStale));
18056
+ if (sourceUnverified.length > 0) opts.warn?.(formatSourceUnverifiedNote(sourceUnverified));
17947
18057
  return kept;
17948
18058
  }
17949
18059
  /**
@@ -17958,6 +18068,15 @@ function formatSourceRedeployedStaleNote(paths) {
17958
18068
  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
18069
  }
17960
18070
  /**
18071
+ * #1958: the coverage note for stale-source voids whose live hash could NOT be verified
18072
+ * against the deployed source (the asset object was unreadable, or the source is not an S3
18073
+ * object) — an out-of-band swap since that redeploy goes unseen until a re-record, and the
18074
+ * user must know the CLEAN verdict does not cover it. Pure + exported for unit tests.
18075
+ */
18076
+ function formatSourceUnverifiedNote(paths) {
18077
+ 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.`;
18078
+ }
18079
+ /**
17961
18080
  * The folded one-line note for baseline entries now declared in the template (R134). One
17962
18081
  * line with a count instead of one line per entry; `record` re-snapshots to clear them.
17963
18082
  * Pure + exported for unit tests.
@@ -18057,6 +18176,108 @@ function warnTemplateHashDrift(baseline, rawTemplate, stackName, warn = console.
18057
18176
  if (baseline.templateHash !== hashTemplate(rawTemplate)) warn(`note: ${stackName}: baseline was captured against a different template version — consider re-running \`cdkrd record\`.`);
18058
18177
  }
18059
18178
 
18179
+ // src/read/deployed-source-hash.ts
18180
+ const s3Clients = /* @__PURE__ */ new Map();
18181
+ const fetchS3Sha256Base64 = async (ref, region) => {
18182
+ let s3 = s3Clients.get(region);
18183
+ if (s3 === void 0) {
18184
+ s3 = new S3Client({
18185
+ region,
18186
+ followRegionRedirects: true,
18187
+ ...READ_RETRY
18188
+ });
18189
+ s3Clients.set(region, s3);
18190
+ }
18191
+ const body = (await s3.send(new GetObjectCommand({
18192
+ Bucket: ref.bucket,
18193
+ Key: ref.key,
18194
+ ...ref.versionId !== void 0 && { VersionId: ref.versionId }
18195
+ }))).Body;
18196
+ if (body === void 0) throw new Error("empty S3 object body");
18197
+ const h = createHash("sha256");
18198
+ for await (const chunk of body) h.update(chunk);
18199
+ return h.digest("base64");
18200
+ };
18201
+ const FETCH_CONCURRENCY = 4;
18202
+ function lambdaCodeS3Ref(declared) {
18203
+ const code = declared?.["Code"];
18204
+ if (code === null || typeof code !== "object" || Array.isArray(code)) return void 0;
18205
+ const { S3Bucket, S3Key, S3ObjectVersion } = code;
18206
+ if (typeof S3Bucket !== "string" || typeof S3Key !== "string") return void 0;
18207
+ if (S3ObjectVersion !== void 0 && typeof S3ObjectVersion !== "string") return void 0;
18208
+ return {
18209
+ bucket: S3Bucket,
18210
+ key: S3Key,
18211
+ versionId: S3ObjectVersion
18212
+ };
18213
+ }
18214
+ function localAssetHash(f, declared, localAssets) {
18215
+ if (localAssets === void 0 || declared === void 0) return void 0;
18216
+ if (f.resourceType === "AWS::Glue::Job") {
18217
+ const loc = declared["Command"]?.["ScriptLocation"];
18218
+ const m = typeof loc === "string" ? /^s3:\/\/[^/]+\/(.+)$/.exec(loc) : null;
18219
+ return m === null ? void 0 : localAssets[m[1]]?.sha256Hex;
18220
+ }
18221
+ if (f.resourceType === "AWS::ElasticLoadBalancingV2::TrustStore") {
18222
+ const key = declared["CaCertificatesBundleS3Key"];
18223
+ return typeof key === "string" ? localAssets[key]?.caBundleSha256 : void 0;
18224
+ }
18225
+ }
18226
+ /**
18227
+ * #1958: stamp `deployedSourceHash` on each live content-hash finding whose recorded entry
18228
+ * the stale-source void (#1606) would drop — a legit code redeploy since record — so
18229
+ * `applyBaseline` can still catch an out-of-band swap made AFTER that redeploy instead of
18230
+ * reading CLEAN until the next `record`. Only the voided entries are fetched (an S3 read of
18231
+ * every function's package on every check would be the wrong cost). Fail-safe: any read
18232
+ * failure (no s3:GetObject on the asset bucket, a lifecycle-expired asset) or a non-S3 source
18233
+ * leaves the finding unstamped, which keeps today's void plus a coverage note. #1960: Glue
18234
+ * ScriptSha256 / TrustStore CaCertificatesBundleSha256 take their expected hash from the
18235
+ * local synthesized asset instead (no fetch).
18236
+ */
18237
+ async function annotateDeployedSourceHashes(findings, baseline, resources, region, opts = {}) {
18238
+ const fetch = opts.fetch ?? fetchS3Sha256Base64;
18239
+ if (!baseline) return findings;
18240
+ const declaredByLogical = new Map(resources.map((r) => [r.logicalId, r.declared]));
18241
+ const voided = sourceRedeployedKeys(baseline, declaredByLogical);
18242
+ if (voided.size === 0) return findings;
18243
+ const jobs = [];
18244
+ const hashes = /* @__PURE__ */ new Map();
18245
+ findings.forEach((f, i) => {
18246
+ if (f.deployedSourceHash !== void 0) return;
18247
+ if (DEPLOYED_SOURCE_VERIFIABLE[f.resourceType] !== f.path) return;
18248
+ if (!voided.has(recordedKey(f))) return;
18249
+ const declared = declaredByLogical.get(f.logicalId);
18250
+ if (f.resourceType !== "AWS::Lambda::Function") {
18251
+ const h = localAssetHash(f, declared, opts.localAssets);
18252
+ if (h !== void 0) hashes.set(i, h);
18253
+ return;
18254
+ }
18255
+ const ref = lambdaCodeS3Ref(declared);
18256
+ if (ref !== void 0) jobs.push({
18257
+ i,
18258
+ ref
18259
+ });
18260
+ });
18261
+ let next = 0;
18262
+ const worker = async () => {
18263
+ while (next < jobs.length) {
18264
+ const { i, ref } = jobs[next++];
18265
+ try {
18266
+ hashes.set(i, await fetch(ref, region));
18267
+ } catch {}
18268
+ }
18269
+ };
18270
+ if (jobs.length > 0) await Promise.all(Array.from({ length: Math.min(FETCH_CONCURRENCY, jobs.length) }, worker));
18271
+ if (hashes.size === 0) return findings;
18272
+ return findings.map((f, i) => {
18273
+ const h = hashes.get(i);
18274
+ return h === void 0 ? f : {
18275
+ ...f,
18276
+ deployedSourceHash: h
18277
+ };
18278
+ });
18279
+ }
18280
+
18060
18281
  // src/diff/hints.ts
18061
18282
  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
18283
  const INSIGHTS_LAYER = /:layer:LambdaInsightsExtension(-Arm64)?:/;
@@ -22115,11 +22336,15 @@ function changedRecordLabel(entry, recordedValue, sourceRedeployed = false) {
22115
22336
  * change out of band (the IaC deploy moved the live hash with the template), so record must
22116
22337
  * label and summarize it as a legit refresh, not "CHANGED out of band". Fail-safe: false when
22117
22338
  * 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.
22339
+ * current declared source does not resolve — exactly the void's own gates. #1958: also
22340
+ * false when the entry's live finding carries a `deployedSourceHash` that differs from its
22341
+ * live value — the code was swapped out of band AFTER the redeploy. Pure + exported.
22119
22342
  */
22120
- function isRecordedSourceRedeployed(entry, existing, declaredByLogical) {
22343
+ function isRecordedSourceRedeployed(entry, existing, declaredByLogical, findings = []) {
22121
22344
  const storedFp = existing?.recordedSourceFingerprints?.[recordedKey(entry)];
22122
22345
  if (storedFp === void 0) return false;
22346
+ const live = findings.find((f) => f.logicalId === entry.logicalId && f.path === entry.path && f.resourceType === entry.resourceType);
22347
+ if (live?.deployedSourceHash !== void 0 && live.actual !== live.deployedSourceHash) return false;
22123
22348
  const currentFp = declaredSourceFingerprint(entry.resourceType, entry.path, declaredByLogical.get(entry.logicalId));
22124
22349
  return currentFp !== void 0 && currentFp !== storedFp;
22125
22350
  }
@@ -22267,8 +22492,9 @@ function realOpCount(plan) {
22267
22492
  * interactive prompt — neither re-gathers.)
22268
22493
  */
22269
22494
  async function recordStack(p) {
22270
- const { stackName, region, desired, findings, yes, interactive, preselectedKeys, expandNested } = p;
22495
+ const { stackName, region, desired, yes, interactive, preselectedKeys, expandNested } = p;
22271
22496
  const existing = await loadBaseline(stackName, desired.accountId, region);
22497
+ const findings = await annotateDeployedSourceHashes(p.findings, existing, desired.resources, region, { localAssets: p.localAssets });
22272
22498
  if (existing) checkBaselineAccount(existing, desired.accountId, stackName);
22273
22499
  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
22500
  let recorded = carryForwardIgnored(carryForwardUnreadable(buildRecorded(findings), existing, findings), existing, findings);
@@ -22281,7 +22507,7 @@ async function recordStack(p) {
22281
22507
  const declaredModel = declaredKeysByLogical(desired.resources);
22282
22508
  const { changed } = splitRecordedByBaseline(recorded, existing);
22283
22509
  const changedExisting = changed.filter((e) => recordedValueForChanged(e, existing).hasRecorded);
22284
- const redeployedViaCfn = changedExisting.filter((e) => isRecordedSourceRedeployed(e, existing, declaredModel));
22510
+ const redeployedViaCfn = changedExisting.filter((e) => isRecordedSourceRedeployed(e, existing, declaredModel, findings));
22285
22511
  const redeployedKeys = new Set(redeployedViaCfn.map((e) => recordedKey(e)));
22286
22512
  const changedOob = changedExisting.filter((e) => !redeployedKeys.has(recordedKey(e)));
22287
22513
  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 +22550,7 @@ async function recordStack(p) {
22324
22550
  const declaredModel = declaredKeysByLogical(desired.resources);
22325
22551
  const fromPrompt = await bulkMultiselect(recordSelectMessage(stackName, region, folded.length), standout.map((e) => {
22326
22552
  const rec = recordedValueForChanged(e, existing);
22327
- const redeployed = isRecordedSourceRedeployed(e, existing, declaredModel);
22553
+ const redeployed = isRecordedSourceRedeployed(e, existing, declaredModel, findings);
22328
22554
  return {
22329
22555
  value: recordedKey(e),
22330
22556
  label: changedRecordLabel(e, rec, redeployed),
@@ -22844,10 +23070,11 @@ async function revertStack(p) {
22844
23070
  region
22845
23071
  }, config);
22846
23072
  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)));
23073
+ const regather = async () => annotateDeployedSourceHashes(await regatherTouched(gathered, touched, region), baseline, gathered.desired.resources, region, { localAssets: p.localAssets });
23074
+ let post = readdFailedDeletes(reconcile(await regather()));
22848
23075
  if (driftCount(post.filter((f) => touched.has(f.logicalId))) > 0) {
22849
23076
  await sleep(p.convergeRetryDelayMs ?? CONVERGE_RETRY_DELAY_MS);
22850
- post = readdFailedDeletes(reconcile(await regatherTouched(gathered, touched, region)));
23077
+ post = readdFailedDeletes(reconcile(await regather()));
22851
23078
  }
22852
23079
  const remainingDrift = post.filter(isDrift);
22853
23080
  const remaining = remainingDrift.length;
@@ -22951,7 +23178,7 @@ async function runRecord(args) {
22951
23178
  let wroteAny = false;
22952
23179
  const showProgress = !a.json && isInteractive();
22953
23180
  const accountGate = createAccountGate("record");
22954
- for (const [idx, { stackName, region, account, template }] of stacks.entries()) {
23181
+ for (const [idx, { stackName, region, account, template, localAssetHashes }] of stacks.entries()) {
22955
23182
  if (!region) {
22956
23183
  const msg = "no region — set env on the stack, pass --region, or set a region for the AWS profile";
22957
23184
  console.error(`error: ${stackName}: ${msg}`);
@@ -22990,6 +23217,7 @@ async function runRecord(args) {
22990
23217
  }
22991
23218
  warnStackStatus(stackName, desired.stackStatusWarning);
22992
23219
  const result = await recordStack({
23220
+ localAssets: localAssetHashes,
22993
23221
  stackName,
22994
23222
  region,
22995
23223
  desired,
@@ -23091,7 +23319,7 @@ async function runIgnore(args) {
23091
23319
  let wroteAny = false;
23092
23320
  const showProgress = !a.json && isInteractive();
23093
23321
  const accountGate = createAccountGate("ignore");
23094
- for (const [idx, { stackName, region, account, template }] of stacks.entries()) {
23322
+ for (const [idx, { stackName, region, account, template, localAssetHashes }] of stacks.entries()) {
23095
23323
  if (!region) {
23096
23324
  const msg = "no region — set env on the stack, pass --region, or set a region for the AWS profile";
23097
23325
  console.error(`error: ${stackName}: ${msg}`);
@@ -23131,7 +23359,8 @@ async function runIgnore(args) {
23131
23359
  warnStackStatus(stackName, desired.stackStatusWarning);
23132
23360
  const baseline = await loadBaseline(stackName, desired.accountId, region);
23133
23361
  if (baseline) checkBaselineAccount(baseline, desired.accountId, stackName);
23134
- const reconciled = applyIgnores(applyBaseline(findings, baseline, ignoreApplyBaselineOpts(desired)), {
23362
+ const verified = await annotateDeployedSourceHashes(findings, baseline, desired.resources, region, { localAssets: localAssetHashes });
23363
+ const reconciled = applyIgnores(applyBaseline(verified, baseline, ignoreApplyBaselineOpts(desired)), {
23135
23364
  stackName,
23136
23365
  accountId: desired.accountId,
23137
23366
  region
@@ -23548,6 +23777,7 @@ async function resolveInteractively(p) {
23548
23777
  }
23549
23778
  async function recordAll(p) {
23550
23779
  if (!(await recordStack({
23780
+ localAssets: p.localAssets,
23551
23781
  stackName: p.stackName,
23552
23782
  region: p.region,
23553
23783
  desired: p.desired,
@@ -23594,6 +23824,7 @@ async function ignoreAll(p) {
23594
23824
  }
23595
23825
  async function revertAll(p) {
23596
23826
  const outcome = await revertStack({
23827
+ localAssets: p.localAssets,
23597
23828
  stackName: p.stackName,
23598
23829
  region: p.region,
23599
23830
  gathered: {
@@ -23643,6 +23874,7 @@ async function perFinding(p, decidable) {
23643
23874
  const preselectedKeys = new Set(buildRecorded(groups.record).map(recordedKey));
23644
23875
  const recordConfig = groups.ignore.length > 0 ? await loadConfig() : p.config;
23645
23876
  await recordStack({
23877
+ localAssets: p.localAssets,
23646
23878
  stackName: p.stackName,
23647
23879
  region: p.region,
23648
23880
  desired: p.desired,
@@ -23662,6 +23894,7 @@ async function perFinding(p, decidable) {
23662
23894
  if (groups.revert.length > 0) {
23663
23895
  const revertKeys = new Set(groups.revert.map(keyOf));
23664
23896
  const outcome = await revertStack({
23897
+ localAssets: p.localAssets,
23665
23898
  stackName: p.stackName,
23666
23899
  region: p.region,
23667
23900
  gathered: {
@@ -23926,7 +24159,7 @@ async function runCheck(args) {
23926
24159
  }
23927
24160
  return callerAccount;
23928
24161
  };
23929
- for (const [idx, { stackName, region, account, template }] of stacks.entries()) {
24162
+ for (const [idx, { stackName, region, account, template, localAssetHashes }] of stacks.entries()) {
23930
24163
  if (!region) {
23931
24164
  const msg = "no region — set env on the stack, pass --region, or set a region for the AWS profile";
23932
24165
  console.error(`error: ${stackName}: ${msg}`);
@@ -24007,6 +24240,7 @@ async function runCheck(args) {
24007
24240
  if (baseline) checkBaselineAccount(baseline, desired.accountId, stackName);
24008
24241
  if (baseline) warnTemplateHashDrift(baseline, desired.rawTemplate, stackName);
24009
24242
  if (baseline) warnBaselineSchemaV1(baseline, stackName);
24243
+ if (!a.declaredOnly) findings = await annotateDeployedSourceHashes(findings, baseline, desired.resources, region, { localAssets: localAssetHashes });
24010
24244
  const reconciled = applyIgnores(reconcileBaseline(findings, baseline, {
24011
24245
  declaredOnly: a.declaredOnly,
24012
24246
  applyOpts: {
@@ -24040,6 +24274,7 @@ async function runCheck(args) {
24040
24274
  hasBaseline: baseline !== void 0,
24041
24275
  interactive: isInteractive()
24042
24276
  })) code = await resolveInteractively({
24277
+ localAssets: localAssetHashes,
24043
24278
  stackName,
24044
24279
  region,
24045
24280
  desired,
@@ -24122,7 +24357,7 @@ async function runRevert(args) {
24122
24357
  let worst = 0;
24123
24358
  const showProgress = !a.json && isInteractive();
24124
24359
  const accountGate = createAccountGate("revert");
24125
- for (const [idx, { stackName, region, account, template }] of stacks.entries()) {
24360
+ for (const [idx, { stackName, region, account, template, localAssetHashes }] of stacks.entries()) {
24126
24361
  if (!region) {
24127
24362
  const msg = "no region — set env on the stack, pass --region, or set a region for the AWS profile";
24128
24363
  console.error(`error: ${stackName}: ${msg}`);
@@ -24152,7 +24387,7 @@ async function runRevert(args) {
24152
24387
  worst = Math.max(worst, 2);
24153
24388
  continue;
24154
24389
  }
24155
- const gathered = await gatherWithProgress(showProgress, progressLabel(idx, stacks.length, stackName, region), () => gatherFindings(stackName, region, void 0, template));
24390
+ let gathered = await gatherWithProgress(showProgress, progressLabel(idx, stacks.length, stackName, region), () => gatherFindings(stackName, region, void 0, template));
24156
24391
  const readMismatch = accountGate.postRead(account, gathered.desired.accountId);
24157
24392
  if (readMismatch.skip) {
24158
24393
  console.error(`error: ${stackName}: ${readMismatch.message}`);
@@ -24169,8 +24404,13 @@ async function runRevert(args) {
24169
24404
  }
24170
24405
  const baseline = await loadBaseline(stackName, gathered.desired.accountId, region);
24171
24406
  if (baseline) checkBaselineAccount(baseline, gathered.desired.accountId, stackName);
24407
+ gathered = {
24408
+ ...gathered,
24409
+ findings: await annotateDeployedSourceHashes(gathered.findings, baseline, gathered.desired.resources, region, { localAssets: localAssetHashes })
24410
+ };
24172
24411
  warnStackStatus(stackName, gathered.desired.stackStatusWarning);
24173
24412
  const outcome = await revertStack({
24413
+ localAssets: localAssetHashes,
24174
24414
  stackName,
24175
24415
  region,
24176
24416
  gathered,