cdk-real-drift 0.26.8 → 0.27.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/README.md CHANGED
@@ -1261,6 +1261,62 @@ access-log / route settings back to unset).
1261
1261
 
1262
1262
  </details>
1263
1263
 
1264
+ ## Behind a corporate proxy
1265
+
1266
+ `cdkrd` honours the standard proxy environment variables for **every** AWS call
1267
+ it makes — the live reads, the revert writes, credential resolution (STS / SSO),
1268
+ and the CDK synth/discovery path:
1269
+
1270
+ | variable | effect |
1271
+ | ----------------------------- | ----------------------------------------------------------- |
1272
+ | `HTTPS_PROXY` / `https_proxy` | proxy for `https://` requests — all AWS traffic in practice |
1273
+ | `HTTP_PROXY` / `http_proxy` | proxy for plain `http://` requests |
1274
+ | `ALL_PROXY` / `all_proxy` | fallback for either scheme |
1275
+ | `NO_PROXY` / `no_proxy` | hosts to reach directly, bypassing the proxy |
1276
+
1277
+ Both spellings work; the lower-case ones win where a tool sets both. The proxy
1278
+ is chosen **per request**, so `HTTPS_PROXY` and `HTTP_PROXY` may name different
1279
+ proxies and each scheme goes to its own. This needed explicit support in
1280
+ `cdkrd` because the AWS SDK for JavaScript v3 does not read these variables the
1281
+ way the AWS CLI does — without it, a machine whose only egress is a corporate
1282
+ proxy fails on the very first call, typically with a certificate error naming
1283
+ the network's TLS interceptor rather than the proxy.
1284
+
1285
+ A few sharp edges worth knowing:
1286
+
1287
+ - **`NO_PROXY` matching is exact, unlike curl.** An entry that does not start
1288
+ with `.` or `*` must equal the hostname exactly: `NO_PROXY=example.com` does
1289
+ NOT cover `api.example.com`, and `.example.com` does not cover the apex — so
1290
+ covering a domain and its subdomains takes two entries
1291
+ (`NO_PROXY=example.com,.example.com`). CIDR ranges (`10.0.0.0/8`) are
1292
+ silently ignored; IP addresses must be listed literally. For a VPC-endpoint
1293
+ setup, write `NO_PROXY=.amazonaws.com,amazonaws.com`.
1294
+ - **A TLS-terminating proxy still needs `NODE_EXTRA_CA_CERTS`.** A proxy that
1295
+ opens a CONNECT tunnel needs nothing extra (the origin's own certificate is
1296
+ validated end to end), but one that terminates TLS presents its own
1297
+ certificate, and Node must be told to trust it:
1298
+ `export NODE_EXTRA_CA_CERTS=/path/to/corporate-root-ca.pem`. (The AWS CLI's
1299
+ equivalent is `AWS_CA_BUNDLE`; it does not affect `cdkrd`.)
1300
+ - **SOCKS proxies are not supported.** A `socks5://` (or any `socks*://`) value
1301
+ in a proxy variable is rejected up front with the variable's name — the
1302
+ routing speaks HTTP CONNECT only, and accepting it would fail every call
1303
+ mid-run with an opaque proxy-protocol error instead.
1304
+ - **A proxy value needs an explicit scheme.** `proxy.example:8080` (which curl
1305
+ accepts as `http://`) is rejected up front with the variable's name — the
1306
+ library `cdkrd` routes with would prepend the _request's_ scheme, turning it
1307
+ into a TLS handshake against a plaintext proxy port mid-run.
1308
+ - **A whitespace-only proxy variable is an error**, reported with the variable's
1309
+ name — treating it as set would fail later with an unnamed URL-parse error,
1310
+ and treating it as unset would silently go direct.
1311
+
1312
+ To verify traffic is actually routed, point `cdkrd` at a proxy that cannot work
1313
+ and confirm the command fails (if it succeeds, the variable is not reaching the
1314
+ process):
1315
+
1316
+ ```bash
1317
+ HTTPS_PROXY=http://127.0.0.1:1 https_proxy=http://127.0.0.1:1 cdkrd check MyStack
1318
+ ```
1319
+
1264
1320
  ## Limitations
1265
1321
 
1266
1322
  `cdkrd` is **fail-closed**: anything it can't confidently compare is reported as
package/dist/cli.js CHANGED
@@ -6,6 +6,13 @@ import { pid } from "node:process";
6
6
  import { YAMLSeq, isSeq, parse, parseDocument } from "yaml";
7
7
  import { GetCallerIdentityCommand, STSClient } from "@aws-sdk/client-sts";
8
8
  import { createCredentialChain, fromEnv, fromNodeProviderChain } from "@aws-sdk/credential-providers";
9
+ import { NodeHttpHandler } from "@smithy/node-http-handler";
10
+ import { Agent } from "node:http";
11
+ import { Agent as Agent$1, get } from "node:https";
12
+ import { Agent as Agent$2 } from "agent-base";
13
+ import { HttpProxyAgent } from "http-proxy-agent";
14
+ import { HttpsProxyAgent } from "https-proxy-agent";
15
+ import { getProxyForUrl } from "proxy-from-env";
9
16
  import { CloudControlClient, DeleteResourceCommand, GetResourceCommand, GetResourceRequestStatusCommand, UpdateResourceCommand } from "@aws-sdk/client-cloudcontrol";
10
17
  import { homedir } from "node:os";
11
18
  import { BaseCredentials, CdkAppMultiContext, NonInteractiveIoHost, StackSelectionStrategy, Toolkit } from "@aws-cdk/toolkit-lib";
@@ -942,6 +949,122 @@ function applyIgnores(findings, scope, config) {
942
949
  });
943
950
  }
944
951
 
952
+ //#endregion
953
+ //#region src/read/proxy-routing-agent.ts
954
+ /**
955
+ * An `http.Agent` that routes each request through the environment's proxy, or
956
+ * direct, according to `HTTPS_PROXY` / `HTTP_PROXY` / `NO_PROXY` (#1841).
957
+ *
958
+ * WHY A ROUTING AGENT AND NOT A PLAIN PROXY AGENT
959
+ *
960
+ * `NodeHttpHandler` picks its agent by PROTOCOL alone — `httpsAgent` for an
961
+ * `https:` request, `httpAgent` otherwise — and never consults the request's
962
+ * host. `https-proxy-agent` does not read `NO_PROXY` either. So a statically
963
+ * chosen proxy agent cannot express "this host is exempt", which is the whole
964
+ * of what `NO_PROXY` means. Deciding per REQUEST is the only place the host is
965
+ * known, and `agent-base` gives us that hook: when `connect()` returns an
966
+ * `http.Agent` rather than a socket, the base class delegates the request to it
967
+ * via `socket.addRequest(req, connectOpts)`.
968
+ *
969
+ * KEEP-ALIVE NEEDS BOTH LAYERS, for different reasons. Sockets POOL on
970
+ * whichever agent `connect()` hands back, so the INNER agents carry
971
+ * `keepAlive` (and `maxSockets`) to do the pooling. But Node's
972
+ * `ClientRequest` decides the `Connection:` header from the agent handed to
973
+ * the REQUEST — this one — and with a default outer agent
974
+ * (`keepAlive: false`, `maxSockets: Infinity`) it stamps `Connection: close`
975
+ * on every request, so the response teardown destroys the socket before the
976
+ * inner pool ever keeps it (measured: two sequential proxied SDK calls opened
977
+ * two CONNECT tunnels; with the outer `keepAlive` they share one). Hence the
978
+ * constructor passes `keepAlive: true` UP as well; the outer `maxSockets`
979
+ * stays unlimited on purpose — concurrency is bounded by the inner agents,
980
+ * and an outer bound would add agent-base's fake-socket accounting for no
981
+ * benefit.
982
+ *
983
+ * WHY THE INNER CACHE IS PER INSTANCE
984
+ *
985
+ * Node's `Agent.prototype.destroy()` walks `[this.freeSockets, this.sockets]`,
986
+ * and the second is the ACTIVE set — it aborts in-flight requests, not just
987
+ * idle sockets. `NodeHttpHandler.destroy()` forwards to `httpAgent` and
988
+ * `httpsAgent` unconditionally, external instances included, and cdkrd calls
989
+ * `client.destroy()` (the region probe in `commands/resolve-stacks.ts` does
990
+ * today, and nothing stops a future site). A module-global inner cache would
991
+ * therefore let one client's teardown kill another client's live request —
992
+ * which is also why `clientRequestHandler()` in `read/client-config.ts` builds
993
+ * a FRESH routing agent per client rather than sharing one. The cache is
994
+ * scoped to `this` and {@link destroy} forwards to the inner agents — without
995
+ * that forwarding the tunneled sockets would outlive the client and keep the
996
+ * process alive.
997
+ *
998
+ * The cost of not sharing is duplicate CONNECT + TLS handshakes where two
999
+ * clients talk to the same host. Pooling is per host either way, so sharing
1000
+ * could never remove the FIRST handshake to each distinct AWS endpoint. This
1001
+ * is also what the SDK already does: it builds a `keepAlive` agent per client
1002
+ * on the unproxied path.
1003
+ */
1004
+ /**
1005
+ * Applied to every inner agent.
1006
+ *
1007
+ * The SDK sets these itself, but ONLY when it is handed a plain option bag —
1008
+ * an external `Agent` instance is passed through untouched
1009
+ * (`@smithy/node-http-handler`'s `NodeHttpHandler` constructor). Since a
1010
+ * routing agent IS such an instance, omitting them would silently drop
1011
+ * connection reuse for every proxied run, and a concurrent `check` (gather.ts
1012
+ * reads a whole stack with pooled concurrency) would renegotiate TLS per
1013
+ * request.
1014
+ */
1015
+ const INNER_AGENT_OPTIONS = {
1016
+ keepAlive: true,
1017
+ maxSockets: 50
1018
+ };
1019
+ /**
1020
+ * Build the absolute URL `getProxyForUrl` needs from what `connect()` is given.
1021
+ *
1022
+ * An IPv6 literal is bracketed, or the `host:port` join produces a string no
1023
+ * URL parser accepts (`https://::1:443`) and `NO_PROXY` could never match an
1024
+ * IPv6 entry. Unreachable with AWS hostnames; handled because the alternative
1025
+ * is a silent wrong answer rather than an error.
1026
+ */
1027
+ function requestUrl(options) {
1028
+ const secure = options.secureEndpoint;
1029
+ const rawHost = options.host ?? "localhost";
1030
+ const host = rawHost.includes(":") && !rawHost.startsWith("[") ? `[${rawHost}]` : rawHost;
1031
+ const port = options.port ?? (secure ? 443 : 80);
1032
+ return `${secure ? "https" : "http"}://${host}:${port}`;
1033
+ }
1034
+ var ProxyRoutingAgent = class extends Agent$2 {
1035
+ constructor() {
1036
+ super({ keepAlive: true });
1037
+ }
1038
+ /**
1039
+ * Inner agents by `<scheme>|<proxy url or "direct">`.
1040
+ *
1041
+ * Keyed on the proxy URL and not merely on "proxied or not" because
1042
+ * `NO_PROXY` is not the only thing that varies per host: `HTTP_PROXY` and
1043
+ * `HTTPS_PROXY` may name different proxies, and a single agent bound to one
1044
+ * of them would quietly send the other scheme's traffic to the wrong place.
1045
+ */
1046
+ innerAgents = /* @__PURE__ */ new Map();
1047
+ connect(_req, options) {
1048
+ const secure = options.secureEndpoint;
1049
+ const proxyUrl = getProxyForUrl(requestUrl(options));
1050
+ const key = `${secure ? "https" : "http"}|${proxyUrl || "direct"}`;
1051
+ const cached = this.innerAgents.get(key);
1052
+ if (cached) return cached;
1053
+ const agent = createInnerAgent(secure, proxyUrl);
1054
+ this.innerAgents.set(key, agent);
1055
+ return agent;
1056
+ }
1057
+ destroy() {
1058
+ for (const agent of this.innerAgents.values()) agent.destroy();
1059
+ this.innerAgents.clear();
1060
+ super.destroy();
1061
+ }
1062
+ };
1063
+ function createInnerAgent(secure, proxyUrl) {
1064
+ if (!proxyUrl) return secure ? new Agent$1(INNER_AGENT_OPTIONS) : new Agent(INNER_AGENT_OPTIONS);
1065
+ return secure ? new HttpsProxyAgent(proxyUrl, INNER_AGENT_OPTIONS) : new HttpProxyAgent(proxyUrl, INNER_AGENT_OPTIONS);
1066
+ }
1067
+
945
1068
  //#endregion
946
1069
  //#region src/read/client-config.ts
947
1070
  /** Port of toolkit-lib awscli-compatible `shouldPrioritizeEnv()` (env creds win over profile). */
@@ -956,15 +1079,57 @@ const CLIENT_REQUEST_HANDLER = {
956
1079
  requestTimeout: 6e4,
957
1080
  throwOnRequestTimeout: true
958
1081
  };
959
- const CLIENT_CREDENTIALS = (awsIdentityProperties) => (shouldPrioritizeEnv() ? createCredentialChain(fromEnv(), fromNodeProviderChain({ clientConfig: { requestHandler: CLIENT_REQUEST_HANDLER } })) : fromNodeProviderChain({ clientConfig: { requestHandler: CLIENT_REQUEST_HANDLER } }))(awsIdentityProperties);
1082
+ const PROXY_ENV_VARS = [
1083
+ "HTTPS_PROXY",
1084
+ "https_proxy",
1085
+ "HTTP_PROXY",
1086
+ "http_proxy",
1087
+ "ALL_PROXY",
1088
+ "all_proxy"
1089
+ ];
1090
+ let proxyConfigured;
1091
+ /** Whether any proxy environment variable is set (memoized parse; see resetProxyConfig). */
1092
+ function isProxyConfigured() {
1093
+ if (proxyConfigured === void 0) {
1094
+ let configured = false;
1095
+ for (const name of PROXY_ENV_VARS) {
1096
+ const value = process.env[name];
1097
+ if (value === void 0 || value === "") continue;
1098
+ 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.`);
1099
+ 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}.`);
1100
+ 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}.`);
1101
+ configured = true;
1102
+ }
1103
+ proxyConfigured = configured;
1104
+ }
1105
+ return proxyConfigured;
1106
+ }
1107
+ function clientRequestHandler() {
1108
+ if (!isProxyConfigured()) return CLIENT_REQUEST_HANDLER;
1109
+ const agent = new ProxyRoutingAgent();
1110
+ return new NodeHttpHandler({
1111
+ ...CLIENT_REQUEST_HANDLER,
1112
+ httpAgent: agent,
1113
+ httpsAgent: agent
1114
+ });
1115
+ }
1116
+ const CLIENT_CREDENTIALS = (awsIdentityProperties) => {
1117
+ const requestHandler = clientRequestHandler();
1118
+ return (shouldPrioritizeEnv() ? createCredentialChain(fromEnv(), fromNodeProviderChain({ clientConfig: { requestHandler } })) : fromNodeProviderChain({ clientConfig: { requestHandler } }))(awsIdentityProperties);
1119
+ };
960
1120
  const CLIENT_TIMEOUTS = {
961
1121
  credentials: CLIENT_CREDENTIALS,
962
- requestHandler: CLIENT_REQUEST_HANDLER
1122
+ get requestHandler() {
1123
+ return clientRequestHandler();
1124
+ }
963
1125
  };
964
1126
  const READ_RETRY = {
965
1127
  maxAttempts: 10,
966
1128
  retryMode: "adaptive",
967
- ...CLIENT_TIMEOUTS
1129
+ credentials: CLIENT_CREDENTIALS,
1130
+ get requestHandler() {
1131
+ return clientRequestHandler();
1132
+ }
968
1133
  };
969
1134
 
970
1135
  //#endregion
@@ -1201,6 +1366,9 @@ function missingContextWarning(keys, opts = {}) {
1201
1366
 
1202
1367
  //#endregion
1203
1368
  //#region src/synth/synth.ts
1369
+ function proxyHttpOptions() {
1370
+ return isProxyConfigured() ? { httpOptions: { agent: new ProxyRoutingAgent() } } : {};
1371
+ }
1204
1372
  /**
1205
1373
  * Map the requested stack name(s)/glob(s) to the toolkit-lib `StackSelector` that scopes
1206
1374
  * `toolkit.synth`'s metadata validation (#905).
@@ -1335,10 +1503,13 @@ async function synthApp(app, opts = {}) {
1335
1503
  const stackSelector = buildStackSelector(opts.stackPatterns);
1336
1504
  const toolkit = new Toolkit({
1337
1505
  ioHost: new QuietIoHost(),
1338
- sdkConfig: { baseCredentials: BaseCredentials.awsCliCompatible({
1339
- ...region && { defaultRegion: region },
1340
- ...profile && { profile }
1341
- }) }
1506
+ sdkConfig: {
1507
+ baseCredentials: BaseCredentials.awsCliCompatible({
1508
+ ...region && { defaultRegion: region },
1509
+ ...profile && { profile }
1510
+ }),
1511
+ ...proxyHttpOptions()
1512
+ }
1342
1513
  });
1343
1514
  const p = resolve(app);
1344
1515
  const isDir = existsSync(p) && statSync(p).isDirectory();
@@ -14415,14 +14586,43 @@ const supplementTrustStore = async ({ physicalId, region }) => {
14415
14586
  const url = str$1(r.Location);
14416
14587
  if (!url) return void 0;
14417
14588
  try {
14418
- const resp = await fetch(url, { signal: AbortSignal.timeout(CLIENT_REQUEST_HANDLER.requestTimeout) });
14419
- if (!resp.ok) return void 0;
14420
- const hash = hashCaBundle(await resp.text());
14589
+ const body = await fetchPresignedText(url);
14590
+ if (body === void 0) return void 0;
14591
+ const hash = hashCaBundle(body);
14421
14592
  return hash !== void 0 ? { CaCertificatesBundleSha256: hash } : void 0;
14422
14593
  } catch {
14423
14594
  return;
14424
14595
  }
14425
14596
  };
14597
+ async function fetchPresignedText(url) {
14598
+ if (!isProxyConfigured()) {
14599
+ const resp = await fetch(url, { signal: AbortSignal.timeout(CLIENT_REQUEST_HANDLER.requestTimeout) });
14600
+ if (!resp.ok) return void 0;
14601
+ return resp.text();
14602
+ }
14603
+ const agent = new ProxyRoutingAgent();
14604
+ try {
14605
+ return await new Promise((resolvePromise, rejectPromise) => {
14606
+ get(url, {
14607
+ agent,
14608
+ signal: AbortSignal.timeout(CLIENT_REQUEST_HANDLER.requestTimeout)
14609
+ }, (res) => {
14610
+ const status = res.statusCode ?? 0;
14611
+ if (status < 200 || status >= 300) {
14612
+ res.resume();
14613
+ resolvePromise(void 0);
14614
+ return;
14615
+ }
14616
+ const chunks = [];
14617
+ res.on("data", (c) => chunks.push(c));
14618
+ res.on("end", () => resolvePromise(Buffer.concat(chunks).toString("utf-8")));
14619
+ res.on("error", rejectPromise);
14620
+ }).on("error", rejectPromise);
14621
+ });
14622
+ } finally {
14623
+ agent.destroy();
14624
+ }
14625
+ }
14426
14626
  const supplementLambdaFunction = async ({ physicalId, region }) => {
14427
14627
  const name = str$1(physicalId);
14428
14628
  if (!name) return void 0;