cdk-real-drift 0.4.38 → 0.4.39

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,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { existsSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
3
- import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
4
4
  import { dirname, join, resolve } from "node:path";
5
+ import { pid } from "node:process";
5
6
  import { YAMLSeq, isSeq, parse, parseDocument } from "yaml";
6
7
  import { CloudControlClient, DeleteResourceCommand, GetResourceCommand, GetResourceRequestStatusCommand, UpdateResourceCommand } from "@aws-sdk/client-cloudcontrol";
7
8
  import { homedir } from "node:os";
@@ -742,25 +743,63 @@ function appendRulesToYaml(existingRaw, added) {
742
743
  return doc.toString();
743
744
  }
744
745
  /**
746
+ * Atomically replace `dest` with `content` (same filesystem): write to a sibling temp file
747
+ * in the SAME directory, then `rename` it over `dest`. `rename` is atomic on one filesystem,
748
+ * so a concurrent reader (`loadConfig`) never observes a half-written file — it sees either
749
+ * the old bytes or the new bytes in full, never a TRUNCATED-but-still-valid YAML (issue
750
+ * #759): a crash/Ctrl-C mid-`writeFile` could otherwise leave e.g. a truncated bare-scalar
751
+ * glob `path: Api` that OVER-matches, which `loadConfig` would accept silently. The temp file
752
+ * MUST be a SIBLING (same dir) so the rename stays within one filesystem — a rename across
753
+ * filesystems is not atomic (it degrades to copy+unlink). The pid + a monotonic counter keep
754
+ * the temp name unique per concurrent writer so two racing processes don't clobber each
755
+ * other's temp file. On any failure the temp file is cleaned up so it can't accumulate.
756
+ */
757
+ let tmpCounter = 0;
758
+ async function atomicWrite(dest, content) {
759
+ const tmp = `${dest}.${pid}.${tmpCounter++}.tmp`;
760
+ try {
761
+ await writeFile(tmp, content);
762
+ await rename(tmp, dest);
763
+ } catch (e) {
764
+ await unlink(tmp).catch(() => {});
765
+ throw e;
766
+ }
767
+ }
768
+ /**
745
769
  * Append ignore rules to `.cdkrd/ignore.yaml` (cwd-relative), creating the file (and
746
770
  * the `.cdkrd/` dir) if absent. Idempotent: rules already present are reported, not
747
771
  * duplicated. Loads through `loadConfig` first so a malformed config fails fast rather
748
772
  * than being silently overwritten. Returns the path + what changed so the caller can
749
773
  * report it. The only mutating entry point for config (parallel to `writeBaseline`).
774
+ *
775
+ * The write is ATOMIC (tmp file + `rename`, see `atomicWrite`) so a crash mid-write can
776
+ * never leave a truncated-but-valid config (#759). To narrow the read-merge-write race with
777
+ * a concurrent `cdkrd` process, the on-disk config is RE-READ immediately before the write
778
+ * and the incoming rules merged against THAT fresh state — so a rule another process
779
+ * appended between our initial `loadConfig` and our write is preserved, not clobbered.
750
780
  */
751
781
  async function addIgnoreRules(newRules) {
752
- const { added, alreadyPresent } = mergeIgnoreRules((await loadConfig()).ignore, newRules);
753
- added.forEach((rule, i) => validateIgnoreEntry(rule, i));
754
- if (added.length > 0) {
755
- let existingRaw;
756
- try {
757
- existingRaw = await readFile(CONFIG_PATH, "utf8");
758
- } catch (e) {
759
- if (e.code !== "ENOENT") throw e;
760
- }
761
- await mkdir(dirname(CONFIG_PATH), { recursive: true });
762
- await writeFile(CONFIG_PATH, appendRulesToYaml(existingRaw, added));
782
+ const firstPass = mergeIgnoreRules((await loadConfig()).ignore, newRules);
783
+ firstPass.added.forEach((rule, i) => validateIgnoreEntry(rule, i));
784
+ if (firstPass.added.length === 0) return {
785
+ path: CONFIG_PATH,
786
+ added: firstPass.added,
787
+ alreadyPresent: firstPass.alreadyPresent
788
+ };
789
+ await mkdir(dirname(CONFIG_PATH), { recursive: true });
790
+ let existingRaw;
791
+ try {
792
+ existingRaw = await readFile(CONFIG_PATH, "utf8");
793
+ } catch (e) {
794
+ if (e.code !== "ENOENT") throw e;
763
795
  }
796
+ const { added, alreadyPresent } = mergeIgnoreRules(existingRaw !== void 0 && existingRaw.trim() !== "" ? (await loadConfig()).ignore : [], newRules);
797
+ if (added.length === 0) return {
798
+ path: CONFIG_PATH,
799
+ added,
800
+ alreadyPresent
801
+ };
802
+ await atomicWrite(CONFIG_PATH, appendRulesToYaml(existingRaw, added));
764
803
  return {
765
804
  path: CONFIG_PATH,
766
805
  added,
@@ -4333,6 +4372,14 @@ function canonicalizeStatement(s) {
4333
4372
  }
4334
4373
  return out;
4335
4374
  }
4375
+ const AWS_LOG_DELIVERY_ALLOWED_ACTIONS = new Set([
4376
+ "s3:PutObject",
4377
+ "s3:GetBucketAcl",
4378
+ "logs:CreateLogStream",
4379
+ "logs:PutLogEvents",
4380
+ "firehose:PutRecord",
4381
+ "firehose:PutRecordBatch"
4382
+ ]);
4336
4383
  function isAwsManagedLogDeliveryStatement(s) {
4337
4384
  if (!isObj(s)) return false;
4338
4385
  const sid = s.Sid;
@@ -4340,7 +4387,12 @@ function isAwsManagedLogDeliveryStatement(s) {
4340
4387
  const principal = s.Principal;
4341
4388
  if (!isObj(principal)) return false;
4342
4389
  const svc = principal.Service;
4343
- return (Array.isArray(svc) ? svc : [svc]).includes("delivery.logs.amazonaws.com");
4390
+ if (!(Array.isArray(svc) ? svc : [svc]).includes("delivery.logs.amazonaws.com")) return false;
4391
+ if (s.Effect !== "Allow") return false;
4392
+ const actionRaw = s.Action;
4393
+ const actions = Array.isArray(actionRaw) ? actionRaw : [actionRaw];
4394
+ if (actions.length === 0) return false;
4395
+ return actions.every((a) => typeof a === "string" && AWS_LOG_DELIVERY_ALLOWED_ACTIONS.has(a));
4344
4396
  }
4345
4397
  function canonicalizePrincipal(v) {
4346
4398
  if (isObj(v)) {
@@ -9350,21 +9402,30 @@ const failureWarned = /* @__PURE__ */ new Set();
9350
9402
  function describeTypeFailedWarning(resourceType, region) {
9351
9403
  return `warning: ${region}: cloudformation:DescribeType failed for ${resourceType} — schema-based drift suppression is degraded for this type. Undeclared read-only attributes may surface as [Potential Drift] and declared write-only properties may report false drift. Grant cloudformation:DescribeType (and retry if throttled) for full coverage.`;
9352
9404
  }
9353
- async function getSchemaInfo(client, resourceType) {
9405
+ async function getSchemaInfoResult(client, resourceType) {
9354
9406
  const region = await client.config.region();
9355
9407
  const cacheKey = `${region}\0${resourceType}`;
9356
9408
  const cached = cache.get(cacheKey);
9357
- if (cached) return cached;
9409
+ if (cached) return {
9410
+ info: cached,
9411
+ failed: false
9412
+ };
9358
9413
  const result = await fetch$1(client, resourceType);
9359
9414
  if (result.ok) {
9360
9415
  cache.set(cacheKey, result.info);
9361
- return result.info;
9416
+ return {
9417
+ info: result.info,
9418
+ failed: false
9419
+ };
9362
9420
  }
9363
9421
  if (!failureWarned.has(cacheKey)) {
9364
9422
  failureWarned.add(cacheKey);
9365
9423
  console.error(describeTypeFailedWarning(resourceType, region));
9366
9424
  }
9367
- return result.info;
9425
+ return {
9426
+ info: result.info,
9427
+ failed: true
9428
+ };
9368
9429
  }
9369
9430
  const OVERRIDE_READABLE_WRITEONLY = {
9370
9431
  "AWS::EC2::LaunchTemplate": ["LaunchTemplateData"],
@@ -9834,8 +9895,12 @@ async function readAddedModel(cc, cfn, c, schemas, oaiCanonicalIds) {
9834
9895
  Identifier: c.identifier
9835
9896
  }));
9836
9897
  const raw = JSON.parse(g.ResourceDescription?.Properties ?? "{}");
9837
- const schema = schemas.get(c.resourceType) ?? await getSchemaInfo(cfn, c.resourceType);
9838
- schemas.set(c.resourceType, schema);
9898
+ let schema = schemas.get(c.resourceType);
9899
+ if (!schema) {
9900
+ const res = await getSchemaInfoResult(cfn, c.resourceType);
9901
+ schema = res.info;
9902
+ if (!res.failed) schemas.set(c.resourceType, schema);
9903
+ }
9839
9904
  return {
9840
9905
  model: normalizeLiveModel(raw, schema, {
9841
9906
  oaiCanonicalIds,
@@ -9985,8 +10050,12 @@ async function classifyRead(cfn, r, read, schemas, classifyOpts) {
9985
10050
  path: "",
9986
10051
  note: read?.skippedReason ?? "not readable"
9987
10052
  }];
9988
- const schema = schemas.get(r.resourceType) ?? await getSchemaInfo(cfn, r.resourceType);
9989
- schemas.set(r.resourceType, schema);
10053
+ let schema = schemas.get(r.resourceType);
10054
+ if (!schema) {
10055
+ const res = await getSchemaInfoResult(cfn, r.resourceType);
10056
+ schema = res.info;
10057
+ if (!res.failed) schemas.set(r.resourceType, schema);
10058
+ }
9990
10059
  return classifyResource(r, read.live, schema, classifyOpts);
9991
10060
  }
9992
10061
  async function gatherFindings(stackName, region, templateOverride, recoveryTemplate) {
@@ -10501,9 +10570,33 @@ function carryForwardUnreadable(recorded, existing, findings) {
10501
10570
  * cleanly with #767's identity-sort case). Idempotency of the pipeline means an
10502
10571
  * already-canonical live value is unchanged, so this never weakens real change
10503
10572
  * detection: two values that differ after canonicalization still compare unequal.
10573
+ *
10574
+ * #767: `canonicalizeForCompare` only IDENTITY-sorts object arrays (by
10575
+ * Key/Id/Name/…), but the live model reaches a DIFFERENT total order — classify's
10576
+ * `sortUnorderedSetProps` runs `sortUnorderedObjectArray` (a full CANONICAL-JSON
10577
+ * sort) over unordered object-array props, and for an IDENTITY-LESS array the
10578
+ * identity-sort is a no-op, so the live `f.actual` lands in canonical-JSON order
10579
+ * while the recorded raw baseline stays in template order. `deepEqual` is
10580
+ * positional, so those two never converge — a permanent "changed since record" that
10581
+ * re-recording can't clear. Re-applying the SAME canonical-JSON sort (deeply) to
10582
+ * BOTH sides here drives them to one total order, restoring reflexivity
10583
+ * (`baselineValueMatches(v, v)` is true for identity-less arrays too). It is
10584
+ * SYMMETRIC and only REORDERS (never merges/drops elements), so two genuinely
10585
+ * different values still differ — change detection is preserved. Baseline compare is
10586
+ * type-agnostic over UNDECLARED snapshot fragments, which never carry an
10587
+ * order-significant declared array, so an order-insensitive sort is safe here.
10504
10588
  */
10505
10589
  function baselineValueMatches(baselineValue, currentCanonicalValue) {
10506
- return deepEqual(canonicalizeForCompare(baselineValue), canonicalizeForCompare(currentCanonicalValue));
10590
+ return deepEqual(sortObjectArraysDeep(canonicalizeForCompare(baselineValue)), sortObjectArraysDeep(canonicalizeForCompare(currentCanonicalValue)));
10591
+ }
10592
+ function sortObjectArraysDeep(v) {
10593
+ if (Array.isArray(v)) return sortUnorderedObjectArray(v.map(sortObjectArraysDeep));
10594
+ if (v && typeof v === "object") {
10595
+ const out = {};
10596
+ for (const [k, val] of Object.entries(v)) out[k] = sortObjectArraysDeep(val);
10597
+ return out;
10598
+ }
10599
+ return v;
10507
10600
  }
10508
10601
  const DELTA_IDENTITY_FIELDS = [
10509
10602
  "Key",