cdk-real-drift 0.12.88 → 0.12.90

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
@@ -295,6 +295,8 @@ needs `--remove-unrecorded`).
295
295
  - **RDS**: database cluster instances
296
296
  - **S3**: bucket resource policies (an out-of-band `put-bucket-policy` on a bucket
297
297
  with no declared `AWS::S3::BucketPolicy`)
298
+ - **SQS**: queue access policies (an out-of-band `set-queue-attributes Policy` on a
299
+ queue with no declared `AWS::SQS::QueuePolicy`)
298
300
 
299
301
  </details>
300
302
 
@@ -510,10 +512,17 @@ no such gap and compares transformed stacks fully; prefer it for SAM/macro apps.
510
512
 
511
513
  ### Ignoring externally-managed properties
512
514
 
513
- Some properties are _legitimately_ rewritten by another system, such as Application
514
- Auto Scaling moving an ECS Service `DesiredCount`, or autoscaled DynamoDB capacity.
515
- A recorded snapshot would re-flag every move. Run **`cdkrd ignore`** to pick the
516
- drift to suppress, or hand-edit the git-committed `.cdkrd/ignore.yaml`. It is a
515
+ Some properties are _legitimately_ rewritten by another system. cdkrd already folds
516
+ the most common case automatically: a property a sibling
517
+ `AWS::ApplicationAutoScaling::ScalableTarget` governs — an ECS Service `DesiredCount`,
518
+ autoscaled DynamoDB capacity, a Lambda alias's provisioned concurrency, … — is **not**
519
+ flagged while its live value stays within the declared `MinCapacity`/`MaxCapacity`
520
+ band (the autoscaler enforcing the template's own delegation is intent, not drift,
521
+ #688). A value pushed _beyond_ the band still surfaces as real drift, but `revert`
522
+ deliberately refuses it (writing the initial value back would just be re-scaled). For
523
+ anything cdkrd does not fold — an externally-managed Lambda **reserved** concurrency,
524
+ a value another controller rewrites — run **`cdkrd ignore`** to pick the drift to
525
+ suppress, or hand-edit the git-committed `.cdkrd/ignore.yaml`. It is a
517
526
  hand-edited policy file (the `.gitignore` / `.dockerignore` / `.trivyignore`
518
527
  family), so it is YAML rather than JSON: the single most valuable hand-edit is a
519
528
  `#` comment recording **why** a property is ignored, and YAML can carry it where
@@ -523,10 +532,10 @@ machine-generated, wholesale-rewritten data, not human policy.)
523
532
  ```yaml
524
533
  # cdkrd ignore rules — properties cdkrd should stop reporting as drift.
525
534
  ignore:
526
- # DesiredCount is managed by Application Auto Scaling
527
- - path: '*.DesiredCount'
535
+ # reserved concurrency is managed by an external controller (not AAS, so not auto-folded)
536
+ - path: '*.ReservedConcurrentExecutions'
528
537
  # the common case: scope a rule to one stack
529
- - path: '*.DesiredCount'
538
+ - path: '*.ReservedConcurrentExecutions'
530
539
  stack: Prod*
531
540
  # narrow further to a single account and/or region when the same stack
532
541
  # name is deployed to several (a property may legitimately drift in only one)
@@ -1014,6 +1023,10 @@ covers them. **If you never run `revert`, cdkrd needs no write permissions at al
1014
1023
  override-reader permission above — here it enumerates a bucket's out-of-band
1015
1024
  resource policy as a child `AWS::S3::BucketPolicy`, so it is required for the
1016
1025
  `added` tier too; `NoSuchBucketPolicy` is the normal no-policy case)
1026
+ - `AWS::SQS::Queue`: `sqs:GetQueueAttributes` (enumerates a queue's out-of-band
1027
+ access policy as a child `AWS::SQS::QueuePolicy`; a queue with no policy simply
1028
+ returns no `Policy` attribute). Reverting a detected one also needs
1029
+ `sqs:SetQueueAttributes` (the SDK deleter clears the `Policy`).
1017
1030
 
1018
1031
  The `added` tier also needs `cloudformation:DescribeStackResources` (grouped with
1019
1032
  the other CloudFormation actions above): before flagging a live child as
package/dist/cli.js CHANGED
@@ -30,6 +30,7 @@ import { DescribeDomainConfigCommand, DescribeDomainsCommand, ListDomainNamesCom
30
30
  import { ChangeResourceRecordSetsCommand, ListResourceRecordSetsCommand, Route53Client } from "@aws-sdk/client-route-53";
31
31
  import { DeleteBucketPolicyCommand, GetBucketPolicyCommand, GetObjectCommand, PutBucketPolicyCommand, S3Client } from "@aws-sdk/client-s3";
32
32
  import { GetTopicAttributesCommand, ListSubscriptionsByTopicCommand, SNSClient, SetTopicAttributesCommand } from "@aws-sdk/client-sns";
33
+ import { GetQueueAttributesCommand, SQSClient, SetQueueAttributesCommand } from "@aws-sdk/client-sqs";
33
34
  import { ACMClient, DescribeCertificateCommand, ListTagsForCertificateCommand } from "@aws-sdk/client-acm";
34
35
  import { BudgetsClient, DescribeBudgetCommand } from "@aws-sdk/client-budgets";
35
36
  import { DescribeConfigurationSettingsCommand, ElasticBeanstalkClient, UpdateApplicationCommand, UpdateApplicationResourceLifecycleCommand, UpdateEnvironmentCommand } from "@aws-sdk/client-elastic-beanstalk";
@@ -53,7 +54,6 @@ import { GetScheduleCommand, SchedulerClient } from "@aws-sdk/client-scheduler";
53
54
  import { DescribeReceiptRuleCommand, DescribeReceiptRuleSetCommand, ListReceiptFiltersCommand, SESClient, UpdateReceiptRuleCommand } from "@aws-sdk/client-ses";
54
55
  import { DescribeEndpointConfigCommand, ListTagsCommand as ListTagsCommand$1, SageMakerClient } from "@aws-sdk/client-sagemaker";
55
56
  import { GetNamespaceCommand, GetServiceCommand, ListTagsForResourceCommand as ListTagsForResourceCommand$4, ServiceDiscoveryClient, UpdateHttpNamespaceCommand } from "@aws-sdk/client-servicediscovery";
56
- import { GetQueueAttributesCommand, SQSClient, SetQueueAttributesCommand } from "@aws-sdk/client-sqs";
57
57
  import { createHash } from "node:crypto";
58
58
  import { S_BAR, S_BAR_END, S_BAR_START, S_CHECKBOX_INACTIVE, S_CHECKBOX_SELECTED, confirm, isCancel, select, spinner } from "@clack/prompts";
59
59
  import pc from "picocolors";
@@ -6287,6 +6287,65 @@ function pushDeclaredFinding(findings, finding) {
6287
6287
  ...finding
6288
6288
  });
6289
6289
  }
6290
+ const AAS_SCALABLE_DIMENSIONS = {
6291
+ "ecs:service:DesiredCount": {
6292
+ resourceType: "AWS::ECS::Service",
6293
+ paths: ["DesiredCount"]
6294
+ },
6295
+ "dynamodb:table:ReadCapacityUnits": {
6296
+ resourceType: "AWS::DynamoDB::Table",
6297
+ paths: ["ProvisionedThroughput.ReadCapacityUnits"]
6298
+ },
6299
+ "dynamodb:table:WriteCapacityUnits": {
6300
+ resourceType: "AWS::DynamoDB::Table",
6301
+ paths: ["ProvisionedThroughput.WriteCapacityUnits"]
6302
+ },
6303
+ "lambda:function:ProvisionedConcurrency": {
6304
+ resourceType: "AWS::Lambda::Alias",
6305
+ paths: ["ProvisionedConcurrencyConfig.ProvisionedConcurrentExecutions"]
6306
+ },
6307
+ "elasticache:replication-group:NodeGroups": {
6308
+ resourceType: "AWS::ElastiCache::ReplicationGroup",
6309
+ paths: ["NumNodeGroups"]
6310
+ },
6311
+ "elasticache:replication-group:Replicas": {
6312
+ resourceType: "AWS::ElastiCache::ReplicationGroup",
6313
+ paths: ["ReplicasPerNodeGroup"]
6314
+ }
6315
+ };
6316
+ const AUTOSCALER_HINT_PREFIX = "governed by a sibling AWS::ApplicationAutoScaling::ScalableTarget (Application Auto Scaling)";
6317
+ /**
6318
+ * #688: fold declared findings whose property the stack DELEGATES to Application Auto Scaling.
6319
+ * A sibling ScalableTarget over `(resource, dimension)` means the live value moving within the
6320
+ * declared `[MinCapacity, MaxCapacity]` band is the autoscaler enforcing the template's own
6321
+ * intent (min-enforcement fires within minutes of a clean deploy, zero traffic) — NOT drift, so
6322
+ * the declared finding is DROPPED. A value OUTSIDE the band is a real over-set: it stays, but is
6323
+ * marked `autoscalerGoverned` (+ a hint) so the revert plan refuses a write the scaler would
6324
+ * immediately undo. Range-gated → detection preserved. Pure; only touches `declared`-tier
6325
+ * findings whose path is a governed path (all else passes through untouched).
6326
+ */
6327
+ function applyAutoscalerBandFold(findings, bands) {
6328
+ const out = [];
6329
+ for (const f of findings) {
6330
+ if (f.tier !== "declared") {
6331
+ out.push(f);
6332
+ continue;
6333
+ }
6334
+ const band = bands.find((b) => b.path === f.path);
6335
+ if (band === void 0) {
6336
+ out.push(f);
6337
+ continue;
6338
+ }
6339
+ const actual = f.actual;
6340
+ if (typeof actual === "number" && Number.isFinite(actual) && actual >= band.min && actual <= band.max) continue;
6341
+ out.push({
6342
+ ...f,
6343
+ autoscalerGoverned: true,
6344
+ ...f.hint === void 0 ? { hint: `${AUTOSCALER_HINT_PREFIX}, band ${band.min}..${band.max}; the live value is outside it, so this is a real change — but revert cannot converge (the scaler re-adjusts it). Change the ScalableTarget band / scaling policy, or record/ignore to accept it` } : {}
6345
+ });
6346
+ }
6347
+ return out;
6348
+ }
6290
6349
  function classifyResource(resource, liveRaw, schema, opts = {}) {
6291
6350
  const { logicalId, resourceType, physicalId, declared: declaredIn } = resource;
6292
6351
  const findings = [];
@@ -7404,7 +7463,8 @@ function classifyResource(resource, liveRaw, schema, opts = {}) {
7404
7463
  const cp = resource.constructPath;
7405
7464
  const pid = resource.physicalId;
7406
7465
  const unresolvedSibling = IAM_PRINCIPAL_POLICY_TYPES.has(resourceType) && resource.siblingPolicyNames === "unresolved";
7407
- return findings.map((f) => ({
7466
+ const bands = opts.scalableTargetBands?.[resource.logicalId];
7467
+ return (bands ? applyAutoscalerBandFold(findings, bands) : findings).map((f) => ({
7408
7468
  ...f,
7409
7469
  ...pid !== void 0 && { physicalId: pid },
7410
7470
  ...cp !== void 0 && { constructPath: cp },
@@ -7435,6 +7495,7 @@ function lambdaFunctionRefMatches(declaredValue, ...candidates) {
7435
7495
  }
7436
7496
  const CHILD_ENUMERATORS = {
7437
7497
  "AWS::S3::Bucket": enumerateS3BucketChildren,
7498
+ "AWS::SQS::Queue": enumerateSqsQueueChildren,
7438
7499
  "AWS::ApiGateway::RestApi": enumerateRestApiChildren,
7439
7500
  "AWS::ApiGatewayV2::Api": enumerateHttpApiChildren,
7440
7501
  "AWS::SNS::Topic": enumerateSnsTopicChildren,
@@ -8453,6 +8514,57 @@ async function enumerateS3BucketChildren(ctx) {
8453
8514
  livePolicy
8454
8515
  });
8455
8516
  }
8517
+ function diffSqsQueuePolicy(input) {
8518
+ if (input.hasDeclaredPolicy) return [];
8519
+ if (!input.livePolicy) return [];
8520
+ return [{
8521
+ resourceType: "AWS::SQS::QueuePolicy",
8522
+ identifier: input.queueUrl,
8523
+ siblingLookupId: input.queueUrl,
8524
+ label: `queue policy ${input.queueUrl}`,
8525
+ live: {
8526
+ Queues: [input.queueUrl],
8527
+ PolicyDocument: input.livePolicy
8528
+ }
8529
+ }];
8530
+ }
8531
+ async function readSqsQueuePolicyDocument(client, queueUrl) {
8532
+ const policyJson = (await client.send(new GetQueueAttributesCommand({
8533
+ QueueUrl: queueUrl,
8534
+ AttributeNames: ["Policy"]
8535
+ }))).Attributes?.Policy;
8536
+ if (!policyJson) return void 0;
8537
+ let parsed;
8538
+ try {
8539
+ parsed = JSON.parse(policyJson);
8540
+ } catch {
8541
+ return;
8542
+ }
8543
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : void 0;
8544
+ }
8545
+ async function enumerateSqsQueueChildren(ctx) {
8546
+ const { parent, desired, region } = ctx;
8547
+ const queueUrl = parent.physicalId;
8548
+ if (!queueUrl) return [];
8549
+ let hasDeclaredPolicy = false;
8550
+ for (const r of desired.resources) {
8551
+ if (r.resourceType !== "AWS::SQS::QueuePolicy") continue;
8552
+ const queues = r.declared.Queues;
8553
+ if (Array.isArray(queues)) {
8554
+ if (queues.some((q) => q === queueUrl)) hasDeclaredPolicy = true;
8555
+ else if (queues.some((q) => hasUnresolved(q))) hasDeclaredPolicy = true;
8556
+ } else if (queues !== void 0 && hasUnresolved(queues)) hasDeclaredPolicy = true;
8557
+ }
8558
+ const livePolicy = await readSqsQueuePolicyDocument(new SQSClient({
8559
+ region,
8560
+ ...READ_RETRY
8561
+ }), queueUrl);
8562
+ return diffSqsQueuePolicy({
8563
+ queueUrl,
8564
+ hasDeclaredPolicy,
8565
+ livePolicy
8566
+ });
8567
+ }
8456
8568
  function diffEventBusChildren(input) {
8457
8569
  const declared = new Set(input.declaredRuleNames);
8458
8570
  const added = [];
@@ -12844,7 +12956,7 @@ function addedFinding(parent, c, read) {
12844
12956
  ...read.ok ? {} : { modelReadFailed: true }
12845
12957
  };
12846
12958
  }
12847
- const CC_GET_UNSUPPORTED_ADDED_TYPES = new Set(["AWS::Route53::RecordSet"]);
12959
+ const CC_GET_UNSUPPORTED_ADDED_TYPES = new Set(["AWS::Route53::RecordSet", "AWS::SQS::QueuePolicy"]);
12848
12960
  async function readAddedModel(cc, cfn, c, schemas, oaiCanonicalIds) {
12849
12961
  const normalizeWith = async (raw) => {
12850
12962
  let schema = schemas.get(c.resourceType);
@@ -13212,6 +13324,83 @@ function buildClusterEchoModels(desired) {
13212
13324
  }
13213
13325
  return map;
13214
13326
  }
13327
+ const SCALABLE_TARGET_TYPE = "AWS::ApplicationAutoScaling::ScalableTarget";
13328
+ function collectRefLogicalIds(v, out = /* @__PURE__ */ new Set()) {
13329
+ if (v == null) return out;
13330
+ if (Array.isArray(v)) {
13331
+ for (const el of v) collectRefLogicalIds(el, out);
13332
+ return out;
13333
+ }
13334
+ if (typeof v !== "object") return out;
13335
+ const o = v;
13336
+ if ("Ref" in o && typeof o.Ref === "string") out.add(o.Ref);
13337
+ if ("Fn::GetAtt" in o) {
13338
+ const g = o["Fn::GetAtt"];
13339
+ if (Array.isArray(g) && typeof g[0] === "string") out.add(g[0]);
13340
+ else if (typeof g === "string") out.add(g.split(".")[0] ?? g);
13341
+ }
13342
+ if ("Fn::Sub" in o) {
13343
+ const s = o["Fn::Sub"];
13344
+ const body = Array.isArray(s) ? s[0] : s;
13345
+ if (typeof body === "string") {
13346
+ for (const m of body.matchAll(/\$\{([A-Za-z0-9]+)(?:\.[^}]+)?\}/g)) if (m[1]) out.add(m[1]);
13347
+ }
13348
+ if (Array.isArray(s) && s[1] && typeof s[1] === "object") collectRefLogicalIds(s[1], out);
13349
+ }
13350
+ for (const [k, val] of Object.entries(o)) {
13351
+ if (k === "Ref" || k === "Fn::GetAtt" || k === "Fn::Sub") continue;
13352
+ collectRefLogicalIds(val, out);
13353
+ }
13354
+ return out;
13355
+ }
13356
+ function buildScalableTargetBands(desired) {
13357
+ const byLogicalId = /* @__PURE__ */ new Map();
13358
+ const byType = /* @__PURE__ */ new Map();
13359
+ for (const r of desired.resources) {
13360
+ byLogicalId.set(r.logicalId, r);
13361
+ const arr = byType.get(r.resourceType);
13362
+ if (arr) arr.push(r);
13363
+ else byType.set(r.resourceType, [r]);
13364
+ }
13365
+ const map = {};
13366
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
13367
+ for (const r of desired.resources) {
13368
+ if (r.resourceType !== SCALABLE_TARGET_TYPE) continue;
13369
+ const decl = r.declared ?? {};
13370
+ const dim = decl.ScalableDimension;
13371
+ if (typeof dim !== "string") continue;
13372
+ const spec = AAS_SCALABLE_DIMENSIONS[dim];
13373
+ if (!spec) continue;
13374
+ const live = desired.ctx.liveAttrs[r.logicalId] ?? {};
13375
+ const min = num(decl.MinCapacity) ?? num(live.MinCapacity);
13376
+ const max = num(decl.MaxCapacity) ?? num(live.MaxCapacity);
13377
+ if (min === void 0 || max === void 0) continue;
13378
+ const rawResourceId = r.declaredRaw?.ResourceId;
13379
+ let governed;
13380
+ for (const id of collectRefLogicalIds(rawResourceId)) {
13381
+ const cand = byLogicalId.get(id);
13382
+ if (cand && cand.resourceType === spec.resourceType) {
13383
+ governed = cand;
13384
+ break;
13385
+ }
13386
+ }
13387
+ if (!governed) {
13388
+ const rid = decl.ResourceId;
13389
+ if (typeof rid === "string") {
13390
+ const segs = new Set(rid.split("/"));
13391
+ governed = byType.get(spec.resourceType)?.find((c) => c.physicalId !== void 0 && (segs.has(c.physicalId) || rid.endsWith(c.physicalId)));
13392
+ }
13393
+ }
13394
+ if (!governed) continue;
13395
+ const entries = map[governed.logicalId] ??= [];
13396
+ for (const path of spec.paths) entries.push({
13397
+ path,
13398
+ min,
13399
+ max
13400
+ });
13401
+ }
13402
+ return map;
13403
+ }
13215
13404
  async function buildRdsOptionSettingDefaults(desired, region) {
13216
13405
  const groups = desired.resources.filter((r) => r.resourceType === "AWS::RDS::OptionGroup" && r.physicalId);
13217
13406
  if (groups.length === 0) return {};
@@ -13449,6 +13638,7 @@ async function gatherFindings(stackName, region, templateOverride, recoveryTempl
13449
13638
  bucketNotificationManaged: buildBucketNotificationManaged(desired),
13450
13639
  bucketNotificationConfigs: buildBucketNotificationConfigs(desired),
13451
13640
  clusterEchoModel: buildClusterEchoModels(desired),
13641
+ scalableTargetBands: buildScalableTargetBands(desired),
13452
13642
  rdsOptionSettingDefaults: await buildRdsOptionSettingDefaults(desired, region)
13453
13643
  };
13454
13644
  const corpusDir = process.env[CORPUS_DIR_ENV];
@@ -13523,6 +13713,7 @@ async function regatherTouched(gathered, touched, region) {
13523
13713
  bucketNotificationManaged: buildBucketNotificationManaged(desired),
13524
13714
  bucketNotificationConfigs: buildBucketNotificationConfigs(desired),
13525
13715
  clusterEchoModel: buildClusterEchoModels(desired),
13716
+ scalableTargetBands: buildScalableTargetBands(desired),
13526
13717
  rdsOptionSettingDefaults: await buildRdsOptionSettingDefaults(desired, region)
13527
13718
  };
13528
13719
  const fresh = [];
@@ -16950,9 +17141,19 @@ const deleteRoute53RecordSet = async (ctx) => {
16950
17141
  }] }
16951
17142
  }));
16952
17143
  };
17144
+ const deleteSqsQueuePolicy = async (ctx) => {
17145
+ await new SQSClient({
17146
+ region: ctx.region,
17147
+ ...CLIENT_TIMEOUTS
17148
+ }).send(new SetQueueAttributesCommand({
17149
+ QueueUrl: ctx.physicalId,
17150
+ Attributes: { Policy: "" }
17151
+ }));
17152
+ };
16953
17153
  const SDK_DELETERS = {
16954
17154
  "AWS::AppSync::ApiKey": deleteAppSyncApiKey,
16955
- "AWS::Route53::RecordSet": deleteRoute53RecordSet
17155
+ "AWS::Route53::RecordSet": deleteRoute53RecordSet,
17156
+ "AWS::SQS::QueuePolicy": deleteSqsQueuePolicy
16956
17157
  };
16957
17158
 
16958
17159
  //#endregion
@@ -17181,6 +17382,15 @@ function buildRevertPlan(findings, baseline, opts = {}) {
17181
17382
  desired: f.wholeArrayRevert.value
17182
17383
  };
17183
17384
  }
17385
+ if (f.autoscalerGoverned) {
17386
+ notRevertable.push({
17387
+ displayId,
17388
+ resourceType: f.resourceType,
17389
+ path: f.path,
17390
+ reason: "managed by Application Auto Scaling — revert would fight the scaler; change the ScalableTarget band / scaling policy, or record/ignore to accept"
17391
+ });
17392
+ continue;
17393
+ }
17184
17394
  if (f.tier === "deleted") {
17185
17395
  notRevertable.push({
17186
17396
  displayId,