cdk-real-drift 0.2.26 → 0.2.28

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
@@ -663,7 +663,13 @@ place, since Cloud Control has no handler for the type),
663
663
  `config:DescribeConfigRules` / `config:PutConfigRule`,
664
664
  `ecs:UpdateService` (reverts an `AWS::ECS::Service` `ServiceConnectConfiguration` /
665
665
  `VolumeConfigurations` drift — the whole writeOnly prop is re-supplied, since Cloud
666
- Control cannot sub-path patch it).
666
+ Control cannot sub-path patch it),
667
+ `apigateway:UpdateStage` (reverts an `AWS::ApiGatewayV2::Stage` — an `autoDeploy`
668
+ stage rejects the `DeploymentId` the Cloud Control handler injects, so only the
669
+ drifted stage properties are written directly, never `DeploymentId`),
670
+ `apigateway:UpdateRestApi` (reverts an `AWS::ApiGateway::RestApi` `Policy` — the
671
+ whole desired resource policy is re-serialized and replaced, since Cloud Control
672
+ holds the policy as a JSON string it cannot sub-path patch).
667
673
 
668
674
  </details>
669
675
 
package/dist/cli.js CHANGED
@@ -7,10 +7,10 @@ import { CloudControlClient, DeleteResourceCommand, GetResourceCommand, GetResou
7
7
  import { BaseCredentials, CdkAppMultiContext, NonInteractiveIoHost, Toolkit } from "@aws-cdk/toolkit-lib";
8
8
  import { CloudFormationClient, DescribeStacksCommand, DescribeTypeCommand, GetTemplateCommand, ListExportsCommand, ListStackResourcesCommand } from "@aws-sdk/client-cloudformation";
9
9
  import { KMSClient, ListAliasesCommand } from "@aws-sdk/client-kms";
10
- import { APIGatewayClient, GetAuthorizersCommand, GetGatewayResponsesCommand, GetModelsCommand, GetRequestValidatorsCommand, GetResourcesCommand, UpdateIntegrationCommand, UpdateIntegrationResponseCommand, UpdateMethodResponseCommand } from "@aws-sdk/client-api-gateway";
10
+ import { APIGatewayClient, GetAuthorizersCommand, GetGatewayResponsesCommand, GetModelsCommand, GetRequestValidatorsCommand, GetResourcesCommand, UpdateIntegrationCommand, UpdateIntegrationResponseCommand, UpdateMethodResponseCommand, UpdateRestApiCommand } from "@aws-sdk/client-api-gateway";
11
11
  import { AppConfigClient, ListConfigurationProfilesCommand, ListEnvironmentsCommand } from "@aws-sdk/client-appconfig";
12
12
  import { AppSyncClient, ListApiKeysCommand, ListDataSourcesCommand, ListFunctionsCommand, ListResolversCommand, ListTypesCommand } from "@aws-sdk/client-appsync";
13
- import { ApiGatewayV2Client, GetAuthorizersCommand as GetAuthorizersCommand$1, GetIntegrationsCommand, GetRoutesCommand, GetStagesCommand } from "@aws-sdk/client-apigatewayv2";
13
+ import { ApiGatewayV2Client, GetAuthorizersCommand as GetAuthorizersCommand$1, GetIntegrationsCommand, GetRoutesCommand, GetStagesCommand, UpdateStageCommand } from "@aws-sdk/client-apigatewayv2";
14
14
  import { CloudWatchLogsClient, DescribeMetricFiltersCommand, DescribeSubscriptionFiltersCommand, PutBearerTokenAuthenticationCommand, PutMetricFilterCommand } from "@aws-sdk/client-cloudwatch-logs";
15
15
  import { CognitoIdentityProviderClient, ListGroupsCommand, ListResourceServersCommand, ListUserPoolClientsCommand } from "@aws-sdk/client-cognito-identity-provider";
16
16
  import { DescribeAddressesCommand, DescribeClientVpnAuthorizationRulesCommand, DescribeClientVpnEndpointsCommand, DescribeClientVpnTargetNetworksCommand, DescribeLaunchTemplateVersionsCommand, DescribeNetworkAclsCommand, DescribeRouteTablesCommand, DescribeSubnetsCommand, EC2Client, ModifyClientVpnEndpointCommand } from "@aws-sdk/client-ec2";
@@ -8507,13 +8507,22 @@ async function loadBaseline(stackName, accountId, region) {
8507
8507
  function sortRecorded(recorded) {
8508
8508
  return [...recorded].sort((a, b) => (a.logicalId < b.logicalId ? -1 : a.logicalId > b.logicalId ? 1 : 0) || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
8509
8509
  }
8510
+ /** #674: keep only physical ids for logicalIds that still carry a recorded entry, with
8511
+ * sorted keys, so the baseline JSON is byte-stable and free of dead entries. */
8512
+ function sortedPhysicalIds(ids, recorded) {
8513
+ const live = new Set(recorded.map((e) => e.logicalId));
8514
+ const out = {};
8515
+ for (const key of Object.keys(ids).sort()) if (live.has(key) && ids[key] !== void 0) out[key] = ids[key];
8516
+ return out;
8517
+ }
8510
8518
  async function writeBaselineFile(b) {
8511
8519
  const p = baselinePath(b.stackName, b.accountId, b.region);
8512
8520
  await mkdir(dirname(p), { recursive: true });
8513
8521
  const stable = {
8514
8522
  ...b,
8515
8523
  recorded: sortRecorded(b.recorded),
8516
- ...b.completeResources ? { completeResources: [...b.completeResources].sort() } : {}
8524
+ ...b.completeResources ? { completeResources: [...b.completeResources].sort() } : {},
8525
+ ...b.recordedPhysicalIds ? { recordedPhysicalIds: sortedPhysicalIds(b.recordedPhysicalIds, b.recorded) } : {}
8517
8526
  };
8518
8527
  await writeFile(p, JSON.stringify(stable, null, 2) + "\n", "utf8");
8519
8528
  return p;
@@ -8559,12 +8568,30 @@ async function writeBaseline(stackName, region, accountId, findings, rawTemplate
8559
8568
  capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
8560
8569
  templateHash: hashTemplate(rawTemplate),
8561
8570
  recorded,
8562
- completeResources: computeCompleteResources(allIds, findings, recorded, opts.previous?.completeResources ?? [])
8571
+ completeResources: computeCompleteResources(allIds, findings, recorded, opts.previous?.completeResources ?? []),
8572
+ ...buildRecordedPhysicalIds(recorded, opts.physicalIdByLogical, opts.previous)
8563
8573
  }),
8564
8574
  count: recorded.length
8565
8575
  };
8566
8576
  }
8567
8577
  /**
8578
+ * #674: build the `recordedPhysicalIds` map (logicalId -> physical id) for the entries
8579
+ * being written. Prefers the physical id resolved THIS run; falls back to the previous
8580
+ * baseline's stored id when this run did not resolve one (a resource skipped / with no
8581
+ * physical id must not lose its previously-captured id on re-record — else a later
8582
+ * replacement could not be detected). Returns `{}` (spread to nothing) when no id is
8583
+ * known, so the field stays absent on baselines with no physical ids at all.
8584
+ */
8585
+ function buildRecordedPhysicalIds(recorded, live, previous) {
8586
+ const prior = previous?.recordedPhysicalIds ?? {};
8587
+ const out = {};
8588
+ for (const e of recorded) {
8589
+ const id = live?.get(e.logicalId) ?? prior[e.logicalId];
8590
+ if (id !== void 0) out[e.logicalId] = id;
8591
+ }
8592
+ return Object.keys(out).length > 0 ? { recordedPhysicalIds: out } : {};
8593
+ }
8594
+ /**
8568
8595
  * Per-account guard (secondary defense). The baseline filename now embeds the
8569
8596
  * accountId, so a correctly-named file always matches; this guard catches a file
8570
8597
  * that was hand-copied or renamed to the wrong account's path (its `accountId`
@@ -8756,6 +8783,13 @@ function applyBaseline(findings, baseline, opts = {}) {
8756
8783
  const recorded = baseline.recorded;
8757
8784
  const complete = new Set(baseline.completeResources ?? []);
8758
8785
  const kept = [];
8786
+ const currentLogicalIds = opts.allLogicalIds === void 0 ? void 0 : Array.isArray(opts.allLogicalIds) ? new Set(opts.allLogicalIds) : opts.allLogicalIds;
8787
+ const recordedPhysIds = baseline.recordedPhysicalIds ?? {};
8788
+ const replacedLogical = /* @__PURE__ */ new Set();
8789
+ for (const [logicalId, recordedId] of Object.entries(recordedPhysIds)) {
8790
+ const liveId = opts.physicalIdByLogical?.get(logicalId);
8791
+ if (liveId !== void 0 && liveId !== recordedId) replacedLogical.add(logicalId);
8792
+ }
8759
8793
  for (const f of findings) {
8760
8794
  if (f.tier === "added") {
8761
8795
  const entry = recorded.find((a) => a.logicalId === f.logicalId && a.path === f.path);
@@ -8786,7 +8820,7 @@ function applyBaseline(findings, baseline, opts = {}) {
8786
8820
  kept.push(f);
8787
8821
  continue;
8788
8822
  }
8789
- const entry = recorded.find((a) => a.logicalId === f.logicalId && a.path === f.path);
8823
+ const entry = replacedLogical.has(f.logicalId) ? void 0 : recorded.find((a) => a.logicalId === f.logicalId && a.path === f.path);
8790
8824
  if (entry && baselineValueMatches(entry.value, f.actual)) continue;
8791
8825
  if (entry) {
8792
8826
  const delta = identityArrayDelta(canonicalizeForCompare(entry.value), f.actual);
@@ -8801,7 +8835,7 @@ function applyBaseline(findings, baseline, opts = {}) {
8801
8835
  kept.push(f);
8802
8836
  continue;
8803
8837
  }
8804
- if (complete.has(f.logicalId)) kept.push({
8838
+ if (complete.has(f.logicalId) && !replacedLogical.has(f.logicalId)) kept.push({
8805
8839
  ...f,
8806
8840
  note: f.note ? `${f.note}; appeared since record` : "appeared since record"
8807
8841
  });
@@ -8822,12 +8856,22 @@ function applyBaseline(findings, baseline, opts = {}) {
8822
8856
  }
8823
8857
  const underDeclaredDrift = (logicalId, path) => (declaredDriftByLogical.get(logicalId) ?? []).some((p) => path === p || path.startsWith(`${p}.`) || path.startsWith(`${p}[`));
8824
8858
  const promotedStale = [];
8859
+ const removedFromTemplate = [];
8860
+ const replacedStale = [];
8825
8861
  for (const a of recorded) {
8826
8862
  if (a.path === "") continue;
8863
+ if (replacedLogical.has(a.logicalId)) {
8864
+ replacedStale.push(`${a.logicalId}.${a.path}`);
8865
+ continue;
8866
+ }
8827
8867
  if (currentPaths.has(`${a.logicalId}.${a.path}`)) continue;
8828
8868
  if (skippedLogical.has(a.logicalId)) continue;
8829
8869
  if (deletedLogical.has(a.logicalId)) continue;
8830
8870
  if (underDeclaredDrift(a.logicalId, a.path)) continue;
8871
+ if (currentLogicalIds !== void 0 && !currentLogicalIds.has(a.logicalId)) {
8872
+ removedFromTemplate.push(`${a.logicalId}.${a.path}`);
8873
+ continue;
8874
+ }
8831
8875
  if (opts.declaredByLogical?.get(a.logicalId)?.has(topSegment(a.path))) {
8832
8876
  promotedStale.push(`${a.logicalId}.${a.path}`);
8833
8877
  continue;
@@ -8845,6 +8889,8 @@ function applyBaseline(findings, baseline, opts = {}) {
8845
8889
  });
8846
8890
  }
8847
8891
  if (promotedStale.length > 0) opts.warn?.(formatPromotedStaleNote(promotedStale));
8892
+ if (removedFromTemplate.length > 0) opts.warn?.(formatRemovedFromTemplateNote(removedFromTemplate));
8893
+ if (replacedStale.length > 0) opts.warn?.(formatReplacedStaleNote(replacedStale));
8848
8894
  return kept;
8849
8895
  }
8850
8896
  /**
@@ -8856,6 +8902,24 @@ function formatPromotedStaleNote(paths) {
8856
8902
  const n = paths.length;
8857
8903
  return `note: ${n === 1 ? `baseline entry (${paths[0]}) is` : `${n} baseline entries are`} now declared in the template — re-run \`cdkrd record\` to clean ${n === 1 ? "it" : "them"} up.`;
8858
8904
  }
8905
+ /**
8906
+ * #675: the folded one-line note for baseline entries whose resource is no longer in
8907
+ * the template at all (legitimately removed from IaC and deleted by the deploy). Mirror
8908
+ * of formatPromotedStaleNote. Pure + exported for unit tests.
8909
+ */
8910
+ function formatRemovedFromTemplateNote(paths) {
8911
+ const n = paths.length;
8912
+ return `note: ${n === 1 ? `baseline entry (${paths[0]}) belongs` : `${n} baseline entries belong`} to resources no longer in the template — re-run \`cdkrd record\` to clean them up.`;
8913
+ }
8914
+ /**
8915
+ * #674: the folded one-line note for baseline entries recorded against a resource that a
8916
+ * deploy has since REPLACED (new physical id). Mirror of formatPromotedStaleNote. Pure +
8917
+ * exported for unit tests.
8918
+ */
8919
+ function formatReplacedStaleNote(paths) {
8920
+ const n = paths.length;
8921
+ return `note: ${n === 1 ? `baseline entry (${paths[0]}) was` : `${n} baseline entries were`} recorded against a resource since REPLACED by a deploy — re-run \`cdkrd record\`.`;
8922
+ }
8859
8923
  /** logicalId -> set of declared top-level keys, for applyBaseline's promotion check. */
8860
8924
  function declaredKeysByLogical(resources) {
8861
8925
  return new Map(resources.map((r) => [r.logicalId, new Set(Object.keys(r.declared))]));
@@ -10337,7 +10401,49 @@ const writeKinesisVideoStreamStorage = async (ctx, ops) => {
10337
10401
  StreamStorageConfiguration: { DefaultStorageTier: target }
10338
10402
  }));
10339
10403
  };
10404
+ const APIGWV2_STAGE_UPDATE_FIELDS = new Set([
10405
+ "DefaultRouteSettings",
10406
+ "RouteSettings",
10407
+ "AccessLogSettings",
10408
+ "Description",
10409
+ "StageVariables",
10410
+ "ClientCertificateId",
10411
+ "AutoDeploy"
10412
+ ]);
10413
+ const writeApiGatewayV2Stage = async (ctx, ops) => {
10414
+ const [apiIdFromComposite, stageFromComposite] = (ctx.identifier ?? "").split("|");
10415
+ const apiId = str(apiIdFromComposite) ?? str(ctx.declared["ApiId"]);
10416
+ const stageName = str(stageFromComposite) ?? str(ctx.physicalId) ?? str(ctx.declared["StageName"]);
10417
+ if (!apiId || !stageName) throw new Error("cannot resolve ApiId|StageName for ApiGatewayV2 Stage revert");
10418
+ const desired = applyOps({ ...ctx.declared }, ops);
10419
+ const touched = new Set(ops.map((o) => o.path.replace(/^\//, "").split("/")[0]).filter((p) => !!p));
10420
+ const input = {
10421
+ ApiId: apiId,
10422
+ StageName: stageName
10423
+ };
10424
+ for (const p of touched) {
10425
+ if (!APIGWV2_STAGE_UPDATE_FIELDS.has(p)) continue;
10426
+ input[p] = desired[p];
10427
+ }
10428
+ if (Object.keys(input).length <= 2) return;
10429
+ await new ApiGatewayV2Client({ region: ctx.region }).send(new UpdateStageCommand(input));
10430
+ };
10431
+ const writeApiGatewayRestApiPolicy = async (ctx) => {
10432
+ const restApiId = str(ctx.physicalId) ?? str(ctx.declared["RestApiId"]);
10433
+ if (!restApiId) throw new Error("cannot resolve RestApiId for RestApi Policy revert");
10434
+ const declaredPolicy = ctx.declared["Policy"];
10435
+ const value = declaredPolicy === void 0 || declaredPolicy === null ? "" : typeof declaredPolicy === "string" ? declaredPolicy : JSON.stringify(declaredPolicy);
10436
+ await new APIGatewayClient({ region: ctx.region }).send(new UpdateRestApiCommand({
10437
+ restApiId,
10438
+ patchOperations: [{
10439
+ op: "replace",
10440
+ path: "/policy",
10441
+ value
10442
+ }]
10443
+ }));
10444
+ };
10340
10445
  const SDK_WRITERS = {
10446
+ "AWS::ApiGatewayV2::Stage": writeApiGatewayV2Stage,
10341
10447
  "AWS::ElasticBeanstalk::Application": writeElasticBeanstalkApplication,
10342
10448
  "AWS::ElasticBeanstalk::Environment": writeElasticBeanstalkEnvironment,
10343
10449
  "AWS::CodeBuild::ReportGroup": writeCodeBuildReportGroup,
@@ -10463,6 +10569,10 @@ const SDK_NESTED_WRITERS = {
10463
10569
  match: (p) => p.startsWith("MethodSettings["),
10464
10570
  writer: writeCloudControlIndexNested
10465
10571
  },
10572
+ "AWS::ApiGateway::RestApi": {
10573
+ match: (p) => p === "Policy" || p.startsWith("Policy.") || p.startsWith("Policy["),
10574
+ writer: writeApiGatewayRestApiPolicy
10575
+ },
10466
10576
  "AWS::Lex::Bot": {
10467
10577
  match: (p) => p === "BotLocales" || p.startsWith("BotLocales.") || p.startsWith("BotLocales["),
10468
10578
  writer: writeLexBotLocales
@@ -10507,6 +10617,8 @@ const REVERT_SET_DEFAULT_PATHS = new Set([
10507
10617
  "AWS::InternetMonitor::Monitor\0Status",
10508
10618
  "AWS::RolesAnywhere::Profile\0DurationSeconds",
10509
10619
  "AWS::RolesAnywhere::Profile\0AttributeMappings",
10620
+ "AWS::EC2::Subnet\0AssignIpv6AddressOnCreation",
10621
+ "AWS::EC2::Subnet\0PrivateDnsNameOptionsOnLaunch",
10510
10622
  "AWS::EC2::Subnet\0EnableDns64"
10511
10623
  ]);
10512
10624
  const REVERT_SET_DEFAULT_VALUES = { "AWS::EC2::Subnet\0EnableDns64": false };
@@ -11218,7 +11330,8 @@ async function recordStack(p) {
11218
11330
  }
11219
11331
  const { path, count } = await writeBaseline(stackName, region, desired.accountId, findings, desired.rawTemplate, recorded, {
11220
11332
  allLogicalIds: desired.resources.map((r) => r.logicalId),
11221
- previous: existing
11333
+ previous: existing,
11334
+ physicalIdByLogical: physicalIdsByLogical(desired.resources)
11222
11335
  });
11223
11336
  console.log(style.ok(recordOutcomeMessage(stackName, path, count, refreshedOnly, !!existing)));
11224
11337
  const scopeNote = recordScopeNote(stackName, findings);
@@ -11403,7 +11516,8 @@ async function revertStack(p) {
11403
11516
  const baselineOpts = {
11404
11517
  declaredByLogical: declaredKeysByLogical(gathered.desired.resources),
11405
11518
  physicalIdByLogical: physicalIdsByLogical(gathered.desired.resources),
11406
- constructPathByLogical: constructPathsByLogical(gathered.desired.resources)
11519
+ constructPathByLogical: constructPathsByLogical(gathered.desired.resources),
11520
+ allLogicalIds: gathered.desired.resources.map((r) => r.logicalId)
11407
11521
  };
11408
11522
  const drifted = applyIgnores(applyBaseline(gathered.findings, baseline, {
11409
11523
  ...baselineOpts,
@@ -11735,6 +11849,8 @@ async function runIgnore(args) {
11735
11849
  stackName,
11736
11850
  findings: applyIgnores(applyBaseline(findings, baseline, {
11737
11851
  declaredByLogical: declaredKeysByLogical(desired.resources),
11852
+ physicalIdByLogical: physicalIdsByLogical(desired.resources),
11853
+ allLogicalIds: desired.resources.map((r) => r.logicalId),
11738
11854
  warn: console.error
11739
11855
  }), {
11740
11856
  stackName,
@@ -12290,7 +12406,8 @@ async function chooseScope(stackName, shownCount, foldedCount, yes) {
12290
12406
  const baselineOpts = (p) => ({
12291
12407
  declaredByLogical: declaredKeysByLogical(p.desired.resources),
12292
12408
  constructPathByLogical: constructPathsByLogical(p.desired.resources),
12293
- physicalIdByLogical: physicalIdsByLogical(p.desired.resources)
12409
+ physicalIdByLogical: physicalIdsByLogical(p.desired.resources),
12410
+ allLogicalIds: p.desired.resources.map((r) => r.logicalId)
12294
12411
  });
12295
12412
  /**
12296
12413
  * Re-evaluate check's exit WITHOUT re-reading AWS: reload the (possibly just-written)
@@ -12687,6 +12804,7 @@ async function runCheck(args) {
12687
12804
  declaredByLogical: declaredKeysByLogical(desired.resources),
12688
12805
  constructPathByLogical: constructPathsByLogical(desired.resources),
12689
12806
  physicalIdByLogical: physicalIdsByLogical(desired.resources),
12807
+ allLogicalIds: desired.resources.map((r) => r.logicalId),
12690
12808
  warn: (s) => {
12691
12809
  if (!a.json) console.error(s);
12692
12810
  }