cdk-real-drift 0.29.0 → 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",
@@ -411,43 +466,359 @@ function parseCommonArgs(args, verb) {
411
466
  waitMs = inlineValue === void 0 ? DEFAULT_WAIT_MS : parseDurationMs(inlineValue);
412
467
  continue;
413
468
  }
414
- throw new Error(`unknown option "${a}" — see cdkrd --help`);
415
- }
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`);
469
+ throw new Error(`unknown option "${a}" — see cdkrd --help`);
470
+ }
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
  };
@@ -2195,6 +2415,7 @@ function buildCorpusCase(resource, liveRaw, schema, opts, findings) {
2195
2415
  ...echoModel && resource.physicalId ? { clusterEchoModel: { [resource.physicalId]: echoModel } } : {},
2196
2416
  ...rdsOptCatalog && resource.physicalId ? { rdsOptionSettingDefaults: { [resource.physicalId]: rdsOptCatalog } } : {},
2197
2417
  ...gaListenerPort ? { siblingListenerPorts: gaListenerPort } : {},
2418
+ ...opts.supplementReadGapPaths && opts.supplementReadGapPaths.length > 0 ? { supplementReadGapPaths: [...opts.supplementReadGapPaths] } : {},
2198
2419
  ...dmsStorageDefault || ebsEncDefault ? { accountDefaults: {
2199
2420
  ...dmsStorageDefault ?? {},
2200
2421
  ...ebsEncDefault ?? {}
@@ -5852,7 +6073,8 @@ function isDefinitiveDenial(err) {
5852
6073
  return e.$metadata?.httpStatusCode === 403;
5853
6074
  }
5854
6075
  async function fetchManagedAliasTargets(region) {
5855
- const cached = cache$1.get(region);
6076
+ const key = `${credentialScopeKey()}|${region}`;
6077
+ const cached = cache$1.get(key);
5856
6078
  if (cached) return cached;
5857
6079
  const targets = {};
5858
6080
  try {
@@ -5873,7 +6095,7 @@ async function fetchManagedAliasTargets(region) {
5873
6095
  targets,
5874
6096
  denied: false
5875
6097
  };
5876
- cache$1.set(region, result);
6098
+ cache$1.set(key, result);
5877
6099
  return result;
5878
6100
  } catch (e) {
5879
6101
  if (isDefinitiveDenial(e)) {
@@ -5881,7 +6103,7 @@ async function fetchManagedAliasTargets(region) {
5881
6103
  targets: {},
5882
6104
  denied: true
5883
6105
  };
5884
- cache$1.set(region, result);
6106
+ cache$1.set(key, result);
5885
6107
  return result;
5886
6108
  }
5887
6109
  return {
@@ -7971,7 +8193,8 @@ function classifyResource(resource, liveRaw, schema, opts = {}) {
7971
8193
  logicalId,
7972
8194
  resourceType,
7973
8195
  path: p,
7974
- 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
7975
8198
  });
7976
8199
  for (const [k, v] of Object.entries(declared)) {
7977
8200
  if (v === UNRESOLVED || hasUnresolved(v)) {
@@ -7989,7 +8212,8 @@ function classifyResource(resource, liveRaw, schema, opts = {}) {
7989
8212
  logicalId,
7990
8213
  resourceType,
7991
8214
  path: k,
7992
- 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
7993
8217
  });
7994
8218
  continue;
7995
8219
  }
@@ -14704,7 +14928,13 @@ const supplementLambdaFunction = async ({ physicalId, region }) => {
14704
14928
  ...READ_RETRY
14705
14929
  }).send(new GetFunctionCommand({ FunctionName: name }));
14706
14930
  const sha = str$1(r.Configuration?.CodeSha256);
14707
- return sha !== void 0 ? { CodeSha256: sha } : void 0;
14931
+ const extra = sha !== void 0 ? { CodeSha256: sha } : void 0;
14932
+ const envError = r.Configuration?.Environment?.Error;
14933
+ if (envError === void 0) return extra;
14934
+ const code = envError.ErrorCode ?? "unknown error";
14935
+ const cause = /AccessDenied/i.test(code) ? "the caller likely lacks kms:Decrypt on the function's key" : "the function's KMS key is unusable";
14936
+ process.stderr.write(`[cdkrd] warning: AWS::Lambda::Function ${name}: environment variables unreadable (${code} — ${cause}) — treating Environment as an unverifiable read-gap\n`);
14937
+ return overrideReadGap(extra ?? {}, ["Environment"]);
14708
14938
  };
14709
14939
  const supplementGlueJob = async ({ physicalId, region }) => {
14710
14940
  const name = str$1(physicalId);
@@ -14989,7 +15219,7 @@ function describeTypeFailedWarning(resourceType, region) {
14989
15219
  }
14990
15220
  async function getSchemaInfoResult(client, resourceType) {
14991
15221
  const region = await client.config.region();
14992
- const cacheKey = `${region}\0${resourceType}`;
15222
+ const cacheKey = `${credentialScopeKey()}\0${region}\0${resourceType}`;
14993
15223
  const cached = cache.get(cacheKey);
14994
15224
  if (cached) return {
14995
15225
  info: cached,
@@ -15451,6 +15681,14 @@ async function readLive(cc, resource, region, accountId) {
15451
15681
  region,
15452
15682
  accountId
15453
15683
  });
15684
+ if (isOverrideReadResult(extra)) {
15685
+ Object.assign(live, extra.model);
15686
+ for (const p of extra.readGapPaths) delete live[p];
15687
+ return {
15688
+ live,
15689
+ readGapPaths: extra.readGapPaths
15690
+ };
15691
+ }
15454
15692
  if (extra) Object.assign(live, extra);
15455
15693
  } catch (e) {
15456
15694
  return {
@@ -15536,9 +15774,10 @@ async function fetchSgNamesByIds(region, ids) {
15536
15774
  return;
15537
15775
  }
15538
15776
  }
15777
+ const scopedKey = (key) => `${credentialScopeKey()}|${key}`;
15539
15778
  const defaultSgIdsCache = /* @__PURE__ */ new Map();
15540
15779
  async function fetchDefaultSgIds(region) {
15541
- const cached = defaultSgIdsCache.get(region);
15780
+ const cached = defaultSgIdsCache.get(scopedKey(region));
15542
15781
  if (cached) return cached;
15543
15782
  const ids = /* @__PURE__ */ new Set();
15544
15783
  try {
@@ -15562,12 +15801,12 @@ async function fetchDefaultSgIds(region) {
15562
15801
  } catch {
15563
15802
  return ids;
15564
15803
  }
15565
- defaultSgIdsCache.set(region, ids);
15804
+ defaultSgIdsCache.set(scopedKey(region), ids);
15566
15805
  return ids;
15567
15806
  }
15568
15807
  const defaultSubnetIdsCache = /* @__PURE__ */ new Map();
15569
15808
  async function fetchDefaultVpcSubnetIds(region) {
15570
- const cached = defaultSubnetIdsCache.get(region);
15809
+ const cached = defaultSubnetIdsCache.get(scopedKey(region));
15571
15810
  if (cached) return cached;
15572
15811
  const ids = /* @__PURE__ */ new Set();
15573
15812
  try {
@@ -15591,12 +15830,12 @@ async function fetchDefaultVpcSubnetIds(region) {
15591
15830
  } catch {
15592
15831
  return ids;
15593
15832
  }
15594
- defaultSubnetIdsCache.set(region, ids);
15833
+ defaultSubnetIdsCache.set(scopedKey(region), ids);
15595
15834
  return ids;
15596
15835
  }
15597
15836
  const ecsContainerInsightsCache = /* @__PURE__ */ new Map();
15598
15837
  async function fetchEcsContainerInsightsDefault(region) {
15599
- if (ecsContainerInsightsCache.has(region)) return ecsContainerInsightsCache.get(region);
15838
+ if (ecsContainerInsightsCache.has(scopedKey(region))) return ecsContainerInsightsCache.get(scopedKey(region));
15600
15839
  try {
15601
15840
  const value = (await new ECSClient({
15602
15841
  region,
@@ -15605,7 +15844,7 @@ async function fetchEcsContainerInsightsDefault(region) {
15605
15844
  name: "containerInsights",
15606
15845
  effectiveSettings: true
15607
15846
  }))).settings?.find((s) => s.name === "containerInsights")?.value;
15608
- ecsContainerInsightsCache.set(region, value);
15847
+ ecsContainerInsightsCache.set(scopedKey(region), value);
15609
15848
  return value;
15610
15849
  } catch {
15611
15850
  return;
@@ -15613,13 +15852,13 @@ async function fetchEcsContainerInsightsDefault(region) {
15613
15852
  }
15614
15853
  const ssmParameterTierCache = /* @__PURE__ */ new Map();
15615
15854
  async function fetchSsmDefaultParameterTier(region) {
15616
- if (ssmParameterTierCache.has(region)) return ssmParameterTierCache.get(region);
15855
+ if (ssmParameterTierCache.has(scopedKey(region))) return ssmParameterTierCache.get(scopedKey(region));
15617
15856
  try {
15618
15857
  const value = (await new SSMClient({
15619
15858
  region,
15620
15859
  ...READ_RETRY
15621
15860
  }).send(new GetServiceSettingCommand({ SettingId: "/ssm/parameter-store/default-parameter-tier" }))).ServiceSetting?.SettingValue;
15622
- ssmParameterTierCache.set(region, value);
15861
+ ssmParameterTierCache.set(scopedKey(region), value);
15623
15862
  return value;
15624
15863
  } catch {
15625
15864
  return;
@@ -15627,13 +15866,13 @@ async function fetchSsmDefaultParameterTier(region) {
15627
15866
  }
15628
15867
  const ebsEncryptionByDefaultCache = /* @__PURE__ */ new Map();
15629
15868
  async function fetchEbsEncryptionByDefault(region) {
15630
- if (ebsEncryptionByDefaultCache.has(region)) return ebsEncryptionByDefaultCache.get(region);
15869
+ if (ebsEncryptionByDefaultCache.has(scopedKey(region))) return ebsEncryptionByDefaultCache.get(scopedKey(region));
15631
15870
  try {
15632
15871
  const value = (await new EC2Client({
15633
15872
  region,
15634
15873
  ...READ_RETRY
15635
15874
  }).send(new GetEbsEncryptionByDefaultCommand({}))).EbsEncryptionByDefault;
15636
- ebsEncryptionByDefaultCache.set(region, value);
15875
+ ebsEncryptionByDefaultCache.set(scopedKey(region), value);
15637
15876
  return value;
15638
15877
  } catch {
15639
15878
  return;
@@ -15641,7 +15880,7 @@ async function fetchEbsEncryptionByDefault(region) {
15641
15880
  }
15642
15881
  const ec2CreditDefaultCache = /* @__PURE__ */ new Map();
15643
15882
  async function fetchEc2FamilyCreditDefault(region, family) {
15644
- const cacheKey = `${region}|${family}`;
15883
+ const cacheKey = scopedKey(`${region}|${family}`);
15645
15884
  if (ec2CreditDefaultCache.has(cacheKey)) return ec2CreditDefaultCache.get(cacheKey);
15646
15885
  try {
15647
15886
  const value = (await new EC2Client({
@@ -15656,13 +15895,13 @@ async function fetchEc2FamilyCreditDefault(region, family) {
15656
15895
  }
15657
15896
  const rdsDefaultCaCache = /* @__PURE__ */ new Map();
15658
15897
  async function fetchRdsDefaultCaIdentifier(region) {
15659
- if (rdsDefaultCaCache.has(region)) return rdsDefaultCaCache.get(region);
15898
+ if (rdsDefaultCaCache.has(scopedKey(region))) return rdsDefaultCaCache.get(scopedKey(region));
15660
15899
  try {
15661
15900
  const value = ((await new RDSClient({
15662
15901
  region,
15663
15902
  ...READ_RETRY
15664
15903
  }).send(new DescribeCertificatesCommand({}))).Certificates ?? []).find((cert) => cert.CustomerOverride === true)?.CertificateIdentifier;
15665
- rdsDefaultCaCache.set(region, value);
15904
+ rdsDefaultCaCache.set(scopedKey(region), value);
15666
15905
  return value;
15667
15906
  } catch {
15668
15907
  return;
@@ -15670,7 +15909,7 @@ async function fetchRdsDefaultCaIdentifier(region) {
15670
15909
  }
15671
15910
  const dmsAllocatedStorageDefaultsCache = /* @__PURE__ */ new Map();
15672
15911
  async function fetchDmsAllocatedStorageDefaults(region) {
15673
- const cached = dmsAllocatedStorageDefaultsCache.get(region);
15912
+ const cached = dmsAllocatedStorageDefaultsCache.get(scopedKey(region));
15674
15913
  if (cached) return cached;
15675
15914
  const map = {};
15676
15915
  try {
@@ -15688,12 +15927,12 @@ async function fetchDmsAllocatedStorageDefaults(region) {
15688
15927
  marker = r.Marker;
15689
15928
  } while (marker);
15690
15929
  } catch {}
15691
- dmsAllocatedStorageDefaultsCache.set(region, map);
15930
+ dmsAllocatedStorageDefaultsCache.set(scopedKey(region), map);
15692
15931
  return map;
15693
15932
  }
15694
15933
  const instanceMetadataDefaultsCache = /* @__PURE__ */ new Map();
15695
15934
  async function fetchInstanceMetadataDefaults(region) {
15696
- if (instanceMetadataDefaultsCache.has(region)) return instanceMetadataDefaultsCache.get(region);
15935
+ if (instanceMetadataDefaultsCache.has(scopedKey(region))) return instanceMetadataDefaultsCache.get(scopedKey(region));
15697
15936
  try {
15698
15937
  const al = (await new EC2Client({
15699
15938
  region,
@@ -15705,7 +15944,7 @@ async function fetchInstanceMetadataDefaults(region) {
15705
15944
  if (al?.HttpEndpoint != null) out.HttpEndpoint = al.HttpEndpoint;
15706
15945
  if (al?.InstanceMetadataTags != null) out.InstanceMetadataTags = al.InstanceMetadataTags;
15707
15946
  const value = Object.keys(out).length > 0 ? out : void 0;
15708
- instanceMetadataDefaultsCache.set(region, value);
15947
+ instanceMetadataDefaultsCache.set(scopedKey(region), value);
15709
15948
  return value;
15710
15949
  } catch {
15711
15950
  return;
@@ -16613,9 +16852,9 @@ async function gatherFindings(stackName, region, templateOverride, recoveryTempl
16613
16852
  if (desired.resources.some((r) => usesManagedKmsAlias(r.declared) || typeNeedsManagedKeyResolution(r.resourceType))) {
16614
16853
  const resolved = await fetchManagedAliasTargets(region);
16615
16854
  kmsAliasTargets = resolved.targets;
16616
- const decision = kmsWarnDecision(region, resolved, kmsDeniedWarned.has(region), kmsTransientWarned.has(region));
16617
- if (decision.stampDenied) kmsDeniedWarned.add(region);
16618
- 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));
16619
16858
  if (decision.warning) console.error(decision.warning);
16620
16859
  }
16621
16860
  let defaultSgIds = /* @__PURE__ */ new Set();
@@ -16698,9 +16937,13 @@ async function gatherFindings(stackName, region, templateOverride, recoveryTempl
16698
16937
  for (const r of desired.resources) {
16699
16938
  const resourceFindings = await classifyRead(cfn, r, reads.get(r.logicalId), schemas, classifyOpts);
16700
16939
  findings.push(...resourceFindings);
16701
- const live = reads.get(r.logicalId)?.live;
16940
+ const read = reads.get(r.logicalId);
16941
+ const live = read?.live;
16702
16942
  const schema = schemas.get(r.resourceType);
16703
- if (corpusDir && live && schema) await recordCorpusCase(corpusDir, buildCorpusCase(r, live, schema, classifyOpts, resourceFindings));
16943
+ if (corpusDir && live && schema) await recordCorpusCase(corpusDir, buildCorpusCase(r, live, schema, {
16944
+ ...classifyOpts,
16945
+ supplementReadGapPaths: read?.readGapPaths
16946
+ }, resourceFindings));
16704
16947
  }
16705
16948
  return {
16706
16949
  desired,
@@ -18160,14 +18403,15 @@ function warnTemplateHashDrift(baseline, rawTemplate, stackName, warn = console.
18160
18403
  // src/read/deployed-source-hash.ts
18161
18404
  const s3Clients = /* @__PURE__ */ new Map();
18162
18405
  const fetchS3Sha256Base64 = async (ref, region) => {
18163
- let s3 = s3Clients.get(region);
18406
+ const key = `${credentialScopeKey()}|${region}`;
18407
+ let s3 = s3Clients.get(key);
18164
18408
  if (s3 === void 0) {
18165
18409
  s3 = new S3Client({
18166
18410
  region,
18167
18411
  followRegionRedirects: true,
18168
18412
  ...READ_RETRY
18169
18413
  });
18170
- s3Clients.set(region, s3);
18414
+ s3Clients.set(key, s3);
18171
18415
  }
18172
18416
  const body = (await s3.send(new GetObjectCommand({
18173
18417
  Bucket: ref.bucket,
@@ -18375,6 +18619,7 @@ function formatFinding(f, stackName = "") {
18375
18619
  const pathDisplay = f.attributeKey ? `${f.path}[${sanitizeForTerminal(f.attributeKey)}]` : f.path;
18376
18620
  let s = `${pathDisplay ? `${id}.${pathDisplay}` : id} (${f.resourceType})`;
18377
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)`;
18378
18623
  const rt = f.resourceType;
18379
18624
  const rd = (v) => redactValue(rt, f.path, v);
18380
18625
  if (f.tier === "declared") {
@@ -18539,10 +18784,15 @@ function report(rawFindings, header, opts = {}) {
18539
18784
  if (t === "atDefault") return `atDefault=${items.length} (undeclared values matching a known AWS default — not drift)`;
18540
18785
  if (t === "generated") return `generated=${items.length} (auto-generated identifiers not in your template, AWS-assigned at deploy — not drift)`;
18541
18786
  if (t === "readGap") {
18542
- const writeOnly = items.filter((f) => (f.note ?? "").includes("write-only")).length;
18543
- const masked = items.filter((f) => f.note === GETTEMPLATE_MASK_NOTE).length;
18544
- 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;
18545
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`] : [],
18546
18796
  ...notReturned > 0 ? [`${notReturned} not returned by AWS`] : [],
18547
18797
  ...writeOnly > 0 ? [`${writeOnly} write-only`] : [],
18548
18798
  ...masked > 0 ? [`${masked} non-ASCII masked by GetTemplate`] : []
@@ -18553,14 +18803,18 @@ function report(rawFindings, header, opts = {}) {
18553
18803
  if (t === "skipped") return `skipped=${items.length} — NOT checked (coverage incomplete: ${groupReasons(items)})`;
18554
18804
  return `${t}=${items.length} (${groupReasons(items)})`;
18555
18805
  };
18556
- const skippedSummaryFor = (items) => {
18557
- 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];
18558
18812
  const pending = items.filter(isPendingCreationSkip$1);
18559
18813
  const gaps = items.filter((f) => !isPendingCreationSkip$1(f));
18560
18814
  const lines = [];
18561
18815
  if (gaps.length > 0) lines.push(summaryFor("skipped", gaps));
18562
18816
  if (pending.length > 0) lines.push(`pending creation=${pending.length} (not yet deployed — the next deploy will create them, not a coverage gap)`);
18563
- return lines;
18817
+ return [...lines, ...ackLine];
18564
18818
  };
18565
18819
  const summaries = INFO_TIERS.filter((t) => !isExpanded(t)).flatMap((t) => {
18566
18820
  const items = byTier(t);
@@ -23173,6 +23427,10 @@ async function runRecord(args) {
23173
23427
  continue;
23174
23428
  }
23175
23429
  try {
23430
+ enterRoleScope(await stackRoleScope(a.assumeRole, {
23431
+ account,
23432
+ region
23433
+ }, "record"));
23176
23434
  const mismatch = await accountGate.preRead(account, region);
23177
23435
  if (mismatch.skip) {
23178
23436
  console.error(`note: ${stackName}: ${mismatch.message}`);
@@ -23314,6 +23572,10 @@ async function runIgnore(args) {
23314
23572
  continue;
23315
23573
  }
23316
23574
  try {
23575
+ enterRoleScope(await stackRoleScope(a.assumeRole, {
23576
+ account,
23577
+ region
23578
+ }, "ignore"));
23317
23579
  const mismatch = await accountGate.preRead(account, region);
23318
23580
  if (mismatch.skip) {
23319
23581
  console.error(`note: ${stackName}: ${mismatch.message}`);
@@ -23921,7 +24183,7 @@ function preDeployFindings(findings) {
23921
24183
  return findings.filter((f) => f.tier !== "undeclared" && f.tier !== "generated" && f.tier !== "atDefault" && f.tier !== "added");
23922
24184
  }
23923
24185
  function undeclaredOnlyFindings(findings) {
23924
- 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");
23925
24187
  }
23926
24188
  function nestedStackWarning(resources, stackName) {
23927
24189
  const nested = resources.filter((r) => r.resourceType === "AWS::CloudFormation::Stack");
@@ -23936,13 +24198,23 @@ function isCustomResourceSkip(f) {
23936
24198
  return f.tier === "skipped" && (f.resourceType === "AWS::CloudFormation::CustomResource" || f.resourceType.startsWith("Custom::"));
23937
24199
  }
23938
24200
  function coverageWarning(findings, stackName, preDeploy = false) {
23939
- 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));
23940
24202
  if (skipped.length === 0) return null;
23941
24203
  const names = skipped.map((f) => f.constructPath ? withinStackPath(f.constructPath, stackName) : f.logicalId).sort();
23942
24204
  const shown = names.slice(0, 10);
23943
24205
  const more = names.length > shown.length ? `, …(+${names.length - shown.length} more)` : "";
23944
24206
  return `warning: ${stackName}: ${skipped.length} resource(s) were NOT checked (coverage incomplete) — ${shown.join(", ")}${more}; see the skipped breakdown (--verbose)`;
23945
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
+ }
23946
24218
  function pendingCreationInfo(findings, stackName) {
23947
24219
  const pending = findings.filter(isPendingCreationSkip);
23948
24220
  if (pending.length === 0) return null;
@@ -23952,7 +24224,7 @@ function pendingCreationInfo(findings, stackName) {
23952
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}`;
23953
24225
  }
23954
24226
  function hasCoverageGap(findings, resources, preDeploy = false) {
23955
- 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");
23956
24228
  }
23957
24229
  function strictCoverageExit(strict, findings, resources, preDeploy = false) {
23958
24230
  return strict && hasCoverageGap(findings, resources, preDeploy) ? 1 : 0;
@@ -24131,14 +24403,11 @@ async function runCheck(args) {
24131
24403
  };
24132
24404
  const separate = stackSeparator();
24133
24405
  const showProgress = !a.json && isInteractive();
24134
- let callerAccount;
24135
- let callerAccountResolved = false;
24406
+ const callerAccounts = /* @__PURE__ */ new Map();
24136
24407
  const ensureCallerAccount = async (region) => {
24137
- if (!callerAccountResolved) {
24138
- callerAccount = await resolveCallerAccount(region);
24139
- callerAccountResolved = true;
24140
- }
24141
- return callerAccount;
24408
+ const key = credentialScopeKey();
24409
+ if (!callerAccounts.has(key)) callerAccounts.set(key, await resolveCallerAccount(region));
24410
+ return callerAccounts.get(key);
24142
24411
  };
24143
24412
  for (const [idx, { stackName, region, account, template, localAssetHashes }] of stacks.entries()) {
24144
24413
  if (!region) {
@@ -24150,6 +24419,10 @@ async function runCheck(args) {
24150
24419
  }
24151
24420
  const posPrefix = a.json ? "" : positionPrefix(idx, stacks.length);
24152
24421
  try {
24422
+ enterRoleScope(await stackRoleScope(a.assumeRole, {
24423
+ account,
24424
+ region
24425
+ }, "check"));
24153
24426
  const mismatch = classifyAccountMismatch(account, await ensureCallerAccount(region));
24154
24427
  if (mismatch.skip) {
24155
24428
  console.error(`note: ${stackName}: ${mismatch.message}`);
@@ -24176,9 +24449,16 @@ async function runCheck(args) {
24176
24449
  }
24177
24450
  const nestedWarn = nestedStackWarning(desired.resources, stackName);
24178
24451
  if (nestedWarn) console.error(nestedWarn);
24452
+ const coverageFindings = applyIgnores(gathered.findings, {
24453
+ stackName,
24454
+ accountId: desired.accountId,
24455
+ region
24456
+ }, config);
24179
24457
  if (a.json) {
24180
- const covWarn = coverageWarning(gathered.findings, stackName, a.preDeploy);
24458
+ const covWarn = coverageWarning(coverageFindings, stackName, a.preDeploy);
24181
24459
  if (covWarn) console.error(covWarn);
24460
+ const readWarn = readFailureWarning(coverageFindings, stackName);
24461
+ if (readWarn) console.error(readWarn);
24182
24462
  }
24183
24463
  if (a.preDeploy) {
24184
24464
  const pendingInfo = pendingCreationInfo(gathered.findings, stackName);
@@ -24214,7 +24494,7 @@ async function runCheck(args) {
24214
24494
  });
24215
24495
  if (preDeployCode === 1) anyDrift = true;
24216
24496
  worst = Math.max(worst, finalCheckExit(preDeployCode, a.fail));
24217
- worst = Math.max(worst, strictCoverageExit(a.strict, gathered.findings, desired.resources, true));
24497
+ worst = Math.max(worst, strictCoverageExit(a.strict, coverageFindings, desired.resources, true));
24218
24498
  continue;
24219
24499
  }
24220
24500
  const baseline = a.showAll ? void 0 : await loadBaseline(stackName, desired.accountId, region);
@@ -24274,11 +24554,10 @@ async function runCheck(args) {
24274
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).`);
24275
24555
  if (code === 1) anyDrift = true;
24276
24556
  worst = Math.max(worst, finalCheckExit(code, a.fail));
24277
- worst = Math.max(worst, strictCoverageExit(a.strict, gathered.findings, desired.resources));
24557
+ worst = Math.max(worst, strictCoverageExit(a.strict, coverageFindings, desired.resources));
24278
24558
  } catch (e) {
24279
24559
  if (isStackNotDeployed(e)) {
24280
- await ensureCallerAccount(region);
24281
- if (hasBaselineForStack(stackName, region, callerAccount)) {
24560
+ if (hasBaselineForStack(stackName, region, await ensureCallerAccount(region))) {
24282
24561
  const msg = "deployed baseline exists but the stack is gone — deleted out of band";
24283
24562
  const label = `${stackName} (${region})`;
24284
24563
  console.error(`[Drift] ${label}: ${msg}`);
@@ -24354,6 +24633,10 @@ async function runRevert(args) {
24354
24633
  continue;
24355
24634
  }
24356
24635
  try {
24636
+ enterRoleScope(await stackRoleScope(a.assumeRole, {
24637
+ account,
24638
+ region
24639
+ }, "revert"));
24357
24640
  const mismatch = await accountGate.preRead(account, region);
24358
24641
  if (mismatch.skip) {
24359
24642
  console.error(`error: ${stackName}: ${mismatch.message}`);
@@ -24490,6 +24773,12 @@ OPTIONS
24490
24773
  An env-agnostic stack with none of these falls back to
24491
24774
  the active --profile's configured region (~/.aws/config)
24492
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
24493
24782
  -a, --app <cmd|cdk.out> CDK app command or pre-synthesized assembly dir
24494
24783
  (or $CDKRD_APP / cdk.json "app") — enables stack
24495
24784
  auto-discovery + construct-path output
@@ -24507,9 +24796,12 @@ OPTIONS
24507
24796
  still prompt and could hang). Non-TTY runs never prompt
24508
24797
  anyway; with --fail, --fail's exit-1 wins
24509
24798
  --strict (check) exit 1 when coverage is INCOMPLETE — any
24510
- 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
24511
24801
  recursed into. A loud coverage warning always prints;
24512
- --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
24513
24805
  --show-all (check) inventory mode: show ALL current undeclared
24514
24806
  state (not just changes since record)
24515
24807
  --verbose (check) expand informational tiers / (revert) the
@@ -24593,11 +24885,7 @@ async function main(argv) {
24593
24885
  installInterruptGuard();
24594
24886
  const argv = process.argv.slice(2);
24595
24887
  main(argv).then((code) => flushAndExit(code)).catch((e) => {
24596
- const msg = e?.message ?? String(e);
24597
- 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.");
24598
- 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.");
24599
- else if (/AccessDenied|not authorized/i.test(msg)) console.error(`error: access denied — ${msg}`);
24600
- else console.error(`error: ${msg}`);
24888
+ console.error(topLevelErrorMessage(e));
24601
24889
  if (argv.includes("--json")) console.log("[]");
24602
24890
  return flushAndExit(2);
24603
24891
  });