cdk-real-drift 0.12.49 → 0.12.51

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
@@ -962,7 +962,11 @@ covers them. **If you never run `revert`, cdkrd needs no write permissions at al
962
962
  - `AWS::Events::EventBus`: `events:ListRules`
963
963
  - `AWS::Cognito::UserPool`: `cognito-idp:ListUserPoolClients`,
964
964
  `cognito-idp:ListGroups`, `cognito-idp:ListResourceServers`,
965
- `cognito-idp:ListIdentityProviders`
965
+ `cognito-idp:ListIdentityProviders`, plus (only when an undeclared
966
+ service-prefix-named app client is present, to corroborate that an
967
+ OpenSearch/Elasticsearch domain targets the pool before skipping it)
968
+ `es:ListDomainNames`, `es:DescribeDomains` — a caller lacking these degrades
969
+ fail-safe (the service client is treated as corroborated, never falsely flagged)
966
970
  - `AWS::AppSync::GraphQLApi`: `appsync:ListDataSources`, `appsync:ListResolvers`,
967
971
  `appsync:ListFunctions`, `appsync:ListTypes`
968
972
  - `AWS::Logs::LogGroup`: `logs:DescribeSubscriptionFilters` (plus
package/dist/cli.js CHANGED
@@ -25,6 +25,7 @@ import { DescribeMountTargetsCommand, EFSClient } from "@aws-sdk/client-efs";
25
25
  import { DescribeListenersCommand, DescribeRulesCommand, ElasticLoadBalancingV2Client, GetTrustStoreCaCertificatesBundleCommand, ModifyLoadBalancerAttributesCommand, ModifyTargetGroupAttributesCommand } from "@aws-sdk/client-elastic-load-balancing-v2";
26
26
  import { DescribeEventBusCommand, EventBridgeClient, ListRulesCommand, PutPermissionCommand } from "@aws-sdk/client-eventbridge";
27
27
  import { GetFunctionCommand, GetPolicyCommand, LambdaClient, ListAliasesCommand as ListAliasesCommand$1, ListEventSourceMappingsCommand, ListFunctionUrlConfigsCommand, ListVersionsByFunctionCommand } from "@aws-sdk/client-lambda";
28
+ import { DescribeDomainConfigCommand, DescribeDomainsCommand, ListDomainNamesCommand, OpenSearchClient, UpdateDomainConfigCommand } from "@aws-sdk/client-opensearch";
28
29
  import { ChangeResourceRecordSetsCommand, ListResourceRecordSetsCommand, Route53Client } from "@aws-sdk/client-route-53";
29
30
  import { GetTopicAttributesCommand, ListSubscriptionsByTopicCommand, SNSClient, SetTopicAttributesCommand } from "@aws-sdk/client-sns";
30
31
  import { ACMClient, DescribeCertificateCommand, ListTagsForCertificateCommand } from "@aws-sdk/client-acm";
@@ -58,7 +59,6 @@ import pc from "picocolors";
58
59
  import { MultiSelectPrompt, Prompt, isCancel as isCancel$1 } from "@clack/core";
59
60
  import { CloudFrontClient, GetDistributionConfigCommand, UpdateDistributionCommand } from "@aws-sdk/client-cloudfront";
60
61
  import { DescribeSignalingChannelCommand, DescribeStreamCommand, KinesisVideoClient, UpdateDataRetentionCommand, UpdateSignalingChannelCommand, UpdateStreamStorageConfigurationCommand } from "@aws-sdk/client-kinesis-video";
61
- import { DescribeDomainConfigCommand, OpenSearchClient, UpdateDomainConfigCommand } from "@aws-sdk/client-opensearch";
62
62
  import { GetWebACLCommand, UpdateWebACLCommand, WAFV2Client } from "@aws-sdk/client-wafv2";
63
63
  import { ConfigServiceClient, DescribeConfigRulesCommand, PutConfigRuleCommand } from "@aws-sdk/client-config-service";
64
64
  import { GetCallerIdentityCommand, STSClient } from "@aws-sdk/client-sts";
@@ -1089,6 +1089,26 @@ function buildStackSelector(patterns) {
1089
1089
  }
1090
1090
  const CONCRETE_REGION = /^[a-z]{2}(-[a-z]+)+-\d+$/;
1091
1091
  const CONCRETE_ACCOUNT = /^\d{12}$/;
1092
+ const SYNTHESIS_ERROR_LEVEL = "error";
1093
+ /**
1094
+ * Extract the ERROR-level synthesis messages of a single stack artifact (#1316).
1095
+ *
1096
+ * A stack's `Annotations.addError(...)` (cdk-nag, a security aspect, a "do not deploy" guard)
1097
+ * surfaces as a `messages` entry with `level === 'error'`. toolkit.synth's own
1098
+ * `validateStacksMetadata` aborts on these — but ONLY for the SELECTOR-matched stacks, and the
1099
+ * #905 selector matches on hierarchicalId, so a stackName-form positional (`Dev-Net`) that
1100
+ * matches zero hierarchicalIds skips that validation entirely. We re-collect them here so
1101
+ * resolveStacks can abort on the SELECTED stacks, restoring the no-args abort behavior for the
1102
+ * named case. Pure + exported for unit tests. Returns the human-readable error strings (empty
1103
+ * when the stack has no error annotation).
1104
+ */
1105
+ function stackErrorMessages(messages) {
1106
+ if (!messages) return [];
1107
+ return messages.filter((m) => m.level === SYNTHESIS_ERROR_LEVEL).map((m) => {
1108
+ const data = m.entry?.data;
1109
+ return typeof data === "string" && data.length > 0 ? data : "error";
1110
+ });
1111
+ }
1092
1112
  function concreteAccount(raw) {
1093
1113
  return raw && CONCRETE_ACCOUNT.test(raw) ? raw : void 0;
1094
1114
  }
@@ -1216,8 +1236,10 @@ async function synthApp(app, opts = {}) {
1216
1236
  }
1217
1237
  return cached.cloudAssembly.stacksRecursively.map((s) => ({
1218
1238
  stackName: s.stackName,
1239
+ hierarchicalId: s.hierarchicalId,
1219
1240
  region: CONCRETE_REGION.test(s.environment.region) ? s.environment.region : void 0,
1220
1241
  account: concreteAccount(s.environment.account),
1242
+ errorMessages: stackErrorMessages(s.messages),
1221
1243
  template: s.template
1222
1244
  }));
1223
1245
  } finally {
@@ -1232,8 +1254,10 @@ async function synthApp(app, opts = {}) {
1232
1254
  async function discoverStacks(app, opts = {}) {
1233
1255
  return (await synthApp(app, opts)).map((s) => ({
1234
1256
  stackName: s.stackName,
1257
+ hierarchicalId: s.hierarchicalId,
1235
1258
  region: s.region,
1236
1259
  account: s.account,
1260
+ errorMessages: s.errorMessages,
1237
1261
  template: s.template
1238
1262
  }));
1239
1263
  }
@@ -1303,6 +1327,39 @@ async function resolveProfileRegion(profile) {
1303
1327
  } catch {}
1304
1328
  return defaultProfileRegionFromIni() ?? await regionFromImds();
1305
1329
  }
1330
+ /**
1331
+ * #1316: does a CLI positional select this discovered stack? A positional matches against BOTH
1332
+ * the deployed CloudFormation `stackName` AND the toolkit `hierarchicalId` (`Stage/Stack` for a
1333
+ * stack nested in a CDK `Stage`), so BOTH `check Dev-Net` (the stage-qualified stackName cdkrd
1334
+ * historically accepted) AND the cdk-native `check Dev/Net` (what `cdk ls`/`cdk synth` show, and
1335
+ * what the #905 selector actually matches on) resolve to the staged stack. A positional with a
1336
+ * glob metachar (`*`/`?`) is matched as a glob against each identifier; a plain positional matches
1337
+ * either identifier EXACTLY (equivalent to a metachar-free glob, but kept as `===` for clarity and
1338
+ * to preserve the exact-name semantics). For a top-level stack the two identifiers are identical,
1339
+ * so behavior there is unchanged. Pure + exported for unit tests.
1340
+ */
1341
+ function positionalMatchesStack(positional, stack) {
1342
+ const hierarchicalId = stack.hierarchicalId ?? stack.stackName;
1343
+ if (isGlob(positional)) return matchesGlob(positional, stack.stackName) || matchesGlob(positional, hierarchicalId);
1344
+ return positional === stack.stackName || positional === hierarchicalId;
1345
+ }
1346
+ /**
1347
+ * #1316: the residual-hole guard. toolkit.synth's metadata validation aborts on a stack's
1348
+ * error-level annotations (`Annotations.addError(...)` — cdk-nag, a security aspect, a
1349
+ * "do not deploy" guard), but ONLY for the SELECTOR-matched collection, and the #905 selector
1350
+ * matches on hierarchicalId. A stackName-form positional (`Dev-Net`) matches zero hierarchicalIds,
1351
+ * so that validation is silently skipped — cdkrd would then read (and `revert --yes` write back)
1352
+ * a template from an app in an error state. After selecting the target stacks, re-check THEIR
1353
+ * error annotations and throw so the caller aborts (check maps a resolveStacks throw to exit 2),
1354
+ * restoring the no-args abort behavior for the named case. The no-args / --all path already had
1355
+ * toolkit.synth validate every stack (no selector), so this is a belt for the named case.
1356
+ * Aggregates messages across every selected stack. Pure + exported for unit tests.
1357
+ */
1358
+ function assertNoStackErrors(selected) {
1359
+ const lines = [];
1360
+ for (const s of selected) for (const msg of s.errorMessages ?? []) lines.push(` ${s.stackName}: ${msg}`);
1361
+ if (lines.length > 0) throw new Error(`the CDK app synthesized with ${lines.length} error(s) (an Annotations.addError — cdk-nag / security aspect / do-not-deploy guard) on the selected stack(s); refusing to read or revert an app in an error state:\n${lines.join("\n")}`);
1362
+ }
1306
1363
  async function resolveStacks(a) {
1307
1364
  const app = resolveApp(a.app);
1308
1365
  if (!app) throw new Error("cdkrd needs a CDK app: run in a directory with cdk.json, pass --app \"<cmd>\" or --app <cdk.out> (a pre-synthesized assembly), or set $CDKRD_APP");
@@ -1315,14 +1372,18 @@ async function resolveStacks(a) {
1315
1372
  context: a.context,
1316
1373
  stackPatterns: scopePatterns
1317
1374
  });
1318
- if (a.all || a.stackNames.length === 0) return discovered.map((s) => ({
1319
- stackName: s.stackName,
1320
- region: s.region ?? fallbackRegion,
1321
- account: s.account,
1322
- template: s.template
1323
- }));
1375
+ if (a.all || a.stackNames.length === 0) {
1376
+ assertNoStackErrors(discovered);
1377
+ return discovered.map((s) => ({
1378
+ stackName: s.stackName,
1379
+ region: s.region ?? fallbackRegion,
1380
+ account: s.account,
1381
+ template: s.template
1382
+ }));
1383
+ }
1324
1384
  const seen = /* @__PURE__ */ new Set();
1325
1385
  const out = [];
1386
+ const selectedByKey = /* @__PURE__ */ new Map();
1326
1387
  const add = (stackName, region, account, template) => {
1327
1388
  const key = `${stackName}\0${region ?? ""}\0${account ?? ""}`;
1328
1389
  if (seen.has(key)) return;
@@ -1334,19 +1395,22 @@ async function resolveStacks(a) {
1334
1395
  template
1335
1396
  });
1336
1397
  };
1337
- const known = () => discovered.map((s) => s.stackName).join(", ") || "none";
1338
- for (const name of a.stackNames) if (isGlob(name)) {
1339
- let matched = 0;
1340
- for (const s of discovered) if (matchesGlob(name, s.stackName)) {
1341
- matched++;
1342
- add(s.stackName, s.region ?? fallbackRegion, s.account, s.template);
1398
+ const known = () => discovered.map((s) => s.hierarchicalId === s.stackName ? s.stackName : `${s.hierarchicalId} (${s.stackName})`).join(", ") || "none";
1399
+ const select = (s) => {
1400
+ add(s.stackName, s.region ?? fallbackRegion, s.account, s.template);
1401
+ selectedByKey.set(`${s.stackName}\0${s.region ?? ""}\0${s.account ?? ""}`, s);
1402
+ };
1403
+ for (const name of a.stackNames) {
1404
+ const hits = discovered.filter((s) => positionalMatchesStack(name, s));
1405
+ if (isGlob(name)) {
1406
+ if (hits.length === 0) throw new Error(`glob "${name}" matched no stacks defined by the CDK app (found: ${known()})`);
1407
+ for (const hit of hits) select(hit);
1408
+ } else {
1409
+ if (hits.length === 0) throw new Error(`stack "${name}" is not defined by the CDK app (found: ${known()})`);
1410
+ for (const hit of hits) select(hit);
1343
1411
  }
1344
- if (matched === 0) throw new Error(`glob "${name}" matched no stacks defined by the CDK app (found: ${known()})`);
1345
- } else {
1346
- const hits = discovered.filter((s) => s.stackName === name);
1347
- if (hits.length === 0) throw new Error(`stack "${name}" is not defined by the CDK app (found: ${known()})`);
1348
- for (const hit of hits) add(hit.stackName, hit.region ?? fallbackRegion, hit.account, hit.template);
1349
1412
  }
1413
+ assertNoStackErrors([...selectedByKey.values()]);
1350
1414
  if (out.length === 0) throw new Error(`no stacks match ${a.stackNames.join(", ")} (found: ${known()})`);
1351
1415
  return out;
1352
1416
  }
@@ -5823,6 +5887,37 @@ function substituteLeaf(obj, leafName, coerced) {
5823
5887
  [leafName]: coerced
5824
5888
  };
5825
5889
  }
5890
+ function valueAtDottedPath$1(root, dottedPath) {
5891
+ let node = root;
5892
+ for (const seg of dottedPath.split(".")) {
5893
+ if (node == null || typeof node !== "object") return void 0;
5894
+ node = node[seg];
5895
+ }
5896
+ return node;
5897
+ }
5898
+ function matchesAncestorPropertyTransform(propertyTransforms, driftPath, declaredRoot, liveRoot) {
5899
+ const segs = driftPath.split(".");
5900
+ for (let end = segs.length - 1; end >= 1; end--) {
5901
+ const ancestor = segs.slice(0, end).join(".");
5902
+ const transformExpr = propertyTransforms[ancestor] ?? propertyTransforms[ancestor.replace(/\.\d+(?=\.|$)/g, ".*")];
5903
+ if (transformExpr === void 0) continue;
5904
+ const liveAtAncestor = valueAtDottedPath$1(liveRoot, ancestor);
5905
+ if (liveAtAncestor === void 0) continue;
5906
+ for (const alt of transformExpr.split(" $OR ")) {
5907
+ const expr = alt.trim();
5908
+ if (!expr) continue;
5909
+ const compiled = compileTransform(expr);
5910
+ if (!compiled) continue;
5911
+ try {
5912
+ const out = compiled.evaluate(declaredRoot);
5913
+ if (out === void 0) continue;
5914
+ const transformedAtAncestor = valueAtDottedPath$1(out, ancestor);
5915
+ if (transformedAtAncestor !== void 0 && deepEqual(transformedAtAncestor, liveAtAncestor)) return true;
5916
+ } catch {}
5917
+ }
5918
+ }
5919
+ return false;
5920
+ }
5826
5921
  function resolveParentObject(root, dottedPath) {
5827
5922
  const segs = dottedPath.split(".");
5828
5923
  if (segs.length <= 1) return root;
@@ -6541,6 +6636,7 @@ function classifyResource(resource, liveRaw, schema, opts = {}) {
6541
6636
  }) ?? false)) continue;
6542
6637
  const transformExpr = schema.propertyTransforms?.[d.path] ?? schema.propertyTransforms?.[d.path.replace(/\.\d+(?=\.|$)/g, ".*")];
6543
6638
  if (transformExpr !== void 0 && matchesPropertyTransform(transformExpr, d.stateValue, resolveParentObject(declared, d.path), declared, d.awsValue, d.path.split(".").at(-1) ?? d.path)) continue;
6639
+ if (schema.propertyTransforms !== void 0 && transformExpr === void 0 && matchesAncestorPropertyTransform(schema.propertyTransforms, d.path, declared, live)) continue;
6544
6640
  const tagListWhole = !unorderedObjArray && Array.isArray(v) && isKeyValueTagList(v) && d.path.startsWith(`${k}.`);
6545
6641
  const unorderedExtra = unorderedObjArray && Array.isArray(declaredVal) && declaredRemapSource ? {
6546
6642
  path: remapSortedIndexToDeclared(d.path, k, declaredVal, declaredRemapSource),
@@ -7741,12 +7837,12 @@ function isOpenSearchServiceClient(name) {
7741
7837
  return OPENSEARCH_SERVICE_CLIENT_PREFIXES.some((p) => name.startsWith(p));
7742
7838
  }
7743
7839
  function diffUserPoolChildren(input) {
7744
- const { userPoolId, declaredClientIds, liveClients } = input;
7840
+ const { userPoolId, declaredClientIds, liveClients, openSearchCorroborated = true } = input;
7745
7841
  const declared = new Set(declaredClientIds);
7746
7842
  const added = [];
7747
7843
  for (const c of liveClients) {
7748
7844
  if (declared.has(c.id)) continue;
7749
- if (isOpenSearchServiceClient(c.name ?? c.label)) continue;
7845
+ if (openSearchCorroborated && isOpenSearchServiceClient(c.name ?? c.label)) continue;
7750
7846
  added.push({
7751
7847
  resourceType: "AWS::Cognito::UserPoolClient",
7752
7848
  identifier: `${userPoolId}|${c.id}`,
@@ -7872,6 +7968,19 @@ async function pageUserPoolIdentityProviders(client, userPoolId) {
7872
7968
  } while (next);
7873
7969
  return out;
7874
7970
  }
7971
+ async function openSearchDomainTargetsPool(region, userPoolId) {
7972
+ try {
7973
+ const os = new OpenSearchClient({
7974
+ region,
7975
+ ...READ_RETRY
7976
+ });
7977
+ const domainNames = ((await os.send(new ListDomainNamesCommand({}))).DomainNames ?? []).map((d) => d.DomainName).filter((n) => typeof n === "string");
7978
+ if (domainNames.length === 0) return false;
7979
+ return ((await os.send(new DescribeDomainsCommand({ DomainNames: domainNames }))).DomainStatusList ?? []).some((d) => d.CognitoOptions?.Enabled === true && d.CognitoOptions.UserPoolId === userPoolId);
7980
+ } catch {
7981
+ return true;
7982
+ }
7983
+ }
7875
7984
  async function enumerateUserPoolChildren(ctx) {
7876
7985
  const { parent, desired, region } = ctx;
7877
7986
  const userPoolId = parent.physicalId;
@@ -7895,14 +8004,18 @@ async function enumerateUserPoolChildren(ctx) {
7895
8004
  region,
7896
8005
  ...READ_RETRY
7897
8006
  });
8007
+ const liveClients = (await pageUserPoolClients(client, userPoolId)).filter((c) => typeof c.ClientId === "string").map((c) => ({
8008
+ id: c.ClientId,
8009
+ name: c.ClientName,
8010
+ label: c.ClientName ?? c.ClientId
8011
+ }));
8012
+ let openSearchCorroborated = desired.resources.some((r) => (r.resourceType === "AWS::OpenSearchService::Domain" || r.resourceType === "AWS::Elasticsearch::Domain") && parentRefMatches(r.declared.CognitoOptions?.UserPoolId, userPoolId));
8013
+ if (!openSearchCorroborated && liveClients.some((c) => !declaredClientIds.includes(c.id) && isOpenSearchServiceClient(c.name ?? c.label))) openSearchCorroborated = await openSearchDomainTargetsPool(region, userPoolId);
7898
8014
  const clientAdded = diffUserPoolChildren({
7899
8015
  userPoolId,
7900
8016
  declaredClientIds,
7901
- liveClients: (await pageUserPoolClients(client, userPoolId)).filter((c) => typeof c.ClientId === "string").map((c) => ({
7902
- id: c.ClientId,
7903
- name: c.ClientName,
7904
- label: c.ClientName ?? c.ClientId
7905
- }))
8017
+ liveClients,
8018
+ openSearchCorroborated
7906
8019
  });
7907
8020
  const groupAdded = diffUserPoolGroups({
7908
8021
  userPoolId,