cdk-real-drift 0.28.1 → 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/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) {
@@ -4065,11 +4132,23 @@ function stripAsymmetricIdentityFields(declared, live) {
4065
4132
  const ORDER_SIGNIFICANT_ARRAY_KEYS = {
4066
4133
  "AWS::CodePipeline::Pipeline": /* @__PURE__ */ new Set(["Stages", "Actions"]),
4067
4134
  "AWS::Logs::Transformer": /* @__PURE__ */ new Set(["TransformerConfig"]),
4068
- "AWS::SSMContacts::Plan": /* @__PURE__ */ new Set(["Stages"])
4135
+ "AWS::SSMContacts::Plan": /* @__PURE__ */ new Set(["Stages"]),
4136
+ "AWS::Glue::Table": /* @__PURE__ */ new Set([
4137
+ "Columns",
4138
+ "PartitionKeys",
4139
+ "SortColumns"
4140
+ ]),
4141
+ "AWS::Glue::Partition": /* @__PURE__ */ new Set(["Columns", "SortColumns"])
4069
4142
  };
4070
4143
  const ORDER_SIGNIFICANT_PATHS = {
4071
4144
  "AWS::Scheduler::Schedule": /* @__PURE__ */ new Set(["Target.EcsParameters.PlacementStrategy"]),
4072
- "AWS::AppSync::Resolver": /* @__PURE__ */ new Set(["PipelineConfig.Functions"])
4145
+ "AWS::AppSync::Resolver": /* @__PURE__ */ new Set(["PipelineConfig.Functions"]),
4146
+ "AWS::Glue::Table": /* @__PURE__ */ new Set([
4147
+ "TableInput.StorageDescriptor.Columns",
4148
+ "TableInput.PartitionKeys",
4149
+ "TableInput.StorageDescriptor.SortColumns",
4150
+ "TableInput.StorageDescriptor.BucketColumns"
4151
+ ])
4073
4152
  };
4074
4153
  function canonicalizeTagListsDeep(v, orderSig) {
4075
4154
  return canonicalizeTagLists(v, orderSig, void 0);
@@ -5691,7 +5770,9 @@ function arnMatchesName(arn, name, opts) {
5691
5770
  const afterSlash = afterColon.includes("/") ? afterColon.slice(afterColon.lastIndexOf("/") + 1) : afterColon;
5692
5771
  const seg = arn.split(":");
5693
5772
  const colonId = seg.length >= 7 ? seg.slice(6).join(":") : afterColon;
5694
- if (name !== afterColon && name !== afterSlash && name !== colonId) return false;
5773
+ if (seg.length >= 8) {
5774
+ if (name !== colonId) return false;
5775
+ } else if (name !== afterColon && name !== afterSlash && name !== colonId) return false;
5695
5776
  const arnRegion = seg[3] ?? "";
5696
5777
  const arnAccount = seg[4] ?? "";
5697
5778
  if (opts?.region && arnRegion && arnRegion !== opts.region) return false;
@@ -5700,11 +5781,11 @@ function arnMatchesName(arn, name, opts) {
5700
5781
  }
5701
5782
  const KMS_KEY_ARN_RE = /^arn:aws[a-z-]*:kms:[^:]*:\d*:key\//;
5702
5783
  const keyIdOf$1 = (s) => s.slice(s.lastIndexOf("/") + 1);
5703
- function isManagedKmsAliasMatch(desired, actual, aliasTargets) {
5704
- if (typeof desired !== "string" || typeof actual !== "string" || !desired.startsWith("alias/aws/") || !KMS_KEY_ARN_RE.test(actual)) return false;
5784
+ function managedKmsAliasVerdict(desired, actual, aliasTargets) {
5785
+ if (typeof desired !== "string" || typeof actual !== "string" || !desired.startsWith("alias/aws/") || !KMS_KEY_ARN_RE.test(actual)) return void 0;
5705
5786
  const target = aliasTargets?.[desired];
5706
- if (target) return keyIdOf$1(actual) === keyIdOf$1(target);
5707
- return true;
5787
+ if (!target) return "unresolved";
5788
+ return keyIdOf$1(actual) === keyIdOf$1(target) ? "match" : "mismatch";
5708
5789
  }
5709
5790
  const LOG_GROUP_ARN_RE = /^arn:aws[a-z-]*:logs:[^:]*:\d*:log-group:/;
5710
5791
  const stripLogGroupWildcard = (s) => s.endsWith(":*") ? s.slice(0, -2) : s;
@@ -5811,11 +5892,11 @@ async function fetchManagedAliasTargets(region) {
5811
5892
  }
5812
5893
  }
5813
5894
  /** The one-line warning emitted when ListAliases is denied but the stack declares an
5814
- * AWS-managed alias: the managed-vs-customer key check degrades to shape-only, which
5815
- * is BLIND to a customer-managed key swapped in for an `alias/aws/*` default. Pure +
5895
+ * AWS-managed alias: the managed-vs-customer key check cannot run, so every
5896
+ * `alias/aws/*` vs live-key pair is reported unverified instead of compared. Pure +
5816
5897
  * exported so the wording is unit-tested. */
5817
5898
  function kmsListAliasesDeniedWarning(region) {
5818
- return `warning: ${region}: kms:ListAliases denied — managed-KMS-alias drift detection is degraded. A customer-managed key swapped in for an AWS-managed default (alias/aws/*) will NOT be detected (every alias/aws/* is treated as matching any live key). Grant kms:ListAliases for full coverage.`;
5899
+ return `warning: ${region}: kms:ListAliases denied — managed-KMS-alias drift detection is degraded. Whether a live key is still the AWS-managed default (alias/aws/*) cannot be verified, so those values are reported as unreadable / not compared. Grant kms:ListAliases for full coverage.`;
5819
5900
  }
5820
5901
  /** The one-line warning emitted when ListAliases fails TRANSIENTLY (throttle / network
5821
5902
  * blip / 5xx) for a stack that declares an AWS-managed alias: the managed-vs-customer
@@ -5859,16 +5940,16 @@ const keyIdOf = (s) => s.slice(s.lastIndexOf("/") + 1);
5859
5940
  /** #704 fold decision for an UNDECLARED managed-service-key nested path (DynamoDB SSE,
5860
5941
  * OpenSearch EncryptionAtRest). Returns whether the value-independent fold should still
5861
5942
  * apply for this live value:
5862
- * - `true` → FOLD (atDefault): the live key IS the account/region AWS-managed key, OR the
5863
- * alias could not be resolved (fail OPEN — no ListAliases / denied / transient).
5943
+ * - `true` → FOLD (atDefault): the live key IS the account/region AWS-managed key.
5864
5944
  * - `false` → SURFACE (undeclared): the live key is some OTHER key (a customer-managed key
5865
- * swapped in out of band — a real, security-relevant drift).
5945
+ * swapped in out of band — a real, security-relevant drift), OR the alias could
5946
+ * not be resolved (no ListAliases / denied / transient; #1952).
5866
5947
  * Pure; `aliasTargets` is the resolved alias-name -> target-key-id map (empty when unresolved).*/
5867
5948
  function shouldFoldManagedServiceKey(resourceType, schemaPath, liveValue, aliasTargets) {
5868
5949
  const alias = MANAGED_KEY_ALIAS_PATHS[resourceType]?.[schemaPath];
5869
5950
  if (!alias) return false;
5870
5951
  const target = aliasTargets?.[alias];
5871
- if (!target) return true;
5952
+ if (!target) return false;
5872
5953
  if (typeof liveValue !== "string") return true;
5873
5954
  return keyIdOf(liveValue) === keyIdOf(target);
5874
5955
  }
@@ -5969,7 +6050,6 @@ function canonicalizeStatement(s) {
5969
6050
  const out = {};
5970
6051
  for (const k of Object.keys(s).sort()) {
5971
6052
  const v = s[k];
5972
- if (k === "Sid" && typeof v === "string" && /^\d+$/.test(v)) continue;
5973
6053
  if (ARRAYISH_KEYS.has(k)) out[k] = toSortedArray(v);
5974
6054
  else if (k === "Principal" || k === "NotPrincipal") out[k] = canonicalizePrincipal(v);
5975
6055
  else if (k === "Condition") out[k] = canonicalizeCondition(v);
@@ -5988,7 +6068,7 @@ const AWS_LOG_DELIVERY_ALLOWED_ACTIONS = /* @__PURE__ */ new Set([
5988
6068
  function isAwsManagedLogDeliveryStatement(s) {
5989
6069
  if (!isObj(s)) return false;
5990
6070
  const sid = s.Sid;
5991
- if (typeof sid !== "string" || !/^AWSLogDelivery/.test(sid)) return false;
6071
+ if (typeof sid !== "string" || !LOG_DELIVERY_SID_RE.test(sid)) return false;
5992
6072
  const principal = s.Principal;
5993
6073
  if (!isObj(principal)) return false;
5994
6074
  const svc = principal.Service;
@@ -5997,7 +6077,28 @@ function isAwsManagedLogDeliveryStatement(s) {
5997
6077
  const actionRaw = s.Action;
5998
6078
  const actions = Array.isArray(actionRaw) ? actionRaw : [actionRaw];
5999
6079
  if (actions.length === 0) return false;
6000
- return actions.every((a) => typeof a === "string" && AWS_LOG_DELIVERY_ALLOWED_ACTIONS.has(a));
6080
+ if (!actions.every((a) => typeof a === "string" && AWS_LOG_DELIVERY_ALLOWED_ACTIONS.has(a))) return false;
6081
+ return hasSourceCondition(s.Condition);
6082
+ }
6083
+ const SOURCE_CONDITION_KEYS = /* @__PURE__ */ new Set(["aws:sourceaccount", "aws:sourcearn"]);
6084
+ function hasSourceCondition(cond) {
6085
+ if (!isObj(cond)) return false;
6086
+ return Object.values(cond).some((body) => isObj(body) && Object.keys(body).some((k) => SOURCE_CONDITION_KEYS.has(k.toLowerCase())));
6087
+ }
6088
+ const LOG_DELIVERY_SID_RE = /^AWSLogDelivery/;
6089
+ /** #1952: the Sids of every `AWSLogDelivery*` statement a (declared) value carries, at any
6090
+ * depth and inside JSON-string policies too. Passed back as `keepLogDeliverySids` so a
6091
+ * DECLARED log-delivery statement is compared instead of subtracted on both sides. */
6092
+ function collectLogDeliverySids(v, out = /* @__PURE__ */ new Set()) {
6093
+ if (typeof v === "string") {
6094
+ const p = parsePolicyString(v);
6095
+ if (p) collectLogDeliverySids(p, out);
6096
+ } else if (Array.isArray(v)) for (const el of v) collectLogDeliverySids(el, out);
6097
+ else if (isObj(v)) {
6098
+ if ("Effect" in v && typeof v.Sid === "string" && LOG_DELIVERY_SID_RE.test(v.Sid)) out.add(v.Sid);
6099
+ for (const val of Object.values(v)) collectLogDeliverySids(val, out);
6100
+ }
6101
+ return out;
6001
6102
  }
6002
6103
  function canonicalizePrincipal(v) {
6003
6104
  if (isObj(v)) {
@@ -6014,13 +6115,22 @@ function normalizeAccountPrincipal(v) {
6014
6115
  }
6015
6116
  return v;
6016
6117
  }
6017
- function canonicalizePolicy(doc) {
6018
- const statements = (Array.isArray(doc.Statement) ? doc.Statement : [doc.Statement]).filter((s) => !isAwsManagedLogDeliveryStatement(s));
6118
+ const POLICY_GRAMMAR_KEYS = /* @__PURE__ */ new Set([
6119
+ "Version",
6120
+ "Id",
6121
+ "Statement"
6122
+ ]);
6123
+ const IAM_DEFAULT_POLICY_VERSION = "2008-10-17";
6124
+ function canonicalizePolicy(doc, keepLogDeliverySids) {
6125
+ const statements = (Array.isArray(doc.Statement) ? doc.Statement : [doc.Statement]).filter((s) => !isAwsManagedLogDeliveryStatement(s) || keepLogDeliverySids?.has(s.Sid) === true);
6019
6126
  const out = {
6020
6127
  ...doc,
6021
6128
  Statement: statements.map(canonicalizeStatement).sort(byJson)
6022
6129
  };
6023
- if (doc.Version === void 0) delete out.Version;
6130
+ if (doc.Version === void 0) {
6131
+ if (Object.keys(doc).every((k) => POLICY_GRAMMAR_KEYS.has(k))) out.Version = IAM_DEFAULT_POLICY_VERSION;
6132
+ else delete out.Version;
6133
+ }
6024
6134
  return out;
6025
6135
  }
6026
6136
  const OAI_USER_ARN_RE = /^arn:aws[a-z-]*:iam::cloudfront:user\/CloudFront Origin Access Identity (.+)$/;
@@ -6078,30 +6188,30 @@ function sortDeep(v) {
6078
6188
  * Walk a value, replacing policy-document subtrees with their canonical form and
6079
6189
  * embedded JSON-text strings with a canonical (sorted, minified) form.
6080
6190
  */
6081
- function normalizePoliciesDeep(v) {
6082
- return normWalk(v, false);
6191
+ function normalizePoliciesDeep(v, keepLogDeliverySids) {
6192
+ return normWalk(v, false, keepLogDeliverySids);
6083
6193
  }
6084
- function normWalk(v, freeForm) {
6194
+ function normWalk(v, freeForm, keep) {
6085
6195
  if (typeof v === "string") {
6086
6196
  if (freeForm) return v;
6087
6197
  const p = parsePolicyString(v);
6088
- if (p) return canonicalizePolicy(p);
6198
+ if (p) return canonicalizePolicy(p, keep);
6089
6199
  return canonicalizeJsonText(v);
6090
6200
  }
6091
- if (Array.isArray(v)) return v.map((el) => normWalk(el, freeForm));
6092
- if (!freeForm && isPolicyDoc(v)) return canonicalizePolicy(v);
6201
+ if (Array.isArray(v)) return v.map((el) => normWalk(el, freeForm, keep));
6202
+ if (!freeForm && isPolicyDoc(v)) return canonicalizePolicy(v, keep);
6093
6203
  if (isObj(v)) {
6094
6204
  const out = {};
6095
- for (const [k, val] of Object.entries(v)) out[k] = normWalk(val, freeForm || FREE_FORM_MAP_PARENTS.has(k));
6205
+ for (const [k, val] of Object.entries(v)) out[k] = normWalk(val, freeForm || FREE_FORM_MAP_PARENTS.has(k), keep);
6096
6206
  return out;
6097
6207
  }
6098
6208
  return v;
6099
6209
  }
6100
6210
 
6101
6211
  // src/normalize/pipeline.ts
6102
- function canonicalizeForCompare(v, resourceType) {
6212
+ function canonicalizeForCompare(v, resourceType, keepLogDeliverySids) {
6103
6213
  const orderSig = resourceType ? ORDER_SIGNIFICANT_ARRAY_KEYS[resourceType] : void 0;
6104
- const base = canonicalizeIpv6CidrsDeep(canonicalizeIdArraysDeep(canonicalizeTagListsDeep(normalizePoliciesDeep(v), orderSig)));
6214
+ const base = canonicalizeIpv6CidrsDeep(canonicalizeIdArraysDeep(canonicalizeTagListsDeep(normalizePoliciesDeep(v, keepLogDeliverySids), orderSig)));
6105
6215
  return resourceType === "AWS::WAFv2::WebACL" || resourceType === "AWS::WAFv2::RuleGroup" ? normalizeWafByteMatchDeep(base) : base;
6106
6216
  }
6107
6217
  function sortObjectArraysDeep(v) {
@@ -6994,7 +7104,7 @@ function sortUnorderedSetProps(model, resourceType, schemaObjectArrayKeys = [],
6994
7104
  }
6995
7105
  function normalizeLiveModel(liveRaw, schema, opts = {}) {
6996
7106
  const oaiMap = opts.oaiCanonicalIds ?? {};
6997
- const live = canonicalizeForCompare(rewriteOaiPrincipalsDeep(stripAwsTagsDeep(stripCcApiAwsManagedFields(liveRaw)), oaiMap), opts.resourceType);
7107
+ const live = canonicalizeForCompare(rewriteOaiPrincipalsDeep(stripAwsTagsDeep(stripCcApiAwsManagedFields(liveRaw)), oaiMap), opts.resourceType, opts.keepLogDeliverySids);
6998
7108
  deepStripPaths(live, schema.readOnlyPaths);
6999
7109
  deepStripPaths(live, schema.writeOnlyPaths);
7000
7110
  if (opts.resourceType) sortUnorderedSetProps(live, opts.resourceType, (schema.unorderedObjectArrayPaths ?? []).filter((p) => !p.includes(".")), schema.unorderedScalarPaths ?? []);
@@ -7239,6 +7349,7 @@ function resolveParentObject(root, dottedPath) {
7239
7349
  return node;
7240
7350
  }
7241
7351
  const GETTEMPLATE_MASK_NOTE = "declared value unverifiable — CloudFormation GetTemplate masks non-ASCII characters as \"?\"";
7352
+ const KMS_ALIAS_UNRESOLVED_NOTE = "AWS-managed KMS alias unresolved (kms:ListAliases unavailable) — cannot confirm the live key is the managed key";
7242
7353
  function pushDeclaredFinding(findings, finding) {
7243
7354
  if (!deepEqual(finding.desired, finding.actual) && deepEqualModuloNonAsciiMask(finding.desired, finding.actual)) {
7244
7355
  findings.push({
@@ -7357,11 +7468,13 @@ function classifyResource(resource, liveRaw, schema, opts = {}) {
7357
7468
  const liveForCompare = structuredClone(liveRaw);
7358
7469
  const declaredForCompare = cloneDeepWithSymbols(declaredIn);
7359
7470
  stripAsymmetricIdentityFields(declaredForCompare, liveForCompare);
7471
+ const keepLogDeliverySids = collectLogDeliverySids(declaredForCompare);
7360
7472
  const live = subtractPropagatedStackTags(normalizeLiveModel(liveForCompare, schema, {
7361
7473
  oaiCanonicalIds: oaiMap,
7362
- resourceType
7474
+ resourceType,
7475
+ keepLogDeliverySids
7363
7476
  }), opts.stackTags ?? {}, declaredTagKeys(declaredForCompare));
7364
- let declared = canonicalizeForCompare(rewriteOaiPrincipalsDeep(declaredForCompare, oaiMap), resourceType);
7477
+ let declared = canonicalizeForCompare(rewriteOaiPrincipalsDeep(declaredForCompare, oaiMap), resourceType, keepLogDeliverySids);
7365
7478
  if (resourceType === "AWS::GuardDuty::Filter") declared = canonicalizeGuardDutyCriterionKeys(declared);
7366
7479
  const reflected = REFLECTED_CHILD_PROPS[resourceType];
7367
7480
  if (reflected && !(reflected in declared)) delete live[reflected];
@@ -7720,7 +7833,7 @@ function classifyResource(resource, liveRaw, schema, opts = {}) {
7720
7833
  }
7721
7834
  if (physicalId && opts.accountId !== void 0 && declared["Policy"] && declared["Policy"] !== UNRESOLVED && !hasUnresolved(declared["Policy"])) {
7722
7835
  const arnPrefix = `arn:${opts.region !== void 0 ? partitionForRegion(opts.region).partition : "aws"}:execute-api:${opts.region ?? ""}:${opts.accountId}:${physicalId}`;
7723
- declared["Policy"] = canonicalizePolicy(expandExecuteApiResources(declared["Policy"], arnPrefix));
7836
+ declared["Policy"] = canonicalizePolicy(expandExecuteApiResources(declared["Policy"], arnPrefix), keepLogDeliverySids);
7724
7837
  }
7725
7838
  }
7726
7839
  if (resourceType === "AWS::Cognito::UserPool") {
@@ -8156,7 +8269,19 @@ function classifyResource(resource, liveRaw, schema, opts = {}) {
8156
8269
  }
8157
8270
  }
8158
8271
  if (isArnNameMatch(d.stateValue, d.awsValue, opts)) continue;
8159
- if (isManagedKmsAliasMatch(d.stateValue, d.awsValue, opts.kmsAliasTargets)) continue;
8272
+ const kmsVerdict = managedKmsAliasVerdict(d.stateValue, d.awsValue, opts.kmsAliasTargets);
8273
+ if (kmsVerdict === "match") continue;
8274
+ if (kmsVerdict === "unresolved") {
8275
+ findings.push({
8276
+ tier: "readGap",
8277
+ logicalId,
8278
+ resourceType,
8279
+ path: d.path,
8280
+ note: KMS_ALIAS_UNRESOLVED_NOTE,
8281
+ compareOnly: true
8282
+ });
8283
+ continue;
8284
+ }
8160
8285
  if (isLogGroupArnWildcardMatch(d.stateValue, d.awsValue)) continue;
8161
8286
  if (isStringlyEqualScalar(d.stateValue, d.awsValue)) continue;
8162
8287
  if (isStringlyEqualScalarArray(d.stateValue, d.awsValue)) continue;
@@ -12383,24 +12508,6 @@ async function enumerateElasticBeanstalkApplicationChildren(ctx) {
12383
12508
  });
12384
12509
  }
12385
12510
 
12386
- // src/read/pem.ts
12387
- function hashCaBundle(pem) {
12388
- if (typeof pem !== "string") return void 0;
12389
- const bodies = [];
12390
- const re = /-----BEGIN CERTIFICATE-----([\s\S]*?)-----END CERTIFICATE-----/g;
12391
- for (let m = re.exec(pem); m !== null; m = re.exec(pem)) {
12392
- const body = (m[1] ?? "").replace(/\s+/g, "");
12393
- if (body.length > 0) bodies.push(body);
12394
- }
12395
- if (bodies.length === 0) return void 0;
12396
- bodies.sort();
12397
- return createHash("sha256").update(bodies.join("\n")).digest("hex");
12398
- }
12399
- function sha256Hex(bytes) {
12400
- if (bytes === void 0 || bytes.length === 0) return void 0;
12401
- return createHash("sha256").update(bytes).digest("hex");
12402
- }
12403
-
12404
12511
  // src/read/overrides.ts
12405
12512
  const OVERRIDE_READ_GAP = Symbol.for("cdkrd.overrideReadGap");
12406
12513
  function overrideReadGap(model, readGapPaths) {
@@ -17133,7 +17240,7 @@ function computeCompleteResources(allLogicalIds, findings, recorded, previousCom
17133
17240
  const blocked = /* @__PURE__ */ new Set();
17134
17241
  const blockedByIgnore = /* @__PURE__ */ new Set();
17135
17242
  for (const f of findings) {
17136
- if (f.tier === "skipped" || f.tier === "deleted" || f.tier === "readGap" && !f.writeOnly) blocked.add(f.logicalId);
17243
+ if (f.tier === "skipped" || f.tier === "deleted" || f.tier === "readGap" && !f.writeOnly && !f.compareOnly) blocked.add(f.logicalId);
17137
17244
  if (f.tier === "undeclared" && !recordedKeys.has(recordedKey(f))) blocked.add(f.logicalId);
17138
17245
  if (f.tier === "ignored" && f.ignoredFrom === "undeclared" && !recordedKeys.has(recordedKey(f))) blockedByIgnore.add(f.logicalId);
17139
17246
  }
@@ -17310,6 +17417,28 @@ function declaredSourceFingerprint(resourceType, path, declared) {
17310
17417
  return node === void 0 ? void 0 : stableValueHash(node);
17311
17418
  }
17312
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
+ /**
17313
17442
  * Build the `recordedSourceFingerprints` map for the entries being written. For each entry
17314
17443
  * with a source mapping: prefer the PREVIOUS baseline's fingerprint when the entry's VALUE
17315
17444
  * was carried forward unchanged from it (a resource unread this run — e.g. skipped — must
@@ -17695,14 +17824,9 @@ function applyBaseline(findings, baseline, opts = {}) {
17695
17824
  const liveId = opts.physicalIdByLogical?.get(logicalId);
17696
17825
  if (liveId !== void 0 && liveId !== recordedId) replacedLogical.add(logicalId);
17697
17826
  }
17698
- const sourceRedeployedVoid = /* @__PURE__ */ new Set();
17699
- const recordedSourceFps = baseline.recordedSourceFingerprints ?? {};
17700
- for (const e of recorded) {
17701
- const storedFp = recordedSourceFps[recordedKey(e)];
17702
- if (storedFp === void 0) continue;
17703
- const currentFp = declaredSourceFingerprint(e.resourceType, e.path, opts.declaredByLogical?.get(e.logicalId));
17704
- if (currentFp !== void 0 && currentFp !== storedFp) sourceRedeployedVoid.add(recordedKey(e));
17705
- }
17827
+ const sourceRedeployedVoid = sourceRedeployedKeys(baseline, opts.declaredByLogical);
17828
+ const sourceSwapped = /* @__PURE__ */ new Set();
17829
+ const sourceVerified = /* @__PURE__ */ new Set();
17706
17830
  const liveTypeByLogical = /* @__PURE__ */ new Map();
17707
17831
  for (const f of findings) if (f.resourceType) liveTypeByLogical.set(f.logicalId, f.resourceType);
17708
17832
  const isTypeVoid = (e) => {
@@ -17710,7 +17834,13 @@ function applyBaseline(findings, baseline, opts = {}) {
17710
17834
  return liveType !== void 0 && liveType !== e.resourceType;
17711
17835
  };
17712
17836
  const entryMatches = (a, f) => a.logicalId === f.logicalId && a.path === f.path && a.resourceType === f.resourceType;
17713
- 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
+ }
17714
17844
  if (f.tier === "added") {
17715
17845
  const entry = recorded.find((a) => entryMatches(a, f));
17716
17846
  if (f.modelReadFailed) {
@@ -17749,6 +17879,21 @@ function applyBaseline(findings, baseline, opts = {}) {
17749
17879
  }
17750
17880
  const matched = replacedLogical.has(f.logicalId) ? void 0 : recorded.find((a) => entryMatches(a, f));
17751
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
+ }
17752
17897
  if (sourceRedeployVoided && f.tier === "undeclared") continue;
17753
17898
  const entry = sourceRedeployVoided ? void 0 : matched;
17754
17899
  if (entry && baselineValueMatches(entry.value, f.actual, f.resourceType, f.path)) continue;
@@ -17795,6 +17940,7 @@ function applyBaseline(findings, baseline, opts = {}) {
17795
17940
  const adoptedStale = [];
17796
17941
  const nameStrippedStale = [];
17797
17942
  const sourceRedeployedStale = [];
17943
+ const sourceUnverified = [];
17798
17944
  for (const a of recorded) {
17799
17945
  if (a.path === "") {
17800
17946
  if (presentAddedLogical.has(a.logicalId)) continue;
@@ -17823,7 +17969,9 @@ function applyBaseline(findings, baseline, opts = {}) {
17823
17969
  continue;
17824
17970
  }
17825
17971
  if (sourceRedeployedVoid.has(recordedKey(a))) {
17972
+ if (sourceSwapped.has(recordedKey(a))) continue;
17826
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}`);
17827
17975
  continue;
17828
17976
  }
17829
17977
  if (currentPaths.has(`${a.logicalId}.${a.path}`)) continue;
@@ -17886,6 +18034,7 @@ function applyBaseline(findings, baseline, opts = {}) {
17886
18034
  if (adoptedStale.length > 0) opts.warn?.(formatAdoptedStaleNote(adoptedStale));
17887
18035
  if (nameStrippedStale.length > 0) opts.warn?.(formatNameStrippedStaleNote(nameStrippedStale));
17888
18036
  if (sourceRedeployedStale.length > 0) opts.warn?.(formatSourceRedeployedStaleNote(sourceRedeployedStale));
18037
+ if (sourceUnverified.length > 0) opts.warn?.(formatSourceUnverifiedNote(sourceUnverified));
17889
18038
  return kept;
17890
18039
  }
17891
18040
  /**
@@ -17900,6 +18049,15 @@ function formatSourceRedeployedStaleNote(paths) {
17900
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.`;
17901
18050
  }
17902
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
+ /**
17903
18061
  * The folded one-line note for baseline entries now declared in the template (R134). One
17904
18062
  * line with a count instead of one line per entry; `record` re-snapshots to clear them.
17905
18063
  * Pure + exported for unit tests.
@@ -17999,6 +18157,108 @@ function warnTemplateHashDrift(baseline, rawTemplate, stackName, warn = console.
17999
18157
  if (baseline.templateHash !== hashTemplate(rawTemplate)) warn(`note: ${stackName}: baseline was captured against a different template version — consider re-running \`cdkrd record\`.`);
18000
18158
  }
18001
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
+
18002
18262
  // src/diff/hints.ts
18003
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";
18004
18264
  const INSIGHTS_LAYER = /:layer:LambdaInsightsExtension(-Arm64)?:/;
@@ -18510,7 +18770,7 @@ async function desiredModel(type, ctx, ops) {
18510
18770
  const current = (reader && await reader(ctx)) ?? {};
18511
18771
  const aligned = current.PolicyDocument === void 0 ? current : {
18512
18772
  ...current,
18513
- PolicyDocument: canonicalizeForCompare(current.PolicyDocument)
18773
+ PolicyDocument: canonicalizeForCompare(current.PolicyDocument, void 0, collectLogDeliverySids(ctx.declared))
18514
18774
  };
18515
18775
  assertIndexedPriorsFresh(type, aligned, ops);
18516
18776
  return applyOps(aligned, ops);
@@ -22057,11 +22317,15 @@ function changedRecordLabel(entry, recordedValue, sourceRedeployed = false) {
22057
22317
  * change out of band (the IaC deploy moved the live hash with the template), so record must
22058
22318
  * label and summarize it as a legit refresh, not "CHANGED out of band". Fail-safe: false when
22059
22319
  * no source fingerprint was stored (an old baseline, or a path with no source mapping) or the
22060
- * 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.
22061
22323
  */
22062
- function isRecordedSourceRedeployed(entry, existing, declaredByLogical) {
22324
+ function isRecordedSourceRedeployed(entry, existing, declaredByLogical, findings = []) {
22063
22325
  const storedFp = existing?.recordedSourceFingerprints?.[recordedKey(entry)];
22064
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;
22065
22329
  const currentFp = declaredSourceFingerprint(entry.resourceType, entry.path, declaredByLogical.get(entry.logicalId));
22066
22330
  return currentFp !== void 0 && currentFp !== storedFp;
22067
22331
  }
@@ -22209,8 +22473,9 @@ function realOpCount(plan) {
22209
22473
  * interactive prompt — neither re-gathers.)
22210
22474
  */
22211
22475
  async function recordStack(p) {
22212
- const { stackName, region, desired, findings, yes, interactive, preselectedKeys, expandNested } = p;
22476
+ const { stackName, region, desired, yes, interactive, preselectedKeys, expandNested } = p;
22213
22477
  const existing = await loadBaseline(stackName, desired.accountId, region);
22478
+ const findings = await annotateDeployedSourceHashes(p.findings, existing, desired.resources, region, { localAssets: p.localAssets });
22214
22479
  if (existing) checkBaselineAccount(existing, desired.accountId, stackName);
22215
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.`);
22216
22481
  let recorded = carryForwardIgnored(carryForwardUnreadable(buildRecorded(findings), existing, findings), existing, findings);
@@ -22223,7 +22488,7 @@ async function recordStack(p) {
22223
22488
  const declaredModel = declaredKeysByLogical(desired.resources);
22224
22489
  const { changed } = splitRecordedByBaseline(recorded, existing);
22225
22490
  const changedExisting = changed.filter((e) => recordedValueForChanged(e, existing).hasRecorded);
22226
- const redeployedViaCfn = changedExisting.filter((e) => isRecordedSourceRedeployed(e, existing, declaredModel));
22491
+ const redeployedViaCfn = changedExisting.filter((e) => isRecordedSourceRedeployed(e, existing, declaredModel, findings));
22227
22492
  const redeployedKeys = new Set(redeployedViaCfn.map((e) => recordedKey(e)));
22228
22493
  const changedOob = changedExisting.filter((e) => !redeployedKeys.has(recordedKey(e)));
22229
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(", "));
@@ -22266,7 +22531,7 @@ async function recordStack(p) {
22266
22531
  const declaredModel = declaredKeysByLogical(desired.resources);
22267
22532
  const fromPrompt = await bulkMultiselect(recordSelectMessage(stackName, region, folded.length), standout.map((e) => {
22268
22533
  const rec = recordedValueForChanged(e, existing);
22269
- const redeployed = isRecordedSourceRedeployed(e, existing, declaredModel);
22534
+ const redeployed = isRecordedSourceRedeployed(e, existing, declaredModel, findings);
22270
22535
  return {
22271
22536
  value: recordedKey(e),
22272
22537
  label: changedRecordLabel(e, rec, redeployed),
@@ -22786,10 +23051,11 @@ async function revertStack(p) {
22786
23051
  region
22787
23052
  }, config);
22788
23053
  const readdFailedDeletes = (findings) => failedDeleteIds.size === 0 ? findings : [...findings, ...gathered.findings.filter((f) => failedDeleteIds.has(f.logicalId))];
22789
- 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()));
22790
23056
  if (driftCount(post.filter((f) => touched.has(f.logicalId))) > 0) {
22791
23057
  await sleep(p.convergeRetryDelayMs ?? CONVERGE_RETRY_DELAY_MS);
22792
- post = readdFailedDeletes(reconcile(await regatherTouched(gathered, touched, region)));
23058
+ post = readdFailedDeletes(reconcile(await regather()));
22793
23059
  }
22794
23060
  const remainingDrift = post.filter(isDrift);
22795
23061
  const remaining = remainingDrift.length;
@@ -22893,7 +23159,7 @@ async function runRecord(args) {
22893
23159
  let wroteAny = false;
22894
23160
  const showProgress = !a.json && isInteractive();
22895
23161
  const accountGate = createAccountGate("record");
22896
- for (const [idx, { stackName, region, account, template }] of stacks.entries()) {
23162
+ for (const [idx, { stackName, region, account, template, localAssetHashes }] of stacks.entries()) {
22897
23163
  if (!region) {
22898
23164
  const msg = "no region — set env on the stack, pass --region, or set a region for the AWS profile";
22899
23165
  console.error(`error: ${stackName}: ${msg}`);
@@ -22932,6 +23198,7 @@ async function runRecord(args) {
22932
23198
  }
22933
23199
  warnStackStatus(stackName, desired.stackStatusWarning);
22934
23200
  const result = await recordStack({
23201
+ localAssets: localAssetHashes,
22935
23202
  stackName,
22936
23203
  region,
22937
23204
  desired,
@@ -23033,7 +23300,7 @@ async function runIgnore(args) {
23033
23300
  let wroteAny = false;
23034
23301
  const showProgress = !a.json && isInteractive();
23035
23302
  const accountGate = createAccountGate("ignore");
23036
- for (const [idx, { stackName, region, account, template }] of stacks.entries()) {
23303
+ for (const [idx, { stackName, region, account, template, localAssetHashes }] of stacks.entries()) {
23037
23304
  if (!region) {
23038
23305
  const msg = "no region — set env on the stack, pass --region, or set a region for the AWS profile";
23039
23306
  console.error(`error: ${stackName}: ${msg}`);
@@ -23073,7 +23340,8 @@ async function runIgnore(args) {
23073
23340
  warnStackStatus(stackName, desired.stackStatusWarning);
23074
23341
  const baseline = await loadBaseline(stackName, desired.accountId, region);
23075
23342
  if (baseline) checkBaselineAccount(baseline, desired.accountId, stackName);
23076
- 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)), {
23077
23345
  stackName,
23078
23346
  accountId: desired.accountId,
23079
23347
  region
@@ -23490,6 +23758,7 @@ async function resolveInteractively(p) {
23490
23758
  }
23491
23759
  async function recordAll(p) {
23492
23760
  if (!(await recordStack({
23761
+ localAssets: p.localAssets,
23493
23762
  stackName: p.stackName,
23494
23763
  region: p.region,
23495
23764
  desired: p.desired,
@@ -23536,6 +23805,7 @@ async function ignoreAll(p) {
23536
23805
  }
23537
23806
  async function revertAll(p) {
23538
23807
  const outcome = await revertStack({
23808
+ localAssets: p.localAssets,
23539
23809
  stackName: p.stackName,
23540
23810
  region: p.region,
23541
23811
  gathered: {
@@ -23585,6 +23855,7 @@ async function perFinding(p, decidable) {
23585
23855
  const preselectedKeys = new Set(buildRecorded(groups.record).map(recordedKey));
23586
23856
  const recordConfig = groups.ignore.length > 0 ? await loadConfig() : p.config;
23587
23857
  await recordStack({
23858
+ localAssets: p.localAssets,
23588
23859
  stackName: p.stackName,
23589
23860
  region: p.region,
23590
23861
  desired: p.desired,
@@ -23604,6 +23875,7 @@ async function perFinding(p, decidable) {
23604
23875
  if (groups.revert.length > 0) {
23605
23876
  const revertKeys = new Set(groups.revert.map(keyOf));
23606
23877
  const outcome = await revertStack({
23878
+ localAssets: p.localAssets,
23607
23879
  stackName: p.stackName,
23608
23880
  region: p.region,
23609
23881
  gathered: {
@@ -23868,7 +24140,7 @@ async function runCheck(args) {
23868
24140
  }
23869
24141
  return callerAccount;
23870
24142
  };
23871
- for (const [idx, { stackName, region, account, template }] of stacks.entries()) {
24143
+ for (const [idx, { stackName, region, account, template, localAssetHashes }] of stacks.entries()) {
23872
24144
  if (!region) {
23873
24145
  const msg = "no region — set env on the stack, pass --region, or set a region for the AWS profile";
23874
24146
  console.error(`error: ${stackName}: ${msg}`);
@@ -23949,6 +24221,7 @@ async function runCheck(args) {
23949
24221
  if (baseline) checkBaselineAccount(baseline, desired.accountId, stackName);
23950
24222
  if (baseline) warnTemplateHashDrift(baseline, desired.rawTemplate, stackName);
23951
24223
  if (baseline) warnBaselineSchemaV1(baseline, stackName);
24224
+ if (!a.declaredOnly) findings = await annotateDeployedSourceHashes(findings, baseline, desired.resources, region, { localAssets: localAssetHashes });
23952
24225
  const reconciled = applyIgnores(reconcileBaseline(findings, baseline, {
23953
24226
  declaredOnly: a.declaredOnly,
23954
24227
  applyOpts: {
@@ -23982,6 +24255,7 @@ async function runCheck(args) {
23982
24255
  hasBaseline: baseline !== void 0,
23983
24256
  interactive: isInteractive()
23984
24257
  })) code = await resolveInteractively({
24258
+ localAssets: localAssetHashes,
23985
24259
  stackName,
23986
24260
  region,
23987
24261
  desired,
@@ -24064,7 +24338,7 @@ async function runRevert(args) {
24064
24338
  let worst = 0;
24065
24339
  const showProgress = !a.json && isInteractive();
24066
24340
  const accountGate = createAccountGate("revert");
24067
- for (const [idx, { stackName, region, account, template }] of stacks.entries()) {
24341
+ for (const [idx, { stackName, region, account, template, localAssetHashes }] of stacks.entries()) {
24068
24342
  if (!region) {
24069
24343
  const msg = "no region — set env on the stack, pass --region, or set a region for the AWS profile";
24070
24344
  console.error(`error: ${stackName}: ${msg}`);
@@ -24094,7 +24368,7 @@ async function runRevert(args) {
24094
24368
  worst = Math.max(worst, 2);
24095
24369
  continue;
24096
24370
  }
24097
- 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));
24098
24372
  const readMismatch = accountGate.postRead(account, gathered.desired.accountId);
24099
24373
  if (readMismatch.skip) {
24100
24374
  console.error(`error: ${stackName}: ${readMismatch.message}`);
@@ -24111,8 +24385,13 @@ async function runRevert(args) {
24111
24385
  }
24112
24386
  const baseline = await loadBaseline(stackName, gathered.desired.accountId, region);
24113
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
+ };
24114
24392
  warnStackStatus(stackName, gathered.desired.stackStatusWarning);
24115
24393
  const outcome = await revertStack({
24394
+ localAssets: localAssetHashes,
24116
24395
  stackName,
24117
24396
  region,
24118
24397
  gathered,