cdk-real-drift 0.29.1 → 0.31.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",
@@ -446,8 +501,324 @@ function parseCommonArgs(args, verb) {
446
501
  verbose: has("--verbose") || has("-v"),
447
502
  waitMs
448
503
  };
449
- parsed.noPrompt = has("--no-prompt");
450
- return parsed;
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)));
806
+ }
807
+ return {
808
+ roleArn,
809
+ provider
810
+ };
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,43 @@ 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
+ function isPendingCreationSkip$1(f) {
957
+ return f.tier === "skipped" && f.note === "no physical id";
958
+ }
959
+ function isCustomResourceSkip(f) {
960
+ return f.tier === "skipped" && (f.resourceType === "AWS::CloudFormation::CustomResource" || f.resourceType.startsWith("Custom::"));
961
+ }
962
+ /**
963
+ * The per-FINDING half of check.ts `hasCoverageGap` (the `--strict` gate): an
964
+ * UNACKNOWLEDGED skipped resource (minus a `Custom::*` skip, #724, and — under
965
+ * `--pre-deploy` — a pending-creation skip, #727) or failed-read readGap. The other half is
966
+ * an un-recursed nested stack, which is a template RESOURCE, not a finding. The `ignore`
967
+ * picker (#1976) offers exactly these, so every gap it lists is one whose acknowledgement
968
+ * changes the `--strict` verdict, and none it omits is one `--strict` fails on.
969
+ */
970
+ function isStrictCoverageGapFinding(f, preDeploy = false) {
971
+ return !isAcknowledgedGap(f) && (f.tier === "skipped" && !(preDeploy && isPendingCreationSkip$1(f)) && !isCustomResourceSkip(f) || isCoverageReadGap(f));
972
+ }
973
+
566
974
  // src/config/config-file.ts
567
975
  const CONFIG_PATH = ".cdkrd/ignore.yaml";
568
976
  const KNOWN_KEYS = /* @__PURE__ */ new Set(["ignore"]);
@@ -570,9 +978,10 @@ const RULE_OBJECT_KEYS = /* @__PURE__ */ new Set([
570
978
  "path",
571
979
  "stack",
572
980
  "account",
573
- "region"
981
+ "region",
982
+ "resourceType"
574
983
  ]);
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";
984
+ 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
985
  function looksUtf16(buf, nulAtOddIndex) {
577
986
  const n = Math.min(buf.length, 64);
578
987
  if (n < 2) return false;
@@ -660,13 +1069,16 @@ function isUniversalPath(path) {
660
1069
  */
661
1070
  function validateIgnoreEntry(entry, index) {
662
1071
  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? }`);
1072
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) throw new Error(`${at} must be a mapping { path, stack?, account?, region?, resourceType? }`);
664
1073
  const obj = entry;
665
1074
  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"`);
1075
+ if (unknown.length > 0) throw new Error(`${at}: unknown key(s) ${unknown.map((k) => `"${k}"`).join(", ")} — known keys: "path", "stack", "account", "region", "resourceType"`);
667
1076
  if (typeof obj.path !== "string") throw new Error(`${at}: "path" is required and must be a string`);
668
1077
  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`);
1078
+ if (typeof obj.resourceType !== "undefined" && typeof obj.resourceType !== "string") throw new Error(`${at}: "resourceType" must be a string`);
1079
+ if (obj.resourceType === "") throw new Error(`${at}: "resourceType" must not be empty (omit it to match any type)`);
1080
+ const exactType = typeof obj.resourceType === "string" && !isGlob(obj.resourceType);
1081
+ 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
1082
  for (const k of [
671
1083
  "stack",
672
1084
  "account",
@@ -729,7 +1141,8 @@ function ruleKey(r) {
729
1141
  r.path,
730
1142
  r.stack ?? null,
731
1143
  r.account ?? null,
732
- r.region ?? null
1144
+ r.region ?? null,
1145
+ r.resourceType ?? null
733
1146
  ]);
734
1147
  }
735
1148
  /** A rule as a plain object with keys in canonical order (path, stack, account, region),
@@ -739,6 +1152,7 @@ function orderedRule(r) {
739
1152
  if (r.stack !== void 0) o.stack = r.stack;
740
1153
  if (r.account !== void 0) o.account = r.account;
741
1154
  if (r.region !== void 0) o.region = r.region;
1155
+ if (r.resourceType !== void 0) o.resourceType = r.resourceType;
742
1156
  return o;
743
1157
  }
744
1158
  /**
@@ -864,14 +1278,16 @@ function parseIgnoreRule(entry) {
864
1278
  const scope = [
865
1279
  entry.stack !== void 0 ? `stack:${entry.stack}` : void 0,
866
1280
  entry.account !== void 0 ? `account:${entry.account}` : void 0,
867
- entry.region !== void 0 ? `region:${entry.region}` : void 0
1281
+ entry.region !== void 0 ? `region:${entry.region}` : void 0,
1282
+ entry.resourceType !== void 0 ? `resourceType:${entry.resourceType}` : void 0
868
1283
  ].filter((s) => s !== void 0);
869
1284
  return {
870
1285
  raw: scope.length > 0 ? `${entry.path} (${scope.join(", ")})` : entry.path,
871
1286
  pathPattern: entry.path,
872
1287
  stackGlob: entry.stack,
873
1288
  accountGlob: entry.account,
874
- regionGlob: entry.region
1289
+ regionGlob: entry.region,
1290
+ resourceTypeGlob: entry.resourceType
875
1291
  };
876
1292
  }
877
1293
  /**
@@ -922,7 +1338,8 @@ function applyIgnores(findings, scope, config) {
922
1338
  const { stackName, accountId, region } = scope;
923
1339
  const rules = config.ignore.map(parseIgnoreRule);
924
1340
  return findings.map((f) => {
925
- if (f.tier !== "declared" && f.tier !== "undeclared" && f.tier !== "added") return f;
1341
+ const gap = f.tier === "skipped" || isCoverageReadGap(f);
1342
+ if (f.tier !== "declared" && f.tier !== "undeclared" && f.tier !== "added" && !gap) return f;
926
1343
  const suffix = f.path ? `.${f.path}` : "";
927
1344
  const wholeResource = f.tier === "added";
928
1345
  const targets = [`${f.logicalId}${suffix}`];
@@ -930,8 +1347,12 @@ function applyIgnores(findings, scope, config) {
930
1347
  targets.push(`${withinStackPath(f.constructPath, stackName)}${suffix}`);
931
1348
  targets.push(`${f.constructPath}${suffix}`);
932
1349
  }
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)));
1350
+ 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
1351
  if (!hit) return f;
1352
+ if (gap) return {
1353
+ ...f,
1354
+ acknowledgedBy: hit.raw
1355
+ };
935
1356
  const { unrecorded: _unrecorded, ...rest } = f;
936
1357
  return {
937
1358
  ...rest,
@@ -942,187 +1363,6 @@ function applyIgnores(findings, scope, config) {
942
1363
  });
943
1364
  }
944
1365
 
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
1366
  // src/commands/account-gate.ts
1127
1367
  function mismatchTail(declaredAccount, verb) {
1128
1368
  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 +1448,16 @@ function classifyReadAccountMismatch(declaredAccount, readAccountId, verb = "che
1208
1448
  * is the backstop for that case, exactly as in check.
1209
1449
  */
1210
1450
  function createAccountGate(verb) {
1211
- let callerAccount;
1212
- let callerAccountResolved = false;
1451
+ const callerAccounts = /* @__PURE__ */ new Map();
1213
1452
  return {
1214
1453
  preRead: async (declaredAccount, region) => {
1215
1454
  if (!declaredAccount) return {
1216
1455
  skip: false,
1217
1456
  message: ""
1218
1457
  };
1219
- if (!callerAccountResolved) {
1220
- callerAccount = await resolveCallerAccount(region);
1221
- callerAccountResolved = true;
1222
- }
1223
- return classifyAccountMismatch(declaredAccount, callerAccount, verb);
1458
+ const key = credentialScopeKey();
1459
+ if (!callerAccounts.has(key)) callerAccounts.set(key, await resolveCallerAccount(region));
1460
+ return classifyAccountMismatch(declaredAccount, callerAccounts.get(key), verb);
1224
1461
  },
1225
1462
  postRead: (declaredAccount, readAccountId) => classifyReadAccountMismatch(declaredAccount, readAccountId, verb)
1226
1463
  };
@@ -5853,7 +6090,8 @@ function isDefinitiveDenial(err) {
5853
6090
  return e.$metadata?.httpStatusCode === 403;
5854
6091
  }
5855
6092
  async function fetchManagedAliasTargets(region) {
5856
- const cached = cache$1.get(region);
6093
+ const key = `${credentialScopeKey()}|${region}`;
6094
+ const cached = cache$1.get(key);
5857
6095
  if (cached) return cached;
5858
6096
  const targets = {};
5859
6097
  try {
@@ -5874,7 +6112,7 @@ async function fetchManagedAliasTargets(region) {
5874
6112
  targets,
5875
6113
  denied: false
5876
6114
  };
5877
- cache$1.set(region, result);
6115
+ cache$1.set(key, result);
5878
6116
  return result;
5879
6117
  } catch (e) {
5880
6118
  if (isDefinitiveDenial(e)) {
@@ -5882,7 +6120,7 @@ async function fetchManagedAliasTargets(region) {
5882
6120
  targets: {},
5883
6121
  denied: true
5884
6122
  };
5885
- cache$1.set(region, result);
6123
+ cache$1.set(key, result);
5886
6124
  return result;
5887
6125
  }
5888
6126
  return {
@@ -7972,7 +8210,8 @@ function classifyResource(resource, liveRaw, schema, opts = {}) {
7972
8210
  logicalId,
7973
8211
  resourceType,
7974
8212
  path: p,
7975
- note: "supplement read failed — property unverifiable (grant the missing read permission)"
8213
+ note: "supplement read failed — property unverifiable (grant the missing read permission)",
8214
+ readFailed: true
7976
8215
  });
7977
8216
  for (const [k, v] of Object.entries(declared)) {
7978
8217
  if (v === UNRESOLVED || hasUnresolved(v)) {
@@ -7990,7 +8229,8 @@ function classifyResource(resource, liveRaw, schema, opts = {}) {
7990
8229
  logicalId,
7991
8230
  resourceType,
7992
8231
  path: k,
7993
- note: "supplement read failed — property unverifiable (grant the missing read permission)"
8232
+ note: "supplement read failed — property unverifiable (grant the missing read permission)",
8233
+ readFailed: true
7994
8234
  });
7995
8235
  continue;
7996
8236
  }
@@ -14996,7 +15236,7 @@ function describeTypeFailedWarning(resourceType, region) {
14996
15236
  }
14997
15237
  async function getSchemaInfoResult(client, resourceType) {
14998
15238
  const region = await client.config.region();
14999
- const cacheKey = `${region}\0${resourceType}`;
15239
+ const cacheKey = `${credentialScopeKey()}\0${region}\0${resourceType}`;
15000
15240
  const cached = cache.get(cacheKey);
15001
15241
  if (cached) return {
15002
15242
  info: cached,
@@ -15551,9 +15791,10 @@ async function fetchSgNamesByIds(region, ids) {
15551
15791
  return;
15552
15792
  }
15553
15793
  }
15794
+ const scopedKey = (key) => `${credentialScopeKey()}|${key}`;
15554
15795
  const defaultSgIdsCache = /* @__PURE__ */ new Map();
15555
15796
  async function fetchDefaultSgIds(region) {
15556
- const cached = defaultSgIdsCache.get(region);
15797
+ const cached = defaultSgIdsCache.get(scopedKey(region));
15557
15798
  if (cached) return cached;
15558
15799
  const ids = /* @__PURE__ */ new Set();
15559
15800
  try {
@@ -15577,12 +15818,12 @@ async function fetchDefaultSgIds(region) {
15577
15818
  } catch {
15578
15819
  return ids;
15579
15820
  }
15580
- defaultSgIdsCache.set(region, ids);
15821
+ defaultSgIdsCache.set(scopedKey(region), ids);
15581
15822
  return ids;
15582
15823
  }
15583
15824
  const defaultSubnetIdsCache = /* @__PURE__ */ new Map();
15584
15825
  async function fetchDefaultVpcSubnetIds(region) {
15585
- const cached = defaultSubnetIdsCache.get(region);
15826
+ const cached = defaultSubnetIdsCache.get(scopedKey(region));
15586
15827
  if (cached) return cached;
15587
15828
  const ids = /* @__PURE__ */ new Set();
15588
15829
  try {
@@ -15606,12 +15847,12 @@ async function fetchDefaultVpcSubnetIds(region) {
15606
15847
  } catch {
15607
15848
  return ids;
15608
15849
  }
15609
- defaultSubnetIdsCache.set(region, ids);
15850
+ defaultSubnetIdsCache.set(scopedKey(region), ids);
15610
15851
  return ids;
15611
15852
  }
15612
15853
  const ecsContainerInsightsCache = /* @__PURE__ */ new Map();
15613
15854
  async function fetchEcsContainerInsightsDefault(region) {
15614
- if (ecsContainerInsightsCache.has(region)) return ecsContainerInsightsCache.get(region);
15855
+ if (ecsContainerInsightsCache.has(scopedKey(region))) return ecsContainerInsightsCache.get(scopedKey(region));
15615
15856
  try {
15616
15857
  const value = (await new ECSClient({
15617
15858
  region,
@@ -15620,7 +15861,7 @@ async function fetchEcsContainerInsightsDefault(region) {
15620
15861
  name: "containerInsights",
15621
15862
  effectiveSettings: true
15622
15863
  }))).settings?.find((s) => s.name === "containerInsights")?.value;
15623
- ecsContainerInsightsCache.set(region, value);
15864
+ ecsContainerInsightsCache.set(scopedKey(region), value);
15624
15865
  return value;
15625
15866
  } catch {
15626
15867
  return;
@@ -15628,13 +15869,13 @@ async function fetchEcsContainerInsightsDefault(region) {
15628
15869
  }
15629
15870
  const ssmParameterTierCache = /* @__PURE__ */ new Map();
15630
15871
  async function fetchSsmDefaultParameterTier(region) {
15631
- if (ssmParameterTierCache.has(region)) return ssmParameterTierCache.get(region);
15872
+ if (ssmParameterTierCache.has(scopedKey(region))) return ssmParameterTierCache.get(scopedKey(region));
15632
15873
  try {
15633
15874
  const value = (await new SSMClient({
15634
15875
  region,
15635
15876
  ...READ_RETRY
15636
15877
  }).send(new GetServiceSettingCommand({ SettingId: "/ssm/parameter-store/default-parameter-tier" }))).ServiceSetting?.SettingValue;
15637
- ssmParameterTierCache.set(region, value);
15878
+ ssmParameterTierCache.set(scopedKey(region), value);
15638
15879
  return value;
15639
15880
  } catch {
15640
15881
  return;
@@ -15642,13 +15883,13 @@ async function fetchSsmDefaultParameterTier(region) {
15642
15883
  }
15643
15884
  const ebsEncryptionByDefaultCache = /* @__PURE__ */ new Map();
15644
15885
  async function fetchEbsEncryptionByDefault(region) {
15645
- if (ebsEncryptionByDefaultCache.has(region)) return ebsEncryptionByDefaultCache.get(region);
15886
+ if (ebsEncryptionByDefaultCache.has(scopedKey(region))) return ebsEncryptionByDefaultCache.get(scopedKey(region));
15646
15887
  try {
15647
15888
  const value = (await new EC2Client({
15648
15889
  region,
15649
15890
  ...READ_RETRY
15650
15891
  }).send(new GetEbsEncryptionByDefaultCommand({}))).EbsEncryptionByDefault;
15651
- ebsEncryptionByDefaultCache.set(region, value);
15892
+ ebsEncryptionByDefaultCache.set(scopedKey(region), value);
15652
15893
  return value;
15653
15894
  } catch {
15654
15895
  return;
@@ -15656,7 +15897,7 @@ async function fetchEbsEncryptionByDefault(region) {
15656
15897
  }
15657
15898
  const ec2CreditDefaultCache = /* @__PURE__ */ new Map();
15658
15899
  async function fetchEc2FamilyCreditDefault(region, family) {
15659
- const cacheKey = `${region}|${family}`;
15900
+ const cacheKey = scopedKey(`${region}|${family}`);
15660
15901
  if (ec2CreditDefaultCache.has(cacheKey)) return ec2CreditDefaultCache.get(cacheKey);
15661
15902
  try {
15662
15903
  const value = (await new EC2Client({
@@ -15671,13 +15912,13 @@ async function fetchEc2FamilyCreditDefault(region, family) {
15671
15912
  }
15672
15913
  const rdsDefaultCaCache = /* @__PURE__ */ new Map();
15673
15914
  async function fetchRdsDefaultCaIdentifier(region) {
15674
- if (rdsDefaultCaCache.has(region)) return rdsDefaultCaCache.get(region);
15915
+ if (rdsDefaultCaCache.has(scopedKey(region))) return rdsDefaultCaCache.get(scopedKey(region));
15675
15916
  try {
15676
15917
  const value = ((await new RDSClient({
15677
15918
  region,
15678
15919
  ...READ_RETRY
15679
15920
  }).send(new DescribeCertificatesCommand({}))).Certificates ?? []).find((cert) => cert.CustomerOverride === true)?.CertificateIdentifier;
15680
- rdsDefaultCaCache.set(region, value);
15921
+ rdsDefaultCaCache.set(scopedKey(region), value);
15681
15922
  return value;
15682
15923
  } catch {
15683
15924
  return;
@@ -15685,7 +15926,7 @@ async function fetchRdsDefaultCaIdentifier(region) {
15685
15926
  }
15686
15927
  const dmsAllocatedStorageDefaultsCache = /* @__PURE__ */ new Map();
15687
15928
  async function fetchDmsAllocatedStorageDefaults(region) {
15688
- const cached = dmsAllocatedStorageDefaultsCache.get(region);
15929
+ const cached = dmsAllocatedStorageDefaultsCache.get(scopedKey(region));
15689
15930
  if (cached) return cached;
15690
15931
  const map = {};
15691
15932
  try {
@@ -15703,12 +15944,12 @@ async function fetchDmsAllocatedStorageDefaults(region) {
15703
15944
  marker = r.Marker;
15704
15945
  } while (marker);
15705
15946
  } catch {}
15706
- dmsAllocatedStorageDefaultsCache.set(region, map);
15947
+ dmsAllocatedStorageDefaultsCache.set(scopedKey(region), map);
15707
15948
  return map;
15708
15949
  }
15709
15950
  const instanceMetadataDefaultsCache = /* @__PURE__ */ new Map();
15710
15951
  async function fetchInstanceMetadataDefaults(region) {
15711
- if (instanceMetadataDefaultsCache.has(region)) return instanceMetadataDefaultsCache.get(region);
15952
+ if (instanceMetadataDefaultsCache.has(scopedKey(region))) return instanceMetadataDefaultsCache.get(scopedKey(region));
15712
15953
  try {
15713
15954
  const al = (await new EC2Client({
15714
15955
  region,
@@ -15720,7 +15961,7 @@ async function fetchInstanceMetadataDefaults(region) {
15720
15961
  if (al?.HttpEndpoint != null) out.HttpEndpoint = al.HttpEndpoint;
15721
15962
  if (al?.InstanceMetadataTags != null) out.InstanceMetadataTags = al.InstanceMetadataTags;
15722
15963
  const value = Object.keys(out).length > 0 ? out : void 0;
15723
- instanceMetadataDefaultsCache.set(region, value);
15964
+ instanceMetadataDefaultsCache.set(scopedKey(region), value);
15724
15965
  return value;
15725
15966
  } catch {
15726
15967
  return;
@@ -16628,9 +16869,9 @@ async function gatherFindings(stackName, region, templateOverride, recoveryTempl
16628
16869
  if (desired.resources.some((r) => usesManagedKmsAlias(r.declared) || typeNeedsManagedKeyResolution(r.resourceType))) {
16629
16870
  const resolved = await fetchManagedAliasTargets(region);
16630
16871
  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);
16872
+ const decision = kmsWarnDecision(region, resolved, kmsDeniedWarned.has(scopedKey(region)), kmsTransientWarned.has(scopedKey(region)));
16873
+ if (decision.stampDenied) kmsDeniedWarned.add(scopedKey(region));
16874
+ if (decision.stampTransient) kmsTransientWarned.add(scopedKey(region));
16634
16875
  if (decision.warning) console.error(decision.warning);
16635
16876
  }
16636
16877
  let defaultSgIds = /* @__PURE__ */ new Set();
@@ -18179,14 +18420,15 @@ function warnTemplateHashDrift(baseline, rawTemplate, stackName, warn = console.
18179
18420
  // src/read/deployed-source-hash.ts
18180
18421
  const s3Clients = /* @__PURE__ */ new Map();
18181
18422
  const fetchS3Sha256Base64 = async (ref, region) => {
18182
- let s3 = s3Clients.get(region);
18423
+ const key = `${credentialScopeKey()}|${region}`;
18424
+ let s3 = s3Clients.get(key);
18183
18425
  if (s3 === void 0) {
18184
18426
  s3 = new S3Client({
18185
18427
  region,
18186
18428
  followRegionRedirects: true,
18187
18429
  ...READ_RETRY
18188
18430
  });
18189
- s3Clients.set(region, s3);
18431
+ s3Clients.set(key, s3);
18190
18432
  }
18191
18433
  const body = (await s3.send(new GetObjectCommand({
18192
18434
  Bucket: ref.bucket,
@@ -18386,7 +18628,7 @@ const INFO_TIERS = [
18386
18628
  "unresolved",
18387
18629
  "skipped"
18388
18630
  ];
18389
- function isPendingCreationSkip$1(f) {
18631
+ function isPendingCreationSkip(f) {
18390
18632
  return f.tier === "skipped" && f.note === "no physical id";
18391
18633
  }
18392
18634
  function formatFinding(f, stackName = "") {
@@ -18394,6 +18636,7 @@ function formatFinding(f, stackName = "") {
18394
18636
  const pathDisplay = f.attributeKey ? `${f.path}[${sanitizeForTerminal(f.attributeKey)}]` : f.path;
18395
18637
  let s = `${pathDisplay ? `${id}.${pathDisplay}` : id} (${f.resourceType})`;
18396
18638
  if (f.note) s += ` — ${sanitizeForTerminal(f.note)}`;
18639
+ if (f.acknowledgedBy !== void 0) s += ` — acknowledged by ignore rule "${sanitizeForTerminal(f.acknowledgedBy)}" (not a --strict failure)`;
18397
18640
  const rt = f.resourceType;
18398
18641
  const rd = (v) => redactValue(rt, f.path, v);
18399
18642
  if (f.tier === "declared") {
@@ -18558,10 +18801,15 @@ function report(rawFindings, header, opts = {}) {
18558
18801
  if (t === "atDefault") return `atDefault=${items.length} (undeclared values matching a known AWS default — not drift)`;
18559
18802
  if (t === "generated") return `generated=${items.length} (auto-generated identifiers not in your template, AWS-assigned at deploy — not drift)`;
18560
18803
  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;
18804
+ const failed = items.filter((f) => isCoverageReadGap(f) && !isAcknowledgedGap(f)).length;
18805
+ const acked = items.filter((f) => isCoverageReadGap(f) && isAcknowledgedGap(f)).length;
18806
+ const byNature = items.filter((f) => !isCoverageReadGap(f));
18807
+ const writeOnly = byNature.filter((f) => (f.note ?? "").includes("write-only")).length;
18808
+ const masked = byNature.filter((f) => f.note === GETTEMPLATE_MASK_NOTE).length;
18809
+ const notReturned = byNature.length - writeOnly - masked;
18564
18810
  const parts = [
18811
+ ...failed > 0 ? [`${failed} read failed — coverage incomplete (grant the read, or acknowledge it)`] : [],
18812
+ ...acked > 0 ? [`${acked} read failed, acknowledged in .cdkrd/ignore.yaml`] : [],
18565
18813
  ...notReturned > 0 ? [`${notReturned} not returned by AWS`] : [],
18566
18814
  ...writeOnly > 0 ? [`${writeOnly} write-only`] : [],
18567
18815
  ...masked > 0 ? [`${masked} non-ASCII masked by GetTemplate`] : []
@@ -18572,14 +18820,18 @@ function report(rawFindings, header, opts = {}) {
18572
18820
  if (t === "skipped") return `skipped=${items.length} — NOT checked (coverage incomplete: ${groupReasons(items)})`;
18573
18821
  return `${t}=${items.length} (${groupReasons(items)})`;
18574
18822
  };
18575
- const skippedSummaryFor = (items) => {
18576
- if (!opts.preDeploy) return [summaryFor("skipped", items)];
18577
- const pending = items.filter(isPendingCreationSkip$1);
18578
- const gaps = items.filter((f) => !isPendingCreationSkip$1(f));
18823
+ const skippedSummaryFor = (all) => {
18824
+ const isPending = (f) => !!opts.preDeploy && isPendingCreationSkip(f);
18825
+ const acked = all.filter((f) => isAcknowledgedGap(f) && !isPending(f));
18826
+ const items = all.filter((f) => !isAcknowledgedGap(f) || isPending(f));
18827
+ const ackLine = acked.length > 0 ? [`acknowledged-skip=${acked.length} — NOT checked, acknowledged in .cdkrd/ignore.yaml (${groupReasons(acked)})`] : [];
18828
+ if (!opts.preDeploy) return [...items.length > 0 ? [summaryFor("skipped", items)] : [], ...ackLine];
18829
+ const pending = items.filter(isPendingCreationSkip);
18830
+ const gaps = items.filter((f) => !isPendingCreationSkip(f));
18579
18831
  const lines = [];
18580
18832
  if (gaps.length > 0) lines.push(summaryFor("skipped", gaps));
18581
18833
  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;
18834
+ return [...lines, ...ackLine];
18583
18835
  };
18584
18836
  const summaries = INFO_TIERS.filter((t) => !isExpanded(t)).flatMap((t) => {
18585
18837
  const items = byTier(t);
@@ -22622,10 +22874,11 @@ async function recordStack(p) {
22622
22874
  }
22623
22875
  /** Header for ignore's multiselect. The key hints are rendered by `bulkMultiselect`
22624
22876
  * itself, so this is just the one-line prompt. Pure + exported for unit tests. */
22625
- function ignoreSelectMessage(stackName, region) {
22626
- return `${stackLabel$1(stackName, region)}: select drift to ignore — stops reporting it (writes .cdkrd/ignore.yaml)`;
22877
+ function ignoreSelectMessage(stackName, region, gaps = 0) {
22878
+ const base = `${stackLabel$1(stackName, region)}: select drift to ignore — stops reporting it (writes .cdkrd/ignore.yaml)`;
22879
+ return gaps > 0 ? `${base}; a [coverage gap] row is ACKNOWLEDGED instead — still listed, no longer fails --strict (once the read succeeds, the rule ignores drift there too — remove it after granting the read)` : base;
22627
22880
  }
22628
- const ignoreFindingKey = (f) => `${f.logicalId}::${f.path}`;
22881
+ const ignoreFindingKey = (f) => f.tier === "skipped" || f.tier === "readGap" ? `${f.tier}::${f.logicalId}::${f.path}` : `${f.logicalId}::${f.path}`;
22629
22882
  /**
22630
22883
  * The ignore multiselect rows. EVERY row starts UNSELECTED (→ selects all) — mirroring
22631
22884
  * revert's picker (R137): ignore STOPS watching permanently, and check's interactive flow
@@ -22638,17 +22891,36 @@ function ignoreSelectOptions(ignorable, stackName = "") {
22638
22891
  const id = f.constructPath ? withinStackPath(f.constructPath, stackName) : f.logicalId;
22639
22892
  return {
22640
22893
  value: ignoreFindingKey(f),
22641
- label: `${id}${f.path ? `.${f.path}` : ""} (${f.tier})`,
22894
+ label: `${id}${f.path ? `.${f.path}` : ""} ${ignoreRowKind(f)}`,
22642
22895
  selected: false
22643
22896
  };
22644
22897
  });
22645
22898
  }
22646
22899
  /**
22900
+ * The coverage gaps the `ignore` picker offers to ACKNOWLEDGE (#1976): exactly the findings
22901
+ * `check --strict` fails on (isStrictCoverageGapFinding, deployed path) — an unacknowledged
22902
+ * non-custom `skipped` resource, or a readGap whose read FAILED. A by-nature readGap
22903
+ * (write-only / not returned) never fails `--strict`, a `Custom::*` skip is excluded from
22904
+ * the gate (#724), and an acknowledged one already carries `acknowledgedBy` — none of them
22905
+ * is offered. Pure + exported.
22906
+ */
22907
+ function acknowledgeableGaps(findings) {
22908
+ return findings.filter((f) => isStrictCoverageGapFinding(f));
22909
+ }
22910
+ function ignoreRowKind(f) {
22911
+ if (f.tier === "skipped") return `[coverage gap — resource not read${f.note ? `: ${sanitizeForTerminal(f.note).slice(0, 80)}` : ""}]`;
22912
+ if (f.tier === "readGap") return f.path ? "[coverage gap — property read failed]" : "[coverage gap — resource read failed]";
22913
+ return `(${f.tier})`;
22914
+ }
22915
+ /**
22647
22916
  * Write `ignore` rules into `.cdkrd/ignore.yaml` for the chosen declared/undeclared
22648
22917
  * findings — they stop being reported entirely (re-tagged `ignored` on the next check),
22649
22918
  * the "stop watching" counterpart to record's "keep watching". Interactive runs pick
22650
22919
  * WHICH findings to ignore (default NONE selected — → selects all, R137); `--yes`
22651
- * ignores all shown.
22920
+ * ignores all shown drift. The interactive picker also lists the `--strict`-failing
22921
+ * coverage gaps (#1976, acknowledgeableGaps): a picked one gets the rule ignoreRuleFor
22922
+ * writes for it — RESOURCE-level for a skip (empty path), property-level for a failed
22923
+ * read — which applyIgnores matches to stamp `acknowledgedBy`. `--yes` never picks a gap.
22652
22924
  * Non-interactively without `--yes` it refuses (a required decision, like record, R38).
22653
22925
  * Idempotent: rules already in the file are reported, not duplicated. Shared by `cdkrd
22654
22926
  * ignore` and (PR-B2) check's interactive flow, so both write rules identically.
@@ -22656,7 +22928,10 @@ function ignoreSelectOptions(ignorable, stackName = "") {
22656
22928
  async function ignoreStack(p) {
22657
22929
  const { stackName, findings, yes, interactive, accountId = "", region = "" } = p;
22658
22930
  const ignorable = findings.filter((f) => f.tier === "declared" || f.tier === "undeclared" || f.tier === "added");
22659
- if (ignorable.length === 0) {
22931
+ const gaps = acknowledgeableGaps(findings);
22932
+ const pickGaps = !yes && interactive && gaps.length > 0;
22933
+ if (gaps.length > 0 && !pickGaps) console.error(`note: ${stackName}: ${gaps.length} coverage gap(s) left unacknowledged — only the interactive picker acknowledges a gap (run \`cdkrd ignore ${stackName}\` in a terminal without --yes)`);
22934
+ if (ignorable.length === 0 && !pickGaps) {
22660
22935
  if (!p.json) console.log(style.clean(`${stackName}: no ignorable drift to ignore.`));
22661
22936
  return {
22662
22937
  wrote: false,
@@ -22674,7 +22949,8 @@ async function ignoreStack(p) {
22674
22949
  added: 0
22675
22950
  };
22676
22951
  }
22677
- const picked = await bulkMultiselect(ignoreSelectMessage(stackName, region), ignoreSelectOptions(ignorable, stackName));
22952
+ const offered = [...ignorable, ...gaps];
22953
+ const picked = await bulkMultiselect(ignoreSelectMessage(stackName, region, gaps.length), ignoreSelectOptions(offered, stackName));
22678
22954
  if (picked === void 0) {
22679
22955
  console.error(`note: ${stackName}: ignore cancelled — config unchanged`);
22680
22956
  return {
@@ -22684,7 +22960,7 @@ async function ignoreStack(p) {
22684
22960
  };
22685
22961
  }
22686
22962
  const set = new Set(picked);
22687
- chosen = ignorable.filter((f) => set.has(ignoreFindingKey(f)));
22963
+ chosen = offered.filter((f) => set.has(ignoreFindingKey(f)));
22688
22964
  if (chosen.length === 0) {
22689
22965
  console.error(`note: ${stackName}: nothing selected — config unchanged`);
22690
22966
  return {
@@ -23192,6 +23468,10 @@ async function runRecord(args) {
23192
23468
  continue;
23193
23469
  }
23194
23470
  try {
23471
+ enterRoleScope(await stackRoleScope(a.assumeRole, {
23472
+ account,
23473
+ region
23474
+ }, "record"));
23195
23475
  const mismatch = await accountGate.preRead(account, region);
23196
23476
  if (mismatch.skip) {
23197
23477
  console.error(`note: ${stackName}: ${mismatch.message}`);
@@ -23333,6 +23613,10 @@ async function runIgnore(args) {
23333
23613
  continue;
23334
23614
  }
23335
23615
  try {
23616
+ enterRoleScope(await stackRoleScope(a.assumeRole, {
23617
+ account,
23618
+ region
23619
+ }, "ignore"));
23336
23620
  const mismatch = await accountGate.preRead(account, region);
23337
23621
  if (mismatch.skip) {
23338
23622
  console.error(`note: ${stackName}: ${mismatch.message}`);
@@ -23940,7 +24224,7 @@ function preDeployFindings(findings) {
23940
24224
  return findings.filter((f) => f.tier !== "undeclared" && f.tier !== "generated" && f.tier !== "atDefault" && f.tier !== "added");
23941
24225
  }
23942
24226
  function undeclaredOnlyFindings(findings) {
23943
- return findings.filter((f) => f.tier !== "declared" && f.tier !== "readGap" && f.tier !== "unresolved");
24227
+ return findings.filter((f) => f.tier !== "declared" && (f.tier !== "readGap" || isCoverageReadGap(f)) && f.tier !== "unresolved");
23944
24228
  }
23945
24229
  function nestedStackWarning(resources, stackName) {
23946
24230
  const nested = resources.filter((r) => r.resourceType === "AWS::CloudFormation::Stack");
@@ -23948,22 +24232,26 @@ function nestedStackWarning(resources, stackName) {
23948
24232
  const names = nested.map((r) => r.constructPath ? withinStackPath(r.constructPath, stackName) : r.logicalId).sort();
23949
24233
  return `warning: ${stackName} has ${nested.length} nested CloudFormation stack(s) — cdkrd does not recurse into them, so the resources INSIDE them are NOT checked: ${names.join(", ")}`;
23950
24234
  }
23951
- function isPendingCreationSkip(f) {
23952
- return f.tier === "skipped" && f.note === "no physical id";
23953
- }
23954
- function isCustomResourceSkip(f) {
23955
- return f.tier === "skipped" && (f.resourceType === "AWS::CloudFormation::CustomResource" || f.resourceType.startsWith("Custom::"));
23956
- }
23957
24235
  function coverageWarning(findings, stackName, preDeploy = false) {
23958
- const skipped = findings.filter((f) => f.tier === "skipped" && !(preDeploy && isPendingCreationSkip(f)));
24236
+ const skipped = findings.filter((f) => f.tier === "skipped" && !(preDeploy && isPendingCreationSkip$1(f)) && !isAcknowledgedGap(f));
23959
24237
  if (skipped.length === 0) return null;
23960
24238
  const names = skipped.map((f) => f.constructPath ? withinStackPath(f.constructPath, stackName) : f.logicalId).sort();
23961
24239
  const shown = names.slice(0, 10);
23962
24240
  const more = names.length > shown.length ? `, …(+${names.length - shown.length} more)` : "";
23963
24241
  return `warning: ${stackName}: ${skipped.length} resource(s) were NOT checked (coverage incomplete) — ${shown.join(", ")}${more}; see the skipped breakdown (--verbose)`;
23964
24242
  }
24243
+ function readFailureWarning(findings, stackName) {
24244
+ const gaps = findings.filter((f) => isCoverageReadGap(f) && !isAcknowledgedGap(f));
24245
+ if (gaps.length === 0) return null;
24246
+ const names = gaps.map((f) => {
24247
+ return `${f.constructPath ? withinStackPath(f.constructPath, stackName) : f.logicalId}.${f.path}`;
24248
+ }).sort();
24249
+ const shown = names.slice(0, 10);
24250
+ const more = names.length > shown.length ? `, …(+${names.length - shown.length} more)` : "";
24251
+ 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}`;
24252
+ }
23965
24253
  function pendingCreationInfo(findings, stackName) {
23966
- const pending = findings.filter(isPendingCreationSkip);
24254
+ const pending = findings.filter(isPendingCreationSkip$1);
23967
24255
  if (pending.length === 0) return null;
23968
24256
  const names = pending.map((f) => f.constructPath ? withinStackPath(f.constructPath, stackName) : f.logicalId).sort();
23969
24257
  const shown = names.slice(0, 10);
@@ -23971,7 +24259,7 @@ function pendingCreationInfo(findings, stackName) {
23971
24259
  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
24260
  }
23973
24261
  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");
24262
+ return findings.some((f) => isStrictCoverageGapFinding(f, preDeploy)) || resources.some((r) => r.resourceType === "AWS::CloudFormation::Stack");
23975
24263
  }
23976
24264
  function strictCoverageExit(strict, findings, resources, preDeploy = false) {
23977
24265
  return strict && hasCoverageGap(findings, resources, preDeploy) ? 1 : 0;
@@ -24150,14 +24438,11 @@ async function runCheck(args) {
24150
24438
  };
24151
24439
  const separate = stackSeparator();
24152
24440
  const showProgress = !a.json && isInteractive();
24153
- let callerAccount;
24154
- let callerAccountResolved = false;
24441
+ const callerAccounts = /* @__PURE__ */ new Map();
24155
24442
  const ensureCallerAccount = async (region) => {
24156
- if (!callerAccountResolved) {
24157
- callerAccount = await resolveCallerAccount(region);
24158
- callerAccountResolved = true;
24159
- }
24160
- return callerAccount;
24443
+ const key = credentialScopeKey();
24444
+ if (!callerAccounts.has(key)) callerAccounts.set(key, await resolveCallerAccount(region));
24445
+ return callerAccounts.get(key);
24161
24446
  };
24162
24447
  for (const [idx, { stackName, region, account, template, localAssetHashes }] of stacks.entries()) {
24163
24448
  if (!region) {
@@ -24169,6 +24454,10 @@ async function runCheck(args) {
24169
24454
  }
24170
24455
  const posPrefix = a.json ? "" : positionPrefix(idx, stacks.length);
24171
24456
  try {
24457
+ enterRoleScope(await stackRoleScope(a.assumeRole, {
24458
+ account,
24459
+ region
24460
+ }, "check"));
24172
24461
  const mismatch = classifyAccountMismatch(account, await ensureCallerAccount(region));
24173
24462
  if (mismatch.skip) {
24174
24463
  console.error(`note: ${stackName}: ${mismatch.message}`);
@@ -24195,9 +24484,16 @@ async function runCheck(args) {
24195
24484
  }
24196
24485
  const nestedWarn = nestedStackWarning(desired.resources, stackName);
24197
24486
  if (nestedWarn) console.error(nestedWarn);
24487
+ const coverageFindings = applyIgnores(gathered.findings, {
24488
+ stackName,
24489
+ accountId: desired.accountId,
24490
+ region
24491
+ }, config);
24198
24492
  if (a.json) {
24199
- const covWarn = coverageWarning(gathered.findings, stackName, a.preDeploy);
24493
+ const covWarn = coverageWarning(coverageFindings, stackName, a.preDeploy);
24200
24494
  if (covWarn) console.error(covWarn);
24495
+ const readWarn = readFailureWarning(coverageFindings, stackName);
24496
+ if (readWarn) console.error(readWarn);
24201
24497
  }
24202
24498
  if (a.preDeploy) {
24203
24499
  const pendingInfo = pendingCreationInfo(gathered.findings, stackName);
@@ -24233,7 +24529,7 @@ async function runCheck(args) {
24233
24529
  });
24234
24530
  if (preDeployCode === 1) anyDrift = true;
24235
24531
  worst = Math.max(worst, finalCheckExit(preDeployCode, a.fail));
24236
- worst = Math.max(worst, strictCoverageExit(a.strict, gathered.findings, desired.resources, true));
24532
+ worst = Math.max(worst, strictCoverageExit(a.strict, coverageFindings, desired.resources, true));
24237
24533
  continue;
24238
24534
  }
24239
24535
  const baseline = a.showAll ? void 0 : await loadBaseline(stackName, desired.accountId, region);
@@ -24293,11 +24589,10 @@ async function runCheck(args) {
24293
24589
  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
24590
  if (code === 1) anyDrift = true;
24295
24591
  worst = Math.max(worst, finalCheckExit(code, a.fail));
24296
- worst = Math.max(worst, strictCoverageExit(a.strict, gathered.findings, desired.resources));
24592
+ worst = Math.max(worst, strictCoverageExit(a.strict, coverageFindings, desired.resources));
24297
24593
  } catch (e) {
24298
24594
  if (isStackNotDeployed(e)) {
24299
- await ensureCallerAccount(region);
24300
- if (hasBaselineForStack(stackName, region, callerAccount)) {
24595
+ if (hasBaselineForStack(stackName, region, await ensureCallerAccount(region))) {
24301
24596
  const msg = "deployed baseline exists but the stack is gone — deleted out of band";
24302
24597
  const label = `${stackName} (${region})`;
24303
24598
  console.error(`[Drift] ${label}: ${msg}`);
@@ -24373,6 +24668,10 @@ async function runRevert(args) {
24373
24668
  continue;
24374
24669
  }
24375
24670
  try {
24671
+ enterRoleScope(await stackRoleScope(a.assumeRole, {
24672
+ account,
24673
+ region
24674
+ }, "revert"));
24376
24675
  const mismatch = await accountGate.preRead(account, region);
24377
24676
  if (mismatch.skip) {
24378
24677
  console.error(`error: ${stackName}: ${mismatch.message}`);
@@ -24509,6 +24808,12 @@ OPTIONS
24509
24808
  An env-agnostic stack with none of these falls back to
24510
24809
  the active --profile's configured region (~/.aws/config)
24511
24810
  --profile <p> AWS profile (or $AWS_PROFILE)
24811
+ --assume-role <arn> assume this IAM role (from the --profile / ambient
24812
+ credentials) for every AWS call (or $CDKRD_ASSUME_ROLE);
24813
+ {account} / {region} are filled per stack from the CDK
24814
+ app, e.g. 'arn:aws:iam::{account}:role/MyReadRole'.
24815
+ Session name cdkrd-<verb>. Synth still uses the ambient
24816
+ credentials, as cdk does
24512
24817
  -a, --app <cmd|cdk.out> CDK app command or pre-synthesized assembly dir
24513
24818
  (or $CDKRD_APP / cdk.json "app") — enables stack
24514
24819
  auto-discovery + construct-path output
@@ -24526,9 +24831,12 @@ OPTIONS
24526
24831
  still prompt and could hang). Non-TTY runs never prompt
24527
24832
  anyway; with --fail, --fail's exit-1 wins
24528
24833
  --strict (check) exit 1 when coverage is INCOMPLETE — any
24529
- resource skipped (unread) or a nested stack not
24834
+ resource skipped (unread), a property whose read
24835
+ failed (e.g. AccessDenied), or a nested stack not
24530
24836
  recursed into. A loud coverage warning always prints;
24531
- --strict makes it CI-failing. Orthogonal to --fail
24837
+ --strict makes it CI-failing. A known, intended gap
24838
+ acknowledged in .cdkrd/ignore.yaml stays listed but
24839
+ does not fail. Orthogonal to --fail
24532
24840
  --show-all (check) inventory mode: show ALL current undeclared
24533
24841
  state (not just changes since record)
24534
24842
  --verbose (check) expand informational tiers / (revert) the
@@ -24560,7 +24868,8 @@ OPTIONS
24560
24868
  --yes, -y skip the write confirm AND the op multiselect — apply the
24561
24869
  FULL plan (revert) / skip the selection multiselect +
24562
24870
  overwrite notice, record ALL (record) / ignore ALL shown
24563
- drift without the multiselect (ignore)
24871
+ drift without the multiselect (ignore; a --strict coverage
24872
+ gap is acknowledged only from the interactive picker)
24564
24873
  --help, -h --version, -v (bare \`cdkrd -v\` prints the version; inside a verb,
24565
24874
  \`-v\` is the short alias for --verbose, e.g. check -v)
24566
24875
 
@@ -24612,11 +24921,7 @@ async function main(argv) {
24612
24921
  installInterruptGuard();
24613
24922
  const argv = process.argv.slice(2);
24614
24923
  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}`);
24924
+ console.error(topLevelErrorMessage(e));
24620
24925
  if (argv.includes("--json")) console.log("[]");
24621
24926
  return flushAndExit(2);
24622
24927
  });