cdk-real-drift 0.29.1 → 0.30.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,11 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { existsSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
3
- import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
4
- import { dirname, isAbsolute, join, resolve } from "node:path";
5
- import { pid } from "node:process";
6
- import { YAMLSeq, isSeq, parse, parseDocument } from "yaml";
7
3
  import { GetCallerIdentityCommand, STSClient } from "@aws-sdk/client-sts";
8
- import { createCredentialChain, fromEnv, fromNodeProviderChain } from "@aws-sdk/credential-providers";
4
+ import { createCredentialChain, fromEnv, fromNodeProviderChain, fromTemporaryCredentials } from "@aws-sdk/credential-providers";
5
+ import { AsyncLocalStorage } from "node:async_hooks";
9
6
  import { NodeHttpHandler } from "@smithy/node-http-handler";
10
7
  import { Agent } from "node:http";
11
8
  import { Agent as Agent$1, get } from "node:https";
@@ -13,6 +10,10 @@ import { Agent as Agent$2 } from "agent-base";
13
10
  import { HttpProxyAgent } from "http-proxy-agent";
14
11
  import { HttpsProxyAgent } from "https-proxy-agent";
15
12
  import { getProxyForUrl } from "proxy-from-env";
13
+ import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
14
+ import { dirname, isAbsolute, join, resolve } from "node:path";
15
+ import { pid } from "node:process";
16
+ import { YAMLSeq, isSeq, parse, parseDocument } from "yaml";
16
17
  import { CloudControlClient, DeleteResourceCommand, GetResourceCommand, GetResourceRequestStatusCommand, UpdateResourceCommand } from "@aws-sdk/client-cloudcontrol";
17
18
  import { homedir } from "node:os";
18
19
  import { BaseCredentials, CdkAppMultiContext, NonInteractiveIoHost, StackSelectionStrategy, Toolkit } from "@aws-cdk/toolkit-lib";
@@ -76,56 +77,18 @@ import { CloudFrontClient, GetDistributionConfigCommand, UpdateDistributionComma
76
77
  import { DescribeSignalingChannelCommand, DescribeStreamCommand, KinesisVideoClient, UpdateDataRetentionCommand, UpdateSignalingChannelCommand, UpdateStreamStorageConfigurationCommand } from "@aws-sdk/client-kinesis-video";
77
78
  import { GetWebACLCommand, UpdateWebACLCommand, WAFV2Client } from "@aws-sdk/client-wafv2";
78
79
 
79
- // src/exit.ts
80
- function drain(stream) {
81
- return new Promise((resolve) => {
82
- if (stream.writableLength === 0 || stream.writableEnded) {
83
- resolve();
84
- return;
85
- }
86
- stream.write("", () => resolve());
87
- });
88
- }
89
- async function flushAndExit(code) {
90
- await Promise.all([drain(process.stdout), drain(process.stderr)]);
91
- process.exit(code);
92
- }
93
-
94
- // src/interrupt.ts
95
- let gatherActive = false;
96
- function setGatherActive(active) {
97
- gatherActive = active;
98
- }
99
- function interruptExitCode(code, active) {
100
- return active && (code === void 0 || code === 0) ? 130 : code ?? 0;
101
- }
102
- let installed = false;
103
- function installInterruptGuard() {
104
- if (installed) return;
105
- installed = true;
106
- const realExit = process.exit.bind(process);
107
- process.exit = (code) => realExit(interruptExitCode(code, gatherActive));
108
- const onSignal = (code) => () => {
109
- process.stderr.write("\x1B[?25h");
110
- return realExit(code);
111
- };
112
- process.on("SIGINT", onSignal(130));
113
- process.on("SIGTERM", onSignal(143));
114
- const onFatal = (kind) => (err) => {
115
- process.stderr.write("\x1B[?25h");
116
- const detail = err instanceof Error ? err.stack ?? err.message : String(err);
117
- console.error(`error: ${kind}: ${detail}`);
118
- realExit(2);
119
- };
120
- process.on("unhandledRejection", onFatal("unhandled rejection"));
121
- process.on("uncaughtException", onFatal("uncaught exception"));
122
- }
123
-
124
80
  // src/aws-errors.ts
125
81
  function isStackNotDeployed(e) {
82
+ if (e instanceof AssumeRoleError) return false;
126
83
  const msg = e?.message ?? String(e);
127
84
  return /does not exist/i.test(msg) || /ValidationError/i.test(msg) && /stack/i.test(msg);
128
85
  }
86
+ var AssumeRoleError = class extends Error {
87
+ constructor(message) {
88
+ super(message);
89
+ this.name = "AssumeRoleError";
90
+ }
91
+ };
129
92
  var StackNotCheckableError = class extends Error {
130
93
  constructor(message) {
131
94
  super(message);
@@ -200,6 +163,96 @@ function isResourceNotFoundError(e) {
200
163
  const code = e?.Code ?? "";
201
164
  return NOT_FOUND_ERROR_NAMES.has(code);
202
165
  }
166
+ /**
167
+ * The stderr line for an error that escaped a verb (src/cli.ts' top-level catch). Pure so it
168
+ * is testable — cli.ts runs main() on import. An AssumeRoleError passes through verbatim: it
169
+ * names the role and the fix, and its STS text ("security token", "not authorized") would
170
+ * otherwise be rewritten into the generic credentials / access-denied hints, dropping both.
171
+ */
172
+ function topLevelErrorMessage(e) {
173
+ const msg = e?.message ?? String(e);
174
+ if (e instanceof AssumeRoleError) return `error: ${msg}`;
175
+ if (/credential|could not load cred|security token/i.test(msg)) return "error: no AWS credentials available. Configure them (aws configure / AWS_PROFILE / env vars) and retry.";
176
+ if (/stack/i.test(msg) && /(does not exist|ValidationError)/i.test(msg)) return "error: stack not found in this account/region. Check the stack name and --region.";
177
+ if (/AccessDenied|not authorized/i.test(msg)) return `error: access denied — ${msg}`;
178
+ return `error: ${msg}`;
179
+ }
180
+
181
+ // src/exit.ts
182
+ function drain(stream) {
183
+ return new Promise((resolve) => {
184
+ if (stream.writableLength === 0 || stream.writableEnded) {
185
+ resolve();
186
+ return;
187
+ }
188
+ stream.write("", () => resolve());
189
+ });
190
+ }
191
+ async function flushAndExit(code) {
192
+ await Promise.all([drain(process.stdout), drain(process.stderr)]);
193
+ process.exit(code);
194
+ }
195
+
196
+ // src/interrupt.ts
197
+ let gatherActive = false;
198
+ function setGatherActive(active) {
199
+ gatherActive = active;
200
+ }
201
+ function interruptExitCode(code, active) {
202
+ return active && (code === void 0 || code === 0) ? 130 : code ?? 0;
203
+ }
204
+ let installed = false;
205
+ function installInterruptGuard() {
206
+ if (installed) return;
207
+ installed = true;
208
+ const realExit = process.exit.bind(process);
209
+ process.exit = (code) => realExit(interruptExitCode(code, gatherActive));
210
+ const onSignal = (code) => () => {
211
+ process.stderr.write("\x1B[?25h");
212
+ return realExit(code);
213
+ };
214
+ process.on("SIGINT", onSignal(130));
215
+ process.on("SIGTERM", onSignal(143));
216
+ const onFatal = (kind) => (err) => {
217
+ process.stderr.write("\x1B[?25h");
218
+ const detail = err instanceof Error ? err.stack ?? err.message : String(err);
219
+ console.error(`error: ${kind}: ${detail}`);
220
+ realExit(2);
221
+ };
222
+ process.on("unhandledRejection", onFatal("unhandled rejection"));
223
+ process.on("uncaughtException", onFatal("uncaught exception"));
224
+ }
225
+
226
+ // src/read/assume-role-arn.ts
227
+ /** The placeholders an `--assume-role` value may carry. */
228
+ const ASSUME_ROLE_PLACEHOLDERS = ["{account}", "{region}"];
229
+ const ROLE_ARN_RE = /^arn:aws(?:-[a-z]+)*:iam::\d{12}:role\/(?:[\w+=,.@-]+\/)*[\w+=,.@-]+$/;
230
+ function substitute(template, account, region) {
231
+ return template.replaceAll("{account}", account).replaceAll("{region}", region);
232
+ }
233
+ /**
234
+ * Validate an `--assume-role` value at parse time (before any synth or AWS call), so a
235
+ * malformed value fails the whole run with exit 2 instead of erroring once per stack.
236
+ * Throws with a message naming the flag.
237
+ */
238
+ function validateAssumeRoleTemplate(template) {
239
+ const probe = substitute(template, "123456789012", "us-east-1");
240
+ const leftover = /\{[^}]*\}/.exec(probe);
241
+ if (leftover) throw new Error(`--assume-role: unknown placeholder "${leftover[0]}" in "${template}" — only ${ASSUME_ROLE_PLACEHOLDERS.join(" and ")} are supported`);
242
+ if (!ROLE_ARN_RE.test(probe)) throw new Error(`--assume-role: "${template}" is not an IAM role ARN (expected arn:aws:iam::<account>:role/<name>; ${ASSUME_ROLE_PLACEHOLDERS.join(" / ")} placeholders allowed)`);
243
+ }
244
+ /** Whether a RESOLVED value is an IAM role ARN. */
245
+ function isRoleArn(arn) {
246
+ return ROLE_ARN_RE.test(arn);
247
+ }
248
+ /** Whether the template needs the stack's account to resolve. */
249
+ function needsAccount(template) {
250
+ return template.includes("{account}");
251
+ }
252
+ /** Resolve the template for ONE stack. `account` must be a concrete 12-digit id. */
253
+ function resolveAssumeRoleArn(template, account, region) {
254
+ return substitute(template, account, region);
255
+ }
203
256
 
204
257
  // src/revert/transient.ts
205
258
  const RETRY_HINT = "the resource is still applying a previous update — retry in a few minutes";
@@ -287,6 +340,7 @@ async function retryTransient(op, opts = {}) {
287
340
  const VALUE_FLAGS = /* @__PURE__ */ new Set([
288
341
  "--region",
289
342
  "--profile",
343
+ "--assume-role",
290
344
  "--app",
291
345
  "-a",
292
346
  "-c",
@@ -320,6 +374,7 @@ const canonicalFlag = (flag) => CANONICAL_FLAG[flag] ?? flag;
320
374
  const GLOBAL_FLAGS = [
321
375
  "--region",
322
376
  "--profile",
377
+ "--assume-role",
323
378
  "--app",
324
379
  "--context",
325
380
  "--all",
@@ -413,41 +468,357 @@ function parseCommonArgs(args, verb) {
413
468
  }
414
469
  throw new Error(`unknown option "${a}" — see cdkrd --help`);
415
470
  }
416
- if (verb !== void 0) {
417
- const allowed = ALLOWED_FLAGS_BY_VERB[verb];
418
- for (const flag of found) if (!allowed.has(canonicalFlag(flag))) throw new Error(`option "${flag}" is not valid for the \`${verb}\` command — see cdkrd --help`);
419
- if (waitMs !== void 0 && !allowed.has("--wait")) throw new Error(`option "--wait" is not valid for the \`${verb}\` command — see cdkrd --help`);
471
+ if (verb !== void 0) {
472
+ const allowed = ALLOWED_FLAGS_BY_VERB[verb];
473
+ for (const flag of found) if (!allowed.has(canonicalFlag(flag))) throw new Error(`option "${flag}" is not valid for the \`${verb}\` command — see cdkrd --help`);
474
+ if (waitMs !== void 0 && !allowed.has("--wait")) throw new Error(`option "--wait" is not valid for the \`${verb}\` command — see cdkrd --help`);
475
+ }
476
+ const has = (flag) => found.has(flag);
477
+ const scopes = [
478
+ "--pre-deploy",
479
+ "--declared-only",
480
+ "--undeclared-only"
481
+ ].filter(has);
482
+ if (scopes.length > 1) throw new Error(`${scopes.join(" and ")} are mutually exclusive — see cdkrd --help`);
483
+ if (values["--profile"] !== void 0) process.env.CDKRD_EXPLICIT_PROFILE = "1";
484
+ const parsed = {
485
+ stackNames,
486
+ all: has("--all"),
487
+ context,
488
+ region: values["--region"] ?? process.env.AWS_REGION ?? process.env.AWS_DEFAULT_REGION,
489
+ profile: values["--profile"] ?? process.env.AWS_PROFILE ?? process.env.AWS_DEFAULT_PROFILE,
490
+ app: values["--app"] ?? process.env.CDKRD_APP,
491
+ json: has("--json"),
492
+ fail: has("--fail"),
493
+ strict: has("--strict"),
494
+ showAll: has("--show-all"),
495
+ yes: has("--yes") || has("-y"),
496
+ preDeploy: has("--pre-deploy"),
497
+ undeclaredOnly: has("--undeclared-only"),
498
+ declaredOnly: has("--declared-only"),
499
+ removeUnrecorded: has("--remove-unrecorded"),
500
+ force: has("--force"),
501
+ verbose: has("--verbose") || has("-v"),
502
+ waitMs
503
+ };
504
+ parsed.noPrompt = has("--no-prompt");
505
+ const assumeRole = values["--assume-role"] ?? (process.env.CDKRD_ASSUME_ROLE || void 0);
506
+ if (assumeRole !== void 0) {
507
+ validateAssumeRoleTemplate(assumeRole);
508
+ parsed.assumeRole = assumeRole;
509
+ }
510
+ return parsed;
511
+ }
512
+
513
+ // src/read/proxy-routing-agent.ts
514
+ /**
515
+ * An `http.Agent` that routes each request through the environment's proxy, or
516
+ * direct, according to `HTTPS_PROXY` / `HTTP_PROXY` / `NO_PROXY` (#1841).
517
+ *
518
+ * WHY A ROUTING AGENT AND NOT A PLAIN PROXY AGENT
519
+ *
520
+ * `NodeHttpHandler` picks its agent by PROTOCOL alone — `httpsAgent` for an
521
+ * `https:` request, `httpAgent` otherwise — and never consults the request's
522
+ * host. `https-proxy-agent` does not read `NO_PROXY` either. So a statically
523
+ * chosen proxy agent cannot express "this host is exempt", which is the whole
524
+ * of what `NO_PROXY` means. Deciding per REQUEST is the only place the host is
525
+ * known, and `agent-base` gives us that hook: when `connect()` returns an
526
+ * `http.Agent` rather than a socket, the base class delegates the request to it
527
+ * via `socket.addRequest(req, connectOpts)`.
528
+ *
529
+ * KEEP-ALIVE NEEDS BOTH LAYERS, for different reasons. Sockets POOL on
530
+ * whichever agent `connect()` hands back, so the INNER agents carry
531
+ * `keepAlive` (and `maxSockets`) to do the pooling. But Node's
532
+ * `ClientRequest` decides the `Connection:` header from the agent handed to
533
+ * the REQUEST — this one — and with a default outer agent
534
+ * (`keepAlive: false`, `maxSockets: Infinity`) it stamps `Connection: close`
535
+ * on every request, so the response teardown destroys the socket before the
536
+ * inner pool ever keeps it (measured: two sequential proxied SDK calls opened
537
+ * two CONNECT tunnels; with the outer `keepAlive` they share one). Hence the
538
+ * constructor passes `keepAlive: true` UP as well; the outer `maxSockets`
539
+ * stays unlimited on purpose — concurrency is bounded by the inner agents,
540
+ * and an outer bound would add agent-base's fake-socket accounting for no
541
+ * benefit.
542
+ *
543
+ * WHY THE INNER CACHE IS PER INSTANCE
544
+ *
545
+ * Node's `Agent.prototype.destroy()` walks `[this.freeSockets, this.sockets]`,
546
+ * and the second is the ACTIVE set — it aborts in-flight requests, not just
547
+ * idle sockets. `NodeHttpHandler.destroy()` forwards to `httpAgent` and
548
+ * `httpsAgent` unconditionally, external instances included, and cdkrd calls
549
+ * `client.destroy()` (the region probe in `commands/resolve-stacks.ts` does
550
+ * today, and nothing stops a future site). A module-global inner cache would
551
+ * therefore let one client's teardown kill another client's live request —
552
+ * which is also why `clientRequestHandler()` in `read/client-config.ts` builds
553
+ * a FRESH routing agent per client rather than sharing one. The cache is
554
+ * scoped to `this` and {@link destroy} forwards to the inner agents — without
555
+ * that forwarding the tunneled sockets would outlive the client and keep the
556
+ * process alive.
557
+ *
558
+ * The cost of not sharing is duplicate CONNECT + TLS handshakes where two
559
+ * clients talk to the same host. Pooling is per host either way, so sharing
560
+ * could never remove the FIRST handshake to each distinct AWS endpoint. This
561
+ * is also what the SDK already does: it builds a `keepAlive` agent per client
562
+ * on the unproxied path.
563
+ */
564
+ /**
565
+ * Applied to every inner agent.
566
+ *
567
+ * The SDK sets these itself, but ONLY when it is handed a plain option bag —
568
+ * an external `Agent` instance is passed through untouched
569
+ * (`@smithy/node-http-handler`'s `NodeHttpHandler` constructor). Since a
570
+ * routing agent IS such an instance, omitting them would silently drop
571
+ * connection reuse for every proxied run, and a concurrent `check` (gather.ts
572
+ * reads a whole stack with pooled concurrency) would renegotiate TLS per
573
+ * request.
574
+ */
575
+ const INNER_AGENT_OPTIONS = {
576
+ keepAlive: true,
577
+ maxSockets: 50
578
+ };
579
+ /**
580
+ * Build the absolute URL `getProxyForUrl` needs from what `connect()` is given.
581
+ *
582
+ * An IPv6 literal is bracketed, or the `host:port` join produces a string no
583
+ * URL parser accepts (`https://::1:443`) and `NO_PROXY` could never match an
584
+ * IPv6 entry. Unreachable with AWS hostnames; handled because the alternative
585
+ * is a silent wrong answer rather than an error.
586
+ */
587
+ function requestUrl(options) {
588
+ const secure = options.secureEndpoint;
589
+ const rawHost = options.host ?? "localhost";
590
+ const host = rawHost.includes(":") && !rawHost.startsWith("[") ? `[${rawHost}]` : rawHost;
591
+ const port = options.port ?? (secure ? 443 : 80);
592
+ return `${secure ? "https" : "http"}://${host}:${port}`;
593
+ }
594
+ var ProxyRoutingAgent = class extends Agent$2 {
595
+ constructor() {
596
+ super({ keepAlive: true });
597
+ }
598
+ /**
599
+ * Inner agents by `<scheme>|<proxy url or "direct">`.
600
+ *
601
+ * Keyed on the proxy URL and not merely on "proxied or not" because
602
+ * `NO_PROXY` is not the only thing that varies per host: `HTTP_PROXY` and
603
+ * `HTTPS_PROXY` may name different proxies, and a single agent bound to one
604
+ * of them would quietly send the other scheme's traffic to the wrong place.
605
+ */
606
+ innerAgents = /* @__PURE__ */ new Map();
607
+ connect(_req, options) {
608
+ const secure = options.secureEndpoint;
609
+ const proxyUrl = getProxyForUrl(requestUrl(options));
610
+ const key = `${secure ? "https" : "http"}|${proxyUrl || "direct"}`;
611
+ const cached = this.innerAgents.get(key);
612
+ if (cached) return cached;
613
+ const agent = createInnerAgent(secure, proxyUrl);
614
+ this.innerAgents.set(key, agent);
615
+ return agent;
616
+ }
617
+ destroy() {
618
+ for (const agent of this.innerAgents.values()) agent.destroy();
619
+ this.innerAgents.clear();
620
+ super.destroy();
621
+ }
622
+ };
623
+ function createInnerAgent(secure, proxyUrl) {
624
+ if (!proxyUrl) return secure ? new Agent$1(INNER_AGENT_OPTIONS) : new Agent(INNER_AGENT_OPTIONS);
625
+ return secure ? new HttpsProxyAgent(proxyUrl, INNER_AGENT_OPTIONS) : new HttpProxyAgent(proxyUrl, INNER_AGENT_OPTIONS);
626
+ }
627
+
628
+ // src/read/client-config.ts
629
+ /** Port of toolkit-lib awscli-compatible `shouldPrioritizeEnv()` (env creds win over profile). */
630
+ function shouldPrioritizeEnv() {
631
+ if (process.env.CDKRD_EXPLICIT_PROFILE) return false;
632
+ const id = process.env.AWS_ACCESS_KEY_ID || process.env.AMAZON_ACCESS_KEY_ID;
633
+ const key = process.env.AWS_SECRET_ACCESS_KEY || process.env.AMAZON_SECRET_ACCESS_KEY;
634
+ return !!id && !!key;
635
+ }
636
+ const CLIENT_REQUEST_HANDLER = {
637
+ connectionTimeout: 6e3,
638
+ requestTimeout: 6e4,
639
+ throwOnRequestTimeout: true
640
+ };
641
+ const PROXY_ENV_VARS = [
642
+ "HTTPS_PROXY",
643
+ "https_proxy",
644
+ "HTTP_PROXY",
645
+ "http_proxy",
646
+ "ALL_PROXY",
647
+ "all_proxy"
648
+ ];
649
+ let proxyConfigured;
650
+ /** Whether any proxy environment variable is set (memoized parse; see resetProxyConfig). */
651
+ function isProxyConfigured() {
652
+ if (proxyConfigured === void 0) {
653
+ let configured = false;
654
+ for (const name of PROXY_ENV_VARS) {
655
+ const value = process.env[name];
656
+ if (value === void 0 || value === "") continue;
657
+ if (value.trim() === "") throw new Error(`${name} is set to whitespace only. Set it to a proxy URL (e.g. http://proxy.example:8080) or unset it.`);
658
+ if (/^socks/i.test(value.trim())) throw new Error(`${name} names a SOCKS proxy, which cdkrd does not support (HTTP(S) proxies only). Use an http:// or https:// proxy URL, or unset ${name}.`);
659
+ if (!value.includes("://")) throw new Error(`${name} has no scheme. Set it to a full proxy URL (e.g. http://proxy.example:8080) or unset ${name}.`);
660
+ configured = true;
661
+ }
662
+ proxyConfigured = configured;
663
+ }
664
+ return proxyConfigured;
665
+ }
666
+ function clientRequestHandler() {
667
+ if (!isProxyConfigured()) return CLIENT_REQUEST_HANDLER;
668
+ const agent = new ProxyRoutingAgent();
669
+ return new NodeHttpHandler({
670
+ ...CLIENT_REQUEST_HANDLER,
671
+ httpAgent: agent,
672
+ httpsAgent: agent
673
+ });
674
+ }
675
+ const AMBIENT_CREDENTIALS = (awsIdentityProperties) => {
676
+ const requestHandler = clientRequestHandler();
677
+ return (shouldPrioritizeEnv() ? createCredentialChain(fromEnv(), fromNodeProviderChain({ clientConfig: { requestHandler } })) : fromNodeProviderChain({ clientConfig: { requestHandler } }))(awsIdentityProperties);
678
+ };
679
+ const roleScope = new AsyncLocalStorage();
680
+ /**
681
+ * Key prefix for a cache that outlives one stack and holds account- or credential-bound
682
+ * state (a client, an account-level default): '' outside an `--assume-role` scope, else the
683
+ * resolved role ARN — which embeds the account, so two stacks in one region but different
684
+ * accounts never share an entry.
685
+ */
686
+ function credentialScopeKey() {
687
+ return roleScope.getStore()?.roleArn ?? "";
688
+ }
689
+ const CLIENT_CREDENTIALS = (awsIdentityProperties) => {
690
+ const scope = roleScope.getStore();
691
+ return scope ? scope.provider(awsIdentityProperties) : AMBIENT_CREDENTIALS(awsIdentityProperties);
692
+ };
693
+ const CLIENT_TIMEOUTS = {
694
+ credentials: CLIENT_CREDENTIALS,
695
+ get requestHandler() {
696
+ return clientRequestHandler();
697
+ }
698
+ };
699
+ const READ_RETRY = {
700
+ maxAttempts: 10,
701
+ retryMode: "adaptive",
702
+ credentials: CLIENT_CREDENTIALS,
703
+ get requestHandler() {
704
+ return clientRequestHandler();
705
+ }
706
+ };
707
+
708
+ // src/read/assume-role.ts
709
+ const REFRESH_BEFORE_EXPIRY_MS = 3e5;
710
+ /**
711
+ * Memoize a credential provider: one in-flight call shared by every caller, the result
712
+ * reused until it is within REFRESH_BEFORE_EXPIRY_MS of expiring. A FAILED call is not
713
+ * cached (the next stack retries once). Without this every client would call
714
+ * sts:AssumeRole on its own — a stack builds dozens of clients, which is a throttle.
715
+ */
716
+ function memoizeCredentials(base) {
717
+ let value;
718
+ let inflight;
719
+ const fresh = (c) => c.expiration === void 0 || c.expiration.getTime() - Date.now() > REFRESH_BEFORE_EXPIRY_MS;
720
+ return () => {
721
+ if (value && fresh(value)) return Promise.resolve(value);
722
+ inflight ??= base().then((c) => {
723
+ value = c;
724
+ return c;
725
+ }).finally(() => {
726
+ inflight = void 0;
727
+ });
728
+ return inflight;
729
+ };
730
+ }
731
+ function describeAssumeFailure(roleArn, e) {
732
+ const msg = e?.message ?? String(e);
733
+ const name = e?.name ?? "";
734
+ const denied = /AccessDenied|not authorized/i.test(`${name} ${msg}`);
735
+ return `cannot assume role ${roleArn} (--assume-role): ${msg}` + (denied ? " — the calling identity needs sts:AssumeRole on this role, and the trust policy of the role must allow that identity" : "");
736
+ }
737
+ const providers = /* @__PURE__ */ new Map();
738
+ function providerFor(roleArn, region, verb) {
739
+ const key = `${roleArn}|${region}`;
740
+ let p = providers.get(key);
741
+ if (!p) {
742
+ const assume = fromTemporaryCredentials({
743
+ params: {
744
+ RoleArn: roleArn,
745
+ RoleSessionName: `cdkrd-${verb}`
746
+ },
747
+ masterCredentials: AMBIENT_CREDENTIALS,
748
+ clientConfig: {
749
+ region,
750
+ requestHandler: clientRequestHandler()
751
+ }
752
+ });
753
+ const memo = memoizeCredentials(async () => {
754
+ try {
755
+ return await assume();
756
+ } catch (e) {
757
+ throw new AssumeRoleError(describeAssumeFailure(roleArn, e));
758
+ }
759
+ });
760
+ p = () => memo();
761
+ providers.set(key, p);
762
+ }
763
+ return p;
764
+ }
765
+ let ambientAccount;
766
+ async function resolveAmbientAccount(region) {
767
+ ambientAccount ??= (async () => {
768
+ try {
769
+ return (await new STSClient({
770
+ region,
771
+ ...CLIENT_TIMEOUTS,
772
+ credentials: AMBIENT_CREDENTIALS
773
+ }).send(new GetCallerIdentityCommand({}))).Account;
774
+ } catch {
775
+ return;
776
+ }
777
+ })();
778
+ const account = await ambientAccount;
779
+ if (account === void 0) ambientAccount = void 0;
780
+ return account;
781
+ }
782
+ const failing = (roleArn, error) => ({
783
+ roleArn,
784
+ provider: () => Promise.reject(error),
785
+ error
786
+ });
787
+ /**
788
+ * Build the `--assume-role` scope for ONE stack. `undefined` when the flag is not set (the
789
+ * verb then runs exactly as before, on the ambient credentials). Never throws: a failure is
790
+ * carried on `scope.error`, which `enterRoleScope` raises after entering the scope.
791
+ */
792
+ async function stackRoleScope(template, stack, verb) {
793
+ if (template === void 0) return void 0;
794
+ let account = stack.account;
795
+ if (account === void 0 && needsAccount(template)) {
796
+ account = await resolveAmbientAccount(stack.region);
797
+ if (account === void 0) return failing(template, new AssumeRoleError(`cannot resolve {account} in --assume-role ${template}: the stack has no env.account and sts:GetCallerIdentity failed for the calling identity`));
798
+ }
799
+ const roleArn = resolveAssumeRoleArn(template, account ?? "", stack.region);
800
+ if (!isRoleArn(roleArn)) return failing(roleArn, new AssumeRoleError(`--assume-role resolved to ${roleArn}, which is not an IAM role ARN`));
801
+ const provider = providerFor(roleArn, stack.region, verb);
802
+ try {
803
+ await provider();
804
+ } catch (e) {
805
+ return failing(roleArn, e instanceof Error ? e : new AssumeRoleError(String(e)));
420
806
  }
421
- const has = (flag) => found.has(flag);
422
- const scopes = [
423
- "--pre-deploy",
424
- "--declared-only",
425
- "--undeclared-only"
426
- ].filter(has);
427
- if (scopes.length > 1) throw new Error(`${scopes.join(" and ")} are mutually exclusive — see cdkrd --help`);
428
- if (values["--profile"] !== void 0) process.env.CDKRD_EXPLICIT_PROFILE = "1";
429
- const parsed = {
430
- stackNames,
431
- all: has("--all"),
432
- context,
433
- region: values["--region"] ?? process.env.AWS_REGION ?? process.env.AWS_DEFAULT_REGION,
434
- profile: values["--profile"] ?? process.env.AWS_PROFILE ?? process.env.AWS_DEFAULT_PROFILE,
435
- app: values["--app"] ?? process.env.CDKRD_APP,
436
- json: has("--json"),
437
- fail: has("--fail"),
438
- strict: has("--strict"),
439
- showAll: has("--show-all"),
440
- yes: has("--yes") || has("-y"),
441
- preDeploy: has("--pre-deploy"),
442
- undeclaredOnly: has("--undeclared-only"),
443
- declaredOnly: has("--declared-only"),
444
- removeUnrecorded: has("--remove-unrecorded"),
445
- force: has("--force"),
446
- verbose: has("--verbose") || has("-v"),
447
- waitMs
807
+ return {
808
+ roleArn,
809
+ provider
448
810
  };
449
- parsed.noPrompt = has("--no-prompt");
450
- return parsed;
811
+ }
812
+ /**
813
+ * Enter `scope` for the rest of the calling stack iteration (AsyncLocalStorage.enterWith,
814
+ * so the verb's loop body needs no restructuring), then throw its error if the role could
815
+ * not be assumed. A no-op for `undefined` (no `--assume-role`). Call it SYNCHRONOUSLY in the
816
+ * loop body — entering inside an awaited helper would not reach the caller's continuation.
817
+ */
818
+ function enterRoleScope(scope) {
819
+ if (scope === void 0) return;
820
+ roleScope.enterWith(scope);
821
+ if (scope.error) throw scope.error;
451
822
  }
452
823
 
453
824
  // src/commands/glob-match.ts
@@ -563,6 +934,26 @@ function withinStackPath(constructPath, stackName) {
563
934
  return constructPath;
564
935
  }
565
936
 
937
+ // src/diff/coverage-gap.ts
938
+ /**
939
+ * A readGap caused by a FAILED read rather than by the property's nature (#1970):
940
+ * - `readFailed` — a supplement / enrichment read was denied or errored (AccessDenied,
941
+ * kms:Decrypt on a Lambda's environment, a throttle), so the property was never read;
942
+ * - `compareOnly` — the value WAS read, but the comparison needs a lookup that was denied
943
+ * (an `alias/aws/*` KMS key with kms:ListAliases unavailable), so a swap to a
944
+ * customer-managed key would go unseen.
945
+ * Both are fixable by granting a read permission, exactly like a `skipped` resource whose
946
+ * read was denied. Write-only / not-echoed / GetTemplate-masked readGaps are NOT gaps: no
947
+ * permission could make them readable.
948
+ */
949
+ function isCoverageReadGap(f) {
950
+ return f.tier === "readGap" && (f.readFailed === true || f.compareOnly === true);
951
+ }
952
+ /** A gap an `.cdkrd/ignore.yaml` rule acknowledged (#1969): still listed, never `--strict`-failing. */
953
+ function isAcknowledgedGap(f) {
954
+ return f.acknowledgedBy !== void 0;
955
+ }
956
+
566
957
  // src/config/config-file.ts
567
958
  const CONFIG_PATH = ".cdkrd/ignore.yaml";
568
959
  const KNOWN_KEYS = /* @__PURE__ */ new Set(["ignore"]);
@@ -570,9 +961,10 @@ const RULE_OBJECT_KEYS = /* @__PURE__ */ new Set([
570
961
  "path",
571
962
  "stack",
572
963
  "account",
573
- "region"
964
+ "region",
965
+ "resourceType"
574
966
  ]);
575
- const FILE_HEADER = "# cdkrd ignore rules — properties cdkrd should stop reporting as drift.\n# Each rule: { path, stack?, account?, region? }; `path` is a\n# \"<constructPath|logicalId>.<property>\" glob, the scopes narrow WHERE it applies.\n# Add a comment above a rule to record WHY it is ignored.\n";
967
+ const FILE_HEADER = "# cdkrd ignore rules — properties cdkrd should stop reporting as drift.\n# Each rule: { path, stack?, account?, region?, resourceType? }; `path` is a\n# \"<constructPath|logicalId>.<property>\" glob, the scopes narrow WHERE it applies.\n# Add a comment above a rule to record WHY it is ignored.\n";
576
968
  function looksUtf16(buf, nulAtOddIndex) {
577
969
  const n = Math.min(buf.length, 64);
578
970
  if (n < 2) return false;
@@ -660,13 +1052,16 @@ function isUniversalPath(path) {
660
1052
  */
661
1053
  function validateIgnoreEntry(entry, index) {
662
1054
  const at = `${CONFIG_PATH}: "ignore"[${index}]`;
663
- if (typeof entry !== "object" || entry === null || Array.isArray(entry)) throw new Error(`${at} must be a mapping { path, stack?, account?, region? }`);
1055
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) throw new Error(`${at} must be a mapping { path, stack?, account?, region?, resourceType? }`);
664
1056
  const obj = entry;
665
1057
  const unknown = Object.keys(obj).filter((k) => !RULE_OBJECT_KEYS.has(k));
666
- if (unknown.length > 0) throw new Error(`${at}: unknown key(s) ${unknown.map((k) => `"${k}"`).join(", ")} — known keys: "path", "stack", "account", "region"`);
1058
+ if (unknown.length > 0) throw new Error(`${at}: unknown key(s) ${unknown.map((k) => `"${k}"`).join(", ")} — known keys: "path", "stack", "account", "region", "resourceType"`);
667
1059
  if (typeof obj.path !== "string") throw new Error(`${at}: "path" is required and must be a string`);
668
1060
  if (obj.path === "") throw new Error(`${at}: "path" must not be empty`);
669
- if (isUniversalPath(obj.path)) throw new Error(`${at}: "path" must not be an all-wildcard pattern ("${obj.path}") — it would ignore every finding; name at least one literal path segment`);
1061
+ if (typeof obj.resourceType !== "undefined" && typeof obj.resourceType !== "string") throw new Error(`${at}: "resourceType" must be a string`);
1062
+ if (obj.resourceType === "") throw new Error(`${at}: "resourceType" must not be empty (omit it to match any type)`);
1063
+ const exactType = typeof obj.resourceType === "string" && !isGlob(obj.resourceType);
1064
+ if (isUniversalPath(obj.path) && !exactType) throw new Error(`${at}: "path" must not be an all-wildcard pattern ("${obj.path}") — it would ignore every finding; name at least one literal path segment (or scope it with an exact "resourceType")`);
670
1065
  for (const k of [
671
1066
  "stack",
672
1067
  "account",
@@ -729,7 +1124,8 @@ function ruleKey(r) {
729
1124
  r.path,
730
1125
  r.stack ?? null,
731
1126
  r.account ?? null,
732
- r.region ?? null
1127
+ r.region ?? null,
1128
+ r.resourceType ?? null
733
1129
  ]);
734
1130
  }
735
1131
  /** A rule as a plain object with keys in canonical order (path, stack, account, region),
@@ -739,6 +1135,7 @@ function orderedRule(r) {
739
1135
  if (r.stack !== void 0) o.stack = r.stack;
740
1136
  if (r.account !== void 0) o.account = r.account;
741
1137
  if (r.region !== void 0) o.region = r.region;
1138
+ if (r.resourceType !== void 0) o.resourceType = r.resourceType;
742
1139
  return o;
743
1140
  }
744
1141
  /**
@@ -864,14 +1261,16 @@ function parseIgnoreRule(entry) {
864
1261
  const scope = [
865
1262
  entry.stack !== void 0 ? `stack:${entry.stack}` : void 0,
866
1263
  entry.account !== void 0 ? `account:${entry.account}` : void 0,
867
- entry.region !== void 0 ? `region:${entry.region}` : void 0
1264
+ entry.region !== void 0 ? `region:${entry.region}` : void 0,
1265
+ entry.resourceType !== void 0 ? `resourceType:${entry.resourceType}` : void 0
868
1266
  ].filter((s) => s !== void 0);
869
1267
  return {
870
1268
  raw: scope.length > 0 ? `${entry.path} (${scope.join(", ")})` : entry.path,
871
1269
  pathPattern: entry.path,
872
1270
  stackGlob: entry.stack,
873
1271
  accountGlob: entry.account,
874
- regionGlob: entry.region
1272
+ regionGlob: entry.region,
1273
+ resourceTypeGlob: entry.resourceType
875
1274
  };
876
1275
  }
877
1276
  /**
@@ -922,7 +1321,8 @@ function applyIgnores(findings, scope, config) {
922
1321
  const { stackName, accountId, region } = scope;
923
1322
  const rules = config.ignore.map(parseIgnoreRule);
924
1323
  return findings.map((f) => {
925
- if (f.tier !== "declared" && f.tier !== "undeclared" && f.tier !== "added") return f;
1324
+ const gap = f.tier === "skipped" || isCoverageReadGap(f);
1325
+ if (f.tier !== "declared" && f.tier !== "undeclared" && f.tier !== "added" && !gap) return f;
926
1326
  const suffix = f.path ? `.${f.path}` : "";
927
1327
  const wholeResource = f.tier === "added";
928
1328
  const targets = [`${f.logicalId}${suffix}`];
@@ -930,8 +1330,12 @@ function applyIgnores(findings, scope, config) {
930
1330
  targets.push(`${withinStackPath(f.constructPath, stackName)}${suffix}`);
931
1331
  targets.push(`${f.constructPath}${suffix}`);
932
1332
  }
933
- const hit = rules.find((r) => (r.stackGlob === void 0 || matchesGlob(r.stackGlob, stackName)) && (r.accountGlob === void 0 || matchesGlob(r.accountGlob, accountId)) && (r.regionGlob === void 0 || matchesGlob(r.regionGlob, region)) && targets.some((t) => pathMatches(r.pathPattern, t, wholeResource)));
1333
+ const hit = rules.find((r) => (r.stackGlob === void 0 || matchesGlob(r.stackGlob, stackName)) && (r.accountGlob === void 0 || matchesGlob(r.accountGlob, accountId)) && (r.regionGlob === void 0 || matchesGlob(r.regionGlob, region)) && (r.resourceTypeGlob === void 0 || matchesGlob(r.resourceTypeGlob, f.resourceType)) && targets.some((t) => pathMatches(r.pathPattern, t, wholeResource)));
934
1334
  if (!hit) return f;
1335
+ if (gap) return {
1336
+ ...f,
1337
+ acknowledgedBy: hit.raw
1338
+ };
935
1339
  const { unrecorded: _unrecorded, ...rest } = f;
936
1340
  return {
937
1341
  ...rest,
@@ -942,187 +1346,6 @@ function applyIgnores(findings, scope, config) {
942
1346
  });
943
1347
  }
944
1348
 
945
- // src/read/proxy-routing-agent.ts
946
- /**
947
- * An `http.Agent` that routes each request through the environment's proxy, or
948
- * direct, according to `HTTPS_PROXY` / `HTTP_PROXY` / `NO_PROXY` (#1841).
949
- *
950
- * WHY A ROUTING AGENT AND NOT A PLAIN PROXY AGENT
951
- *
952
- * `NodeHttpHandler` picks its agent by PROTOCOL alone — `httpsAgent` for an
953
- * `https:` request, `httpAgent` otherwise — and never consults the request's
954
- * host. `https-proxy-agent` does not read `NO_PROXY` either. So a statically
955
- * chosen proxy agent cannot express "this host is exempt", which is the whole
956
- * of what `NO_PROXY` means. Deciding per REQUEST is the only place the host is
957
- * known, and `agent-base` gives us that hook: when `connect()` returns an
958
- * `http.Agent` rather than a socket, the base class delegates the request to it
959
- * via `socket.addRequest(req, connectOpts)`.
960
- *
961
- * KEEP-ALIVE NEEDS BOTH LAYERS, for different reasons. Sockets POOL on
962
- * whichever agent `connect()` hands back, so the INNER agents carry
963
- * `keepAlive` (and `maxSockets`) to do the pooling. But Node's
964
- * `ClientRequest` decides the `Connection:` header from the agent handed to
965
- * the REQUEST — this one — and with a default outer agent
966
- * (`keepAlive: false`, `maxSockets: Infinity`) it stamps `Connection: close`
967
- * on every request, so the response teardown destroys the socket before the
968
- * inner pool ever keeps it (measured: two sequential proxied SDK calls opened
969
- * two CONNECT tunnels; with the outer `keepAlive` they share one). Hence the
970
- * constructor passes `keepAlive: true` UP as well; the outer `maxSockets`
971
- * stays unlimited on purpose — concurrency is bounded by the inner agents,
972
- * and an outer bound would add agent-base's fake-socket accounting for no
973
- * benefit.
974
- *
975
- * WHY THE INNER CACHE IS PER INSTANCE
976
- *
977
- * Node's `Agent.prototype.destroy()` walks `[this.freeSockets, this.sockets]`,
978
- * and the second is the ACTIVE set — it aborts in-flight requests, not just
979
- * idle sockets. `NodeHttpHandler.destroy()` forwards to `httpAgent` and
980
- * `httpsAgent` unconditionally, external instances included, and cdkrd calls
981
- * `client.destroy()` (the region probe in `commands/resolve-stacks.ts` does
982
- * today, and nothing stops a future site). A module-global inner cache would
983
- * therefore let one client's teardown kill another client's live request —
984
- * which is also why `clientRequestHandler()` in `read/client-config.ts` builds
985
- * a FRESH routing agent per client rather than sharing one. The cache is
986
- * scoped to `this` and {@link destroy} forwards to the inner agents — without
987
- * that forwarding the tunneled sockets would outlive the client and keep the
988
- * process alive.
989
- *
990
- * The cost of not sharing is duplicate CONNECT + TLS handshakes where two
991
- * clients talk to the same host. Pooling is per host either way, so sharing
992
- * could never remove the FIRST handshake to each distinct AWS endpoint. This
993
- * is also what the SDK already does: it builds a `keepAlive` agent per client
994
- * on the unproxied path.
995
- */
996
- /**
997
- * Applied to every inner agent.
998
- *
999
- * The SDK sets these itself, but ONLY when it is handed a plain option bag —
1000
- * an external `Agent` instance is passed through untouched
1001
- * (`@smithy/node-http-handler`'s `NodeHttpHandler` constructor). Since a
1002
- * routing agent IS such an instance, omitting them would silently drop
1003
- * connection reuse for every proxied run, and a concurrent `check` (gather.ts
1004
- * reads a whole stack with pooled concurrency) would renegotiate TLS per
1005
- * request.
1006
- */
1007
- const INNER_AGENT_OPTIONS = {
1008
- keepAlive: true,
1009
- maxSockets: 50
1010
- };
1011
- /**
1012
- * Build the absolute URL `getProxyForUrl` needs from what `connect()` is given.
1013
- *
1014
- * An IPv6 literal is bracketed, or the `host:port` join produces a string no
1015
- * URL parser accepts (`https://::1:443`) and `NO_PROXY` could never match an
1016
- * IPv6 entry. Unreachable with AWS hostnames; handled because the alternative
1017
- * is a silent wrong answer rather than an error.
1018
- */
1019
- function requestUrl(options) {
1020
- const secure = options.secureEndpoint;
1021
- const rawHost = options.host ?? "localhost";
1022
- const host = rawHost.includes(":") && !rawHost.startsWith("[") ? `[${rawHost}]` : rawHost;
1023
- const port = options.port ?? (secure ? 443 : 80);
1024
- return `${secure ? "https" : "http"}://${host}:${port}`;
1025
- }
1026
- var ProxyRoutingAgent = class extends Agent$2 {
1027
- constructor() {
1028
- super({ keepAlive: true });
1029
- }
1030
- /**
1031
- * Inner agents by `<scheme>|<proxy url or "direct">`.
1032
- *
1033
- * Keyed on the proxy URL and not merely on "proxied or not" because
1034
- * `NO_PROXY` is not the only thing that varies per host: `HTTP_PROXY` and
1035
- * `HTTPS_PROXY` may name different proxies, and a single agent bound to one
1036
- * of them would quietly send the other scheme's traffic to the wrong place.
1037
- */
1038
- innerAgents = /* @__PURE__ */ new Map();
1039
- connect(_req, options) {
1040
- const secure = options.secureEndpoint;
1041
- const proxyUrl = getProxyForUrl(requestUrl(options));
1042
- const key = `${secure ? "https" : "http"}|${proxyUrl || "direct"}`;
1043
- const cached = this.innerAgents.get(key);
1044
- if (cached) return cached;
1045
- const agent = createInnerAgent(secure, proxyUrl);
1046
- this.innerAgents.set(key, agent);
1047
- return agent;
1048
- }
1049
- destroy() {
1050
- for (const agent of this.innerAgents.values()) agent.destroy();
1051
- this.innerAgents.clear();
1052
- super.destroy();
1053
- }
1054
- };
1055
- function createInnerAgent(secure, proxyUrl) {
1056
- if (!proxyUrl) return secure ? new Agent$1(INNER_AGENT_OPTIONS) : new Agent(INNER_AGENT_OPTIONS);
1057
- return secure ? new HttpsProxyAgent(proxyUrl, INNER_AGENT_OPTIONS) : new HttpProxyAgent(proxyUrl, INNER_AGENT_OPTIONS);
1058
- }
1059
-
1060
- // src/read/client-config.ts
1061
- /** Port of toolkit-lib awscli-compatible `shouldPrioritizeEnv()` (env creds win over profile). */
1062
- function shouldPrioritizeEnv() {
1063
- if (process.env.CDKRD_EXPLICIT_PROFILE) return false;
1064
- const id = process.env.AWS_ACCESS_KEY_ID || process.env.AMAZON_ACCESS_KEY_ID;
1065
- const key = process.env.AWS_SECRET_ACCESS_KEY || process.env.AMAZON_SECRET_ACCESS_KEY;
1066
- return !!id && !!key;
1067
- }
1068
- const CLIENT_REQUEST_HANDLER = {
1069
- connectionTimeout: 6e3,
1070
- requestTimeout: 6e4,
1071
- throwOnRequestTimeout: true
1072
- };
1073
- const PROXY_ENV_VARS = [
1074
- "HTTPS_PROXY",
1075
- "https_proxy",
1076
- "HTTP_PROXY",
1077
- "http_proxy",
1078
- "ALL_PROXY",
1079
- "all_proxy"
1080
- ];
1081
- let proxyConfigured;
1082
- /** Whether any proxy environment variable is set (memoized parse; see resetProxyConfig). */
1083
- function isProxyConfigured() {
1084
- if (proxyConfigured === void 0) {
1085
- let configured = false;
1086
- for (const name of PROXY_ENV_VARS) {
1087
- const value = process.env[name];
1088
- if (value === void 0 || value === "") continue;
1089
- if (value.trim() === "") throw new Error(`${name} is set to whitespace only. Set it to a proxy URL (e.g. http://proxy.example:8080) or unset it.`);
1090
- if (/^socks/i.test(value.trim())) throw new Error(`${name} names a SOCKS proxy, which cdkrd does not support (HTTP(S) proxies only). Use an http:// or https:// proxy URL, or unset ${name}.`);
1091
- if (!value.includes("://")) throw new Error(`${name} has no scheme. Set it to a full proxy URL (e.g. http://proxy.example:8080) or unset ${name}.`);
1092
- configured = true;
1093
- }
1094
- proxyConfigured = configured;
1095
- }
1096
- return proxyConfigured;
1097
- }
1098
- function clientRequestHandler() {
1099
- if (!isProxyConfigured()) return CLIENT_REQUEST_HANDLER;
1100
- const agent = new ProxyRoutingAgent();
1101
- return new NodeHttpHandler({
1102
- ...CLIENT_REQUEST_HANDLER,
1103
- httpAgent: agent,
1104
- httpsAgent: agent
1105
- });
1106
- }
1107
- const CLIENT_CREDENTIALS = (awsIdentityProperties) => {
1108
- const requestHandler = clientRequestHandler();
1109
- return (shouldPrioritizeEnv() ? createCredentialChain(fromEnv(), fromNodeProviderChain({ clientConfig: { requestHandler } })) : fromNodeProviderChain({ clientConfig: { requestHandler } }))(awsIdentityProperties);
1110
- };
1111
- const CLIENT_TIMEOUTS = {
1112
- credentials: CLIENT_CREDENTIALS,
1113
- get requestHandler() {
1114
- return clientRequestHandler();
1115
- }
1116
- };
1117
- const READ_RETRY = {
1118
- maxAttempts: 10,
1119
- retryMode: "adaptive",
1120
- credentials: CLIENT_CREDENTIALS,
1121
- get requestHandler() {
1122
- return clientRequestHandler();
1123
- }
1124
- };
1125
-
1126
1349
  // src/commands/account-gate.ts
1127
1350
  function mismatchTail(declaredAccount, verb) {
1128
1351
  return verb === "revert" ? `refusing to revert (run with account-${declaredAccount} credentials to revert it)` : `skipped (run with account-${declaredAccount} credentials to ${verb} it)`;
@@ -1208,19 +1431,16 @@ function classifyReadAccountMismatch(declaredAccount, readAccountId, verb = "che
1208
1431
  * is the backstop for that case, exactly as in check.
1209
1432
  */
1210
1433
  function createAccountGate(verb) {
1211
- let callerAccount;
1212
- let callerAccountResolved = false;
1434
+ const callerAccounts = /* @__PURE__ */ new Map();
1213
1435
  return {
1214
1436
  preRead: async (declaredAccount, region) => {
1215
1437
  if (!declaredAccount) return {
1216
1438
  skip: false,
1217
1439
  message: ""
1218
1440
  };
1219
- if (!callerAccountResolved) {
1220
- callerAccount = await resolveCallerAccount(region);
1221
- callerAccountResolved = true;
1222
- }
1223
- return classifyAccountMismatch(declaredAccount, callerAccount, verb);
1441
+ const key = credentialScopeKey();
1442
+ if (!callerAccounts.has(key)) callerAccounts.set(key, await resolveCallerAccount(region));
1443
+ return classifyAccountMismatch(declaredAccount, callerAccounts.get(key), verb);
1224
1444
  },
1225
1445
  postRead: (declaredAccount, readAccountId) => classifyReadAccountMismatch(declaredAccount, readAccountId, verb)
1226
1446
  };
@@ -5853,7 +6073,8 @@ function isDefinitiveDenial(err) {
5853
6073
  return e.$metadata?.httpStatusCode === 403;
5854
6074
  }
5855
6075
  async function fetchManagedAliasTargets(region) {
5856
- const cached = cache$1.get(region);
6076
+ const key = `${credentialScopeKey()}|${region}`;
6077
+ const cached = cache$1.get(key);
5857
6078
  if (cached) return cached;
5858
6079
  const targets = {};
5859
6080
  try {
@@ -5874,7 +6095,7 @@ async function fetchManagedAliasTargets(region) {
5874
6095
  targets,
5875
6096
  denied: false
5876
6097
  };
5877
- cache$1.set(region, result);
6098
+ cache$1.set(key, result);
5878
6099
  return result;
5879
6100
  } catch (e) {
5880
6101
  if (isDefinitiveDenial(e)) {
@@ -5882,7 +6103,7 @@ async function fetchManagedAliasTargets(region) {
5882
6103
  targets: {},
5883
6104
  denied: true
5884
6105
  };
5885
- cache$1.set(region, result);
6106
+ cache$1.set(key, result);
5886
6107
  return result;
5887
6108
  }
5888
6109
  return {
@@ -7972,7 +8193,8 @@ function classifyResource(resource, liveRaw, schema, opts = {}) {
7972
8193
  logicalId,
7973
8194
  resourceType,
7974
8195
  path: p,
7975
- note: "supplement read failed — property unverifiable (grant the missing read permission)"
8196
+ note: "supplement read failed — property unverifiable (grant the missing read permission)",
8197
+ readFailed: true
7976
8198
  });
7977
8199
  for (const [k, v] of Object.entries(declared)) {
7978
8200
  if (v === UNRESOLVED || hasUnresolved(v)) {
@@ -7990,7 +8212,8 @@ function classifyResource(resource, liveRaw, schema, opts = {}) {
7990
8212
  logicalId,
7991
8213
  resourceType,
7992
8214
  path: k,
7993
- note: "supplement read failed — property unverifiable (grant the missing read permission)"
8215
+ note: "supplement read failed — property unverifiable (grant the missing read permission)",
8216
+ readFailed: true
7994
8217
  });
7995
8218
  continue;
7996
8219
  }
@@ -14996,7 +15219,7 @@ function describeTypeFailedWarning(resourceType, region) {
14996
15219
  }
14997
15220
  async function getSchemaInfoResult(client, resourceType) {
14998
15221
  const region = await client.config.region();
14999
- const cacheKey = `${region}\0${resourceType}`;
15222
+ const cacheKey = `${credentialScopeKey()}\0${region}\0${resourceType}`;
15000
15223
  const cached = cache.get(cacheKey);
15001
15224
  if (cached) return {
15002
15225
  info: cached,
@@ -15551,9 +15774,10 @@ async function fetchSgNamesByIds(region, ids) {
15551
15774
  return;
15552
15775
  }
15553
15776
  }
15777
+ const scopedKey = (key) => `${credentialScopeKey()}|${key}`;
15554
15778
  const defaultSgIdsCache = /* @__PURE__ */ new Map();
15555
15779
  async function fetchDefaultSgIds(region) {
15556
- const cached = defaultSgIdsCache.get(region);
15780
+ const cached = defaultSgIdsCache.get(scopedKey(region));
15557
15781
  if (cached) return cached;
15558
15782
  const ids = /* @__PURE__ */ new Set();
15559
15783
  try {
@@ -15577,12 +15801,12 @@ async function fetchDefaultSgIds(region) {
15577
15801
  } catch {
15578
15802
  return ids;
15579
15803
  }
15580
- defaultSgIdsCache.set(region, ids);
15804
+ defaultSgIdsCache.set(scopedKey(region), ids);
15581
15805
  return ids;
15582
15806
  }
15583
15807
  const defaultSubnetIdsCache = /* @__PURE__ */ new Map();
15584
15808
  async function fetchDefaultVpcSubnetIds(region) {
15585
- const cached = defaultSubnetIdsCache.get(region);
15809
+ const cached = defaultSubnetIdsCache.get(scopedKey(region));
15586
15810
  if (cached) return cached;
15587
15811
  const ids = /* @__PURE__ */ new Set();
15588
15812
  try {
@@ -15606,12 +15830,12 @@ async function fetchDefaultVpcSubnetIds(region) {
15606
15830
  } catch {
15607
15831
  return ids;
15608
15832
  }
15609
- defaultSubnetIdsCache.set(region, ids);
15833
+ defaultSubnetIdsCache.set(scopedKey(region), ids);
15610
15834
  return ids;
15611
15835
  }
15612
15836
  const ecsContainerInsightsCache = /* @__PURE__ */ new Map();
15613
15837
  async function fetchEcsContainerInsightsDefault(region) {
15614
- if (ecsContainerInsightsCache.has(region)) return ecsContainerInsightsCache.get(region);
15838
+ if (ecsContainerInsightsCache.has(scopedKey(region))) return ecsContainerInsightsCache.get(scopedKey(region));
15615
15839
  try {
15616
15840
  const value = (await new ECSClient({
15617
15841
  region,
@@ -15620,7 +15844,7 @@ async function fetchEcsContainerInsightsDefault(region) {
15620
15844
  name: "containerInsights",
15621
15845
  effectiveSettings: true
15622
15846
  }))).settings?.find((s) => s.name === "containerInsights")?.value;
15623
- ecsContainerInsightsCache.set(region, value);
15847
+ ecsContainerInsightsCache.set(scopedKey(region), value);
15624
15848
  return value;
15625
15849
  } catch {
15626
15850
  return;
@@ -15628,13 +15852,13 @@ async function fetchEcsContainerInsightsDefault(region) {
15628
15852
  }
15629
15853
  const ssmParameterTierCache = /* @__PURE__ */ new Map();
15630
15854
  async function fetchSsmDefaultParameterTier(region) {
15631
- if (ssmParameterTierCache.has(region)) return ssmParameterTierCache.get(region);
15855
+ if (ssmParameterTierCache.has(scopedKey(region))) return ssmParameterTierCache.get(scopedKey(region));
15632
15856
  try {
15633
15857
  const value = (await new SSMClient({
15634
15858
  region,
15635
15859
  ...READ_RETRY
15636
15860
  }).send(new GetServiceSettingCommand({ SettingId: "/ssm/parameter-store/default-parameter-tier" }))).ServiceSetting?.SettingValue;
15637
- ssmParameterTierCache.set(region, value);
15861
+ ssmParameterTierCache.set(scopedKey(region), value);
15638
15862
  return value;
15639
15863
  } catch {
15640
15864
  return;
@@ -15642,13 +15866,13 @@ async function fetchSsmDefaultParameterTier(region) {
15642
15866
  }
15643
15867
  const ebsEncryptionByDefaultCache = /* @__PURE__ */ new Map();
15644
15868
  async function fetchEbsEncryptionByDefault(region) {
15645
- if (ebsEncryptionByDefaultCache.has(region)) return ebsEncryptionByDefaultCache.get(region);
15869
+ if (ebsEncryptionByDefaultCache.has(scopedKey(region))) return ebsEncryptionByDefaultCache.get(scopedKey(region));
15646
15870
  try {
15647
15871
  const value = (await new EC2Client({
15648
15872
  region,
15649
15873
  ...READ_RETRY
15650
15874
  }).send(new GetEbsEncryptionByDefaultCommand({}))).EbsEncryptionByDefault;
15651
- ebsEncryptionByDefaultCache.set(region, value);
15875
+ ebsEncryptionByDefaultCache.set(scopedKey(region), value);
15652
15876
  return value;
15653
15877
  } catch {
15654
15878
  return;
@@ -15656,7 +15880,7 @@ async function fetchEbsEncryptionByDefault(region) {
15656
15880
  }
15657
15881
  const ec2CreditDefaultCache = /* @__PURE__ */ new Map();
15658
15882
  async function fetchEc2FamilyCreditDefault(region, family) {
15659
- const cacheKey = `${region}|${family}`;
15883
+ const cacheKey = scopedKey(`${region}|${family}`);
15660
15884
  if (ec2CreditDefaultCache.has(cacheKey)) return ec2CreditDefaultCache.get(cacheKey);
15661
15885
  try {
15662
15886
  const value = (await new EC2Client({
@@ -15671,13 +15895,13 @@ async function fetchEc2FamilyCreditDefault(region, family) {
15671
15895
  }
15672
15896
  const rdsDefaultCaCache = /* @__PURE__ */ new Map();
15673
15897
  async function fetchRdsDefaultCaIdentifier(region) {
15674
- if (rdsDefaultCaCache.has(region)) return rdsDefaultCaCache.get(region);
15898
+ if (rdsDefaultCaCache.has(scopedKey(region))) return rdsDefaultCaCache.get(scopedKey(region));
15675
15899
  try {
15676
15900
  const value = ((await new RDSClient({
15677
15901
  region,
15678
15902
  ...READ_RETRY
15679
15903
  }).send(new DescribeCertificatesCommand({}))).Certificates ?? []).find((cert) => cert.CustomerOverride === true)?.CertificateIdentifier;
15680
- rdsDefaultCaCache.set(region, value);
15904
+ rdsDefaultCaCache.set(scopedKey(region), value);
15681
15905
  return value;
15682
15906
  } catch {
15683
15907
  return;
@@ -15685,7 +15909,7 @@ async function fetchRdsDefaultCaIdentifier(region) {
15685
15909
  }
15686
15910
  const dmsAllocatedStorageDefaultsCache = /* @__PURE__ */ new Map();
15687
15911
  async function fetchDmsAllocatedStorageDefaults(region) {
15688
- const cached = dmsAllocatedStorageDefaultsCache.get(region);
15912
+ const cached = dmsAllocatedStorageDefaultsCache.get(scopedKey(region));
15689
15913
  if (cached) return cached;
15690
15914
  const map = {};
15691
15915
  try {
@@ -15703,12 +15927,12 @@ async function fetchDmsAllocatedStorageDefaults(region) {
15703
15927
  marker = r.Marker;
15704
15928
  } while (marker);
15705
15929
  } catch {}
15706
- dmsAllocatedStorageDefaultsCache.set(region, map);
15930
+ dmsAllocatedStorageDefaultsCache.set(scopedKey(region), map);
15707
15931
  return map;
15708
15932
  }
15709
15933
  const instanceMetadataDefaultsCache = /* @__PURE__ */ new Map();
15710
15934
  async function fetchInstanceMetadataDefaults(region) {
15711
- if (instanceMetadataDefaultsCache.has(region)) return instanceMetadataDefaultsCache.get(region);
15935
+ if (instanceMetadataDefaultsCache.has(scopedKey(region))) return instanceMetadataDefaultsCache.get(scopedKey(region));
15712
15936
  try {
15713
15937
  const al = (await new EC2Client({
15714
15938
  region,
@@ -15720,7 +15944,7 @@ async function fetchInstanceMetadataDefaults(region) {
15720
15944
  if (al?.HttpEndpoint != null) out.HttpEndpoint = al.HttpEndpoint;
15721
15945
  if (al?.InstanceMetadataTags != null) out.InstanceMetadataTags = al.InstanceMetadataTags;
15722
15946
  const value = Object.keys(out).length > 0 ? out : void 0;
15723
- instanceMetadataDefaultsCache.set(region, value);
15947
+ instanceMetadataDefaultsCache.set(scopedKey(region), value);
15724
15948
  return value;
15725
15949
  } catch {
15726
15950
  return;
@@ -16628,9 +16852,9 @@ async function gatherFindings(stackName, region, templateOverride, recoveryTempl
16628
16852
  if (desired.resources.some((r) => usesManagedKmsAlias(r.declared) || typeNeedsManagedKeyResolution(r.resourceType))) {
16629
16853
  const resolved = await fetchManagedAliasTargets(region);
16630
16854
  kmsAliasTargets = resolved.targets;
16631
- const decision = kmsWarnDecision(region, resolved, kmsDeniedWarned.has(region), kmsTransientWarned.has(region));
16632
- if (decision.stampDenied) kmsDeniedWarned.add(region);
16633
- if (decision.stampTransient) kmsTransientWarned.add(region);
16855
+ const decision = kmsWarnDecision(region, resolved, kmsDeniedWarned.has(scopedKey(region)), kmsTransientWarned.has(scopedKey(region)));
16856
+ if (decision.stampDenied) kmsDeniedWarned.add(scopedKey(region));
16857
+ if (decision.stampTransient) kmsTransientWarned.add(scopedKey(region));
16634
16858
  if (decision.warning) console.error(decision.warning);
16635
16859
  }
16636
16860
  let defaultSgIds = /* @__PURE__ */ new Set();
@@ -18179,14 +18403,15 @@ function warnTemplateHashDrift(baseline, rawTemplate, stackName, warn = console.
18179
18403
  // src/read/deployed-source-hash.ts
18180
18404
  const s3Clients = /* @__PURE__ */ new Map();
18181
18405
  const fetchS3Sha256Base64 = async (ref, region) => {
18182
- let s3 = s3Clients.get(region);
18406
+ const key = `${credentialScopeKey()}|${region}`;
18407
+ let s3 = s3Clients.get(key);
18183
18408
  if (s3 === void 0) {
18184
18409
  s3 = new S3Client({
18185
18410
  region,
18186
18411
  followRegionRedirects: true,
18187
18412
  ...READ_RETRY
18188
18413
  });
18189
- s3Clients.set(region, s3);
18414
+ s3Clients.set(key, s3);
18190
18415
  }
18191
18416
  const body = (await s3.send(new GetObjectCommand({
18192
18417
  Bucket: ref.bucket,
@@ -18394,6 +18619,7 @@ function formatFinding(f, stackName = "") {
18394
18619
  const pathDisplay = f.attributeKey ? `${f.path}[${sanitizeForTerminal(f.attributeKey)}]` : f.path;
18395
18620
  let s = `${pathDisplay ? `${id}.${pathDisplay}` : id} (${f.resourceType})`;
18396
18621
  if (f.note) s += ` — ${sanitizeForTerminal(f.note)}`;
18622
+ if (f.acknowledgedBy !== void 0) s += ` — acknowledged by ignore rule "${sanitizeForTerminal(f.acknowledgedBy)}" (not a --strict failure)`;
18397
18623
  const rt = f.resourceType;
18398
18624
  const rd = (v) => redactValue(rt, f.path, v);
18399
18625
  if (f.tier === "declared") {
@@ -18558,10 +18784,15 @@ function report(rawFindings, header, opts = {}) {
18558
18784
  if (t === "atDefault") return `atDefault=${items.length} (undeclared values matching a known AWS default — not drift)`;
18559
18785
  if (t === "generated") return `generated=${items.length} (auto-generated identifiers not in your template, AWS-assigned at deploy — not drift)`;
18560
18786
  if (t === "readGap") {
18561
- const writeOnly = items.filter((f) => (f.note ?? "").includes("write-only")).length;
18562
- const masked = items.filter((f) => f.note === GETTEMPLATE_MASK_NOTE).length;
18563
- const notReturned = items.length - writeOnly - masked;
18787
+ const failed = items.filter((f) => isCoverageReadGap(f) && !isAcknowledgedGap(f)).length;
18788
+ const acked = items.filter((f) => isCoverageReadGap(f) && isAcknowledgedGap(f)).length;
18789
+ const byNature = items.filter((f) => !isCoverageReadGap(f));
18790
+ const writeOnly = byNature.filter((f) => (f.note ?? "").includes("write-only")).length;
18791
+ const masked = byNature.filter((f) => f.note === GETTEMPLATE_MASK_NOTE).length;
18792
+ const notReturned = byNature.length - writeOnly - masked;
18564
18793
  const parts = [
18794
+ ...failed > 0 ? [`${failed} read failed — coverage incomplete (grant the read, or acknowledge it)`] : [],
18795
+ ...acked > 0 ? [`${acked} read failed, acknowledged in .cdkrd/ignore.yaml`] : [],
18565
18796
  ...notReturned > 0 ? [`${notReturned} not returned by AWS`] : [],
18566
18797
  ...writeOnly > 0 ? [`${writeOnly} write-only`] : [],
18567
18798
  ...masked > 0 ? [`${masked} non-ASCII masked by GetTemplate`] : []
@@ -18572,14 +18803,18 @@ function report(rawFindings, header, opts = {}) {
18572
18803
  if (t === "skipped") return `skipped=${items.length} — NOT checked (coverage incomplete: ${groupReasons(items)})`;
18573
18804
  return `${t}=${items.length} (${groupReasons(items)})`;
18574
18805
  };
18575
- const skippedSummaryFor = (items) => {
18576
- if (!opts.preDeploy) return [summaryFor("skipped", items)];
18806
+ const skippedSummaryFor = (all) => {
18807
+ const isPending = (f) => !!opts.preDeploy && isPendingCreationSkip$1(f);
18808
+ const acked = all.filter((f) => isAcknowledgedGap(f) && !isPending(f));
18809
+ const items = all.filter((f) => !isAcknowledgedGap(f) || isPending(f));
18810
+ const ackLine = acked.length > 0 ? [`acknowledged-skip=${acked.length} — NOT checked, acknowledged in .cdkrd/ignore.yaml (${groupReasons(acked)})`] : [];
18811
+ if (!opts.preDeploy) return [...items.length > 0 ? [summaryFor("skipped", items)] : [], ...ackLine];
18577
18812
  const pending = items.filter(isPendingCreationSkip$1);
18578
18813
  const gaps = items.filter((f) => !isPendingCreationSkip$1(f));
18579
18814
  const lines = [];
18580
18815
  if (gaps.length > 0) lines.push(summaryFor("skipped", gaps));
18581
18816
  if (pending.length > 0) lines.push(`pending creation=${pending.length} (not yet deployed — the next deploy will create them, not a coverage gap)`);
18582
- return lines;
18817
+ return [...lines, ...ackLine];
18583
18818
  };
18584
18819
  const summaries = INFO_TIERS.filter((t) => !isExpanded(t)).flatMap((t) => {
18585
18820
  const items = byTier(t);
@@ -23192,6 +23427,10 @@ async function runRecord(args) {
23192
23427
  continue;
23193
23428
  }
23194
23429
  try {
23430
+ enterRoleScope(await stackRoleScope(a.assumeRole, {
23431
+ account,
23432
+ region
23433
+ }, "record"));
23195
23434
  const mismatch = await accountGate.preRead(account, region);
23196
23435
  if (mismatch.skip) {
23197
23436
  console.error(`note: ${stackName}: ${mismatch.message}`);
@@ -23333,6 +23572,10 @@ async function runIgnore(args) {
23333
23572
  continue;
23334
23573
  }
23335
23574
  try {
23575
+ enterRoleScope(await stackRoleScope(a.assumeRole, {
23576
+ account,
23577
+ region
23578
+ }, "ignore"));
23336
23579
  const mismatch = await accountGate.preRead(account, region);
23337
23580
  if (mismatch.skip) {
23338
23581
  console.error(`note: ${stackName}: ${mismatch.message}`);
@@ -23940,7 +24183,7 @@ function preDeployFindings(findings) {
23940
24183
  return findings.filter((f) => f.tier !== "undeclared" && f.tier !== "generated" && f.tier !== "atDefault" && f.tier !== "added");
23941
24184
  }
23942
24185
  function undeclaredOnlyFindings(findings) {
23943
- return findings.filter((f) => f.tier !== "declared" && f.tier !== "readGap" && f.tier !== "unresolved");
24186
+ return findings.filter((f) => f.tier !== "declared" && (f.tier !== "readGap" || isCoverageReadGap(f)) && f.tier !== "unresolved");
23944
24187
  }
23945
24188
  function nestedStackWarning(resources, stackName) {
23946
24189
  const nested = resources.filter((r) => r.resourceType === "AWS::CloudFormation::Stack");
@@ -23955,13 +24198,23 @@ function isCustomResourceSkip(f) {
23955
24198
  return f.tier === "skipped" && (f.resourceType === "AWS::CloudFormation::CustomResource" || f.resourceType.startsWith("Custom::"));
23956
24199
  }
23957
24200
  function coverageWarning(findings, stackName, preDeploy = false) {
23958
- const skipped = findings.filter((f) => f.tier === "skipped" && !(preDeploy && isPendingCreationSkip(f)));
24201
+ const skipped = findings.filter((f) => f.tier === "skipped" && !(preDeploy && isPendingCreationSkip(f)) && !isAcknowledgedGap(f));
23959
24202
  if (skipped.length === 0) return null;
23960
24203
  const names = skipped.map((f) => f.constructPath ? withinStackPath(f.constructPath, stackName) : f.logicalId).sort();
23961
24204
  const shown = names.slice(0, 10);
23962
24205
  const more = names.length > shown.length ? `, …(+${names.length - shown.length} more)` : "";
23963
24206
  return `warning: ${stackName}: ${skipped.length} resource(s) were NOT checked (coverage incomplete) — ${shown.join(", ")}${more}; see the skipped breakdown (--verbose)`;
23964
24207
  }
24208
+ function readFailureWarning(findings, stackName) {
24209
+ const gaps = findings.filter((f) => isCoverageReadGap(f) && !isAcknowledgedGap(f));
24210
+ if (gaps.length === 0) return null;
24211
+ const names = gaps.map((f) => {
24212
+ return `${f.constructPath ? withinStackPath(f.constructPath, stackName) : f.logicalId}.${f.path}`;
24213
+ }).sort();
24214
+ const shown = names.slice(0, 10);
24215
+ const more = names.length > shown.length ? `, …(+${names.length - shown.length} more)` : "";
24216
+ return `warning: ${stackName}: ${gaps.length} propert(ies) could NOT be read (coverage incomplete — grant the missing read permission, or acknowledge it in .cdkrd/ignore.yaml) — ${shown.join(", ")}${more}`;
24217
+ }
23965
24218
  function pendingCreationInfo(findings, stackName) {
23966
24219
  const pending = findings.filter(isPendingCreationSkip);
23967
24220
  if (pending.length === 0) return null;
@@ -23971,7 +24224,7 @@ function pendingCreationInfo(findings, stackName) {
23971
24224
  return `info: ${stackName}: ${pending.length} resource(s) not yet deployed — will be created by the next deploy (pending creation, not a coverage gap): ${shown.join(", ")}${more}`;
23972
24225
  }
23973
24226
  function hasCoverageGap(findings, resources, preDeploy = false) {
23974
- return findings.some((f) => f.tier === "skipped" && !(preDeploy && isPendingCreationSkip(f)) && !isCustomResourceSkip(f)) || resources.some((r) => r.resourceType === "AWS::CloudFormation::Stack");
24227
+ return findings.some((f) => !isAcknowledgedGap(f) && (f.tier === "skipped" && !(preDeploy && isPendingCreationSkip(f)) && !isCustomResourceSkip(f) || isCoverageReadGap(f))) || resources.some((r) => r.resourceType === "AWS::CloudFormation::Stack");
23975
24228
  }
23976
24229
  function strictCoverageExit(strict, findings, resources, preDeploy = false) {
23977
24230
  return strict && hasCoverageGap(findings, resources, preDeploy) ? 1 : 0;
@@ -24150,14 +24403,11 @@ async function runCheck(args) {
24150
24403
  };
24151
24404
  const separate = stackSeparator();
24152
24405
  const showProgress = !a.json && isInteractive();
24153
- let callerAccount;
24154
- let callerAccountResolved = false;
24406
+ const callerAccounts = /* @__PURE__ */ new Map();
24155
24407
  const ensureCallerAccount = async (region) => {
24156
- if (!callerAccountResolved) {
24157
- callerAccount = await resolveCallerAccount(region);
24158
- callerAccountResolved = true;
24159
- }
24160
- return callerAccount;
24408
+ const key = credentialScopeKey();
24409
+ if (!callerAccounts.has(key)) callerAccounts.set(key, await resolveCallerAccount(region));
24410
+ return callerAccounts.get(key);
24161
24411
  };
24162
24412
  for (const [idx, { stackName, region, account, template, localAssetHashes }] of stacks.entries()) {
24163
24413
  if (!region) {
@@ -24169,6 +24419,10 @@ async function runCheck(args) {
24169
24419
  }
24170
24420
  const posPrefix = a.json ? "" : positionPrefix(idx, stacks.length);
24171
24421
  try {
24422
+ enterRoleScope(await stackRoleScope(a.assumeRole, {
24423
+ account,
24424
+ region
24425
+ }, "check"));
24172
24426
  const mismatch = classifyAccountMismatch(account, await ensureCallerAccount(region));
24173
24427
  if (mismatch.skip) {
24174
24428
  console.error(`note: ${stackName}: ${mismatch.message}`);
@@ -24195,9 +24449,16 @@ async function runCheck(args) {
24195
24449
  }
24196
24450
  const nestedWarn = nestedStackWarning(desired.resources, stackName);
24197
24451
  if (nestedWarn) console.error(nestedWarn);
24452
+ const coverageFindings = applyIgnores(gathered.findings, {
24453
+ stackName,
24454
+ accountId: desired.accountId,
24455
+ region
24456
+ }, config);
24198
24457
  if (a.json) {
24199
- const covWarn = coverageWarning(gathered.findings, stackName, a.preDeploy);
24458
+ const covWarn = coverageWarning(coverageFindings, stackName, a.preDeploy);
24200
24459
  if (covWarn) console.error(covWarn);
24460
+ const readWarn = readFailureWarning(coverageFindings, stackName);
24461
+ if (readWarn) console.error(readWarn);
24201
24462
  }
24202
24463
  if (a.preDeploy) {
24203
24464
  const pendingInfo = pendingCreationInfo(gathered.findings, stackName);
@@ -24233,7 +24494,7 @@ async function runCheck(args) {
24233
24494
  });
24234
24495
  if (preDeployCode === 1) anyDrift = true;
24235
24496
  worst = Math.max(worst, finalCheckExit(preDeployCode, a.fail));
24236
- worst = Math.max(worst, strictCoverageExit(a.strict, gathered.findings, desired.resources, true));
24497
+ worst = Math.max(worst, strictCoverageExit(a.strict, coverageFindings, desired.resources, true));
24237
24498
  continue;
24238
24499
  }
24239
24500
  const baseline = a.showAll ? void 0 : await loadBaseline(stackName, desired.accountId, region);
@@ -24293,11 +24554,10 @@ async function runCheck(args) {
24293
24554
  else if (!baseline && !hasUnrecorded && !a.showAll && !a.preDeploy) console.error(`note: ${stackName}: no .cdkrd baseline yet — run \`cdkrd record\` to establish one (future out-of-band changes then report as drift).`);
24294
24555
  if (code === 1) anyDrift = true;
24295
24556
  worst = Math.max(worst, finalCheckExit(code, a.fail));
24296
- worst = Math.max(worst, strictCoverageExit(a.strict, gathered.findings, desired.resources));
24557
+ worst = Math.max(worst, strictCoverageExit(a.strict, coverageFindings, desired.resources));
24297
24558
  } catch (e) {
24298
24559
  if (isStackNotDeployed(e)) {
24299
- await ensureCallerAccount(region);
24300
- if (hasBaselineForStack(stackName, region, callerAccount)) {
24560
+ if (hasBaselineForStack(stackName, region, await ensureCallerAccount(region))) {
24301
24561
  const msg = "deployed baseline exists but the stack is gone — deleted out of band";
24302
24562
  const label = `${stackName} (${region})`;
24303
24563
  console.error(`[Drift] ${label}: ${msg}`);
@@ -24373,6 +24633,10 @@ async function runRevert(args) {
24373
24633
  continue;
24374
24634
  }
24375
24635
  try {
24636
+ enterRoleScope(await stackRoleScope(a.assumeRole, {
24637
+ account,
24638
+ region
24639
+ }, "revert"));
24376
24640
  const mismatch = await accountGate.preRead(account, region);
24377
24641
  if (mismatch.skip) {
24378
24642
  console.error(`error: ${stackName}: ${mismatch.message}`);
@@ -24509,6 +24773,12 @@ OPTIONS
24509
24773
  An env-agnostic stack with none of these falls back to
24510
24774
  the active --profile's configured region (~/.aws/config)
24511
24775
  --profile <p> AWS profile (or $AWS_PROFILE)
24776
+ --assume-role <arn> assume this IAM role (from the --profile / ambient
24777
+ credentials) for every AWS call (or $CDKRD_ASSUME_ROLE);
24778
+ {account} / {region} are filled per stack from the CDK
24779
+ app, e.g. 'arn:aws:iam::{account}:role/MyReadRole'.
24780
+ Session name cdkrd-<verb>. Synth still uses the ambient
24781
+ credentials, as cdk does
24512
24782
  -a, --app <cmd|cdk.out> CDK app command or pre-synthesized assembly dir
24513
24783
  (or $CDKRD_APP / cdk.json "app") — enables stack
24514
24784
  auto-discovery + construct-path output
@@ -24526,9 +24796,12 @@ OPTIONS
24526
24796
  still prompt and could hang). Non-TTY runs never prompt
24527
24797
  anyway; with --fail, --fail's exit-1 wins
24528
24798
  --strict (check) exit 1 when coverage is INCOMPLETE — any
24529
- resource skipped (unread) or a nested stack not
24799
+ resource skipped (unread), a property whose read
24800
+ failed (e.g. AccessDenied), or a nested stack not
24530
24801
  recursed into. A loud coverage warning always prints;
24531
- --strict makes it CI-failing. Orthogonal to --fail
24802
+ --strict makes it CI-failing. A known, intended gap
24803
+ acknowledged in .cdkrd/ignore.yaml stays listed but
24804
+ does not fail. Orthogonal to --fail
24532
24805
  --show-all (check) inventory mode: show ALL current undeclared
24533
24806
  state (not just changes since record)
24534
24807
  --verbose (check) expand informational tiers / (revert) the
@@ -24612,11 +24885,7 @@ async function main(argv) {
24612
24885
  installInterruptGuard();
24613
24886
  const argv = process.argv.slice(2);
24614
24887
  main(argv).then((code) => flushAndExit(code)).catch((e) => {
24615
- const msg = e?.message ?? String(e);
24616
- if (/credential|could not load cred|security token/i.test(msg)) console.error("error: no AWS credentials available. Configure them (aws configure / AWS_PROFILE / env vars) and retry.");
24617
- else if (/stack/i.test(msg) && /(does not exist|ValidationError)/i.test(msg)) console.error("error: stack not found in this account/region. Check the stack name and --region.");
24618
- else if (/AccessDenied|not authorized/i.test(msg)) console.error(`error: access denied — ${msg}`);
24619
- else console.error(`error: ${msg}`);
24888
+ console.error(topLevelErrorMessage(e));
24620
24889
  if (argv.includes("--json")) console.log("[]");
24621
24890
  return flushAndExit(2);
24622
24891
  });