@fjall/components-infrastructure 39.0.12 → 39.0.14
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/lib/layers/secrets-resolver/bin/aws-read.mjs +672 -0
- package/dist/lib/layers/secrets-resolver/bin/error-identity.mjs +7 -4
- package/dist/lib/layers/secrets-resolver/bin/mask.mjs +250 -0
- package/dist/lib/layers/secrets-resolver/bin/resolve-secrets +24 -8
- package/dist/lib/layers/secrets-resolver/bin/resolve-secrets.mjs +442 -217
- package/dist/lib/resources/aws/compute/lambda.d.ts +18 -13
- package/dist/lib/resources/aws/compute/lambda.js +27 -16
- package/dist/lib/utils/validationLogger.js +10 -6
- package/package.json +9 -3
|
@@ -0,0 +1,672 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The secrets resolver's AWS client: it signs and sends the resolver's reads,
|
|
3
|
+
* Systems Manager's GetParameters and Secrets Manager's GetSecretValue, with
|
|
4
|
+
* the function's own credentials, as SigV4 over a JSON 1.1 POST, through
|
|
5
|
+
* `node:crypto` and `node:https`. It loads no package: the layer runs alone in
|
|
6
|
+
* /opt/bin, before the runtime starts. `callAws` is its one entry.
|
|
7
|
+
*
|
|
8
|
+
* The rules it follows are the AWS SDK for JavaScript's, and tests hold each
|
|
9
|
+
* of them to the SDK at every SDK bump: the signature to @smithy/signature-v4
|
|
10
|
+
* and the host to each client's endpoint rules for every Region Fjall deploys
|
|
11
|
+
* to (lib/__tests__/secretsResolverAwsReadSigning.test.ts), and the retry
|
|
12
|
+
* classes and backoff bases to @smithy/core's standard retry strategy and the
|
|
13
|
+
* error code to each client's own deserialiser
|
|
14
|
+
* (lib/__tests__/secretsResolverAwsReadRetries.test.ts). Where it does less
|
|
15
|
+
* than the SDK, it fails closed: it reads only in the `aws` partition and
|
|
16
|
+
* refuses any other Region by name; it corrects for no clock skew, so a skew
|
|
17
|
+
* refusal stops the read; and it honours no environment proxy, so a read goes
|
|
18
|
+
* direct or not at all. It also waits out no retry hint and keeps no retry
|
|
19
|
+
* capacity, as the SDK's standard strategy does, so a retry can come sooner
|
|
20
|
+
* than the SDK's, within the same attempts and the same deadline.
|
|
21
|
+
*
|
|
22
|
+
* A failure's message is identifier-only by construction: fixed text, the
|
|
23
|
+
* service's name, an error code from the closed list `NAMED_CODES`, an HTTP
|
|
24
|
+
* status, a request id in lowercase UUID shape, a length, the function's
|
|
25
|
+
* Region and an error's class and code (`describeErrorIdentity`). It never
|
|
26
|
+
* holds an answer's body or message, a configured URL, or a credential.
|
|
27
|
+
*
|
|
28
|
+
* Every signed header is set with `setHeader` before the request ends, never
|
|
29
|
+
* in the request's options, which Node's debug output prints: with the
|
|
30
|
+
* headers in the options, the session token, the access key id and the
|
|
31
|
+
* signature reached stderr under NODE_DEBUG=https and * over `https:`, under
|
|
32
|
+
* net and * over `http:`, and on Node 20 under http as well (Node 20.19.2,
|
|
33
|
+
* 22.23.2, 24.18.1 and 24.19.0, measured 2026-10-16). Every request goes
|
|
34
|
+
* through an agent of this module's own, never Node's global agent, which
|
|
35
|
+
* under NODE_USE_ENV_PROXY=1 sent its requests to the proxy that HTTPS_PROXY,
|
|
36
|
+
* HTTP_PROXY or their lowercase forms name, as a CONNECT or as the signed
|
|
37
|
+
* request itself (Node 22.23.2, 24.18.1 and 24.19.0, measured 2026-10-16;
|
|
38
|
+
* FJL-1510). lib/__tests__/secretsResolverAwsReadTransport.test.ts holds
|
|
39
|
+
* both. A function whose only route out is such a proxy therefore gets no
|
|
40
|
+
* read through it, as a client on the SDK's default Node handler gets none.
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
import { createHash, createHmac } from "node:crypto";
|
|
44
|
+
import { Agent as HttpAgent, request as httpRequest } from "node:http";
|
|
45
|
+
import { Agent as HttpsAgent, request as httpsRequest } from "node:https";
|
|
46
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
47
|
+
|
|
48
|
+
import { describeErrorIdentity } from "./error-identity.mjs";
|
|
49
|
+
|
|
50
|
+
/** The resolver's budget for all of its reads, which one signal carries. */
|
|
51
|
+
export const DEADLINE_MS = 6000;
|
|
52
|
+
|
|
53
|
+
/** How long the resolver lets a read outlive its deadline before it stops itself. */
|
|
54
|
+
export const BACKSTOP_MS = DEADLINE_MS + 500;
|
|
55
|
+
|
|
56
|
+
/** How long one attempt may take: its connection, its TLS and its answer. */
|
|
57
|
+
export const ATTEMPT_TIMEOUT_MS = 3000;
|
|
58
|
+
|
|
59
|
+
/** One attempt and up to two retries, the SDK's default. */
|
|
60
|
+
export const MAX_ATTEMPTS = 3;
|
|
61
|
+
|
|
62
|
+
/** The full-jitter backoff bases of the SDK's standard retry strategy. */
|
|
63
|
+
export const RETRY_DELAY_BASE_MS = Object.freeze({
|
|
64
|
+
throttling: 500,
|
|
65
|
+
transient: 100
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
/** The most names one GetParameters call takes. */
|
|
69
|
+
export const GET_PARAMETERS_BATCH_SIZE = 10;
|
|
70
|
+
|
|
71
|
+
/** Reads in flight at once, across both services, and each agent's sockets per host. */
|
|
72
|
+
export const READS_IN_FLIGHT = 8;
|
|
73
|
+
|
|
74
|
+
/** The most an answer may hold; a value is at most 64 KB. */
|
|
75
|
+
export const MAX_ANSWER_BYTES = 1024 * 1024;
|
|
76
|
+
|
|
77
|
+
/** The User-Agent of every read, unsigned, so CloudTrail shows the reads as the resolver's. */
|
|
78
|
+
const USER_AGENT = "fjall-secrets-resolver";
|
|
79
|
+
|
|
80
|
+
/** The content type of the JSON 1.1 protocol, which both services speak. */
|
|
81
|
+
const JSON_CONTENT_TYPE = "application/x-amz-json-1.1";
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The two services, as their endpoint rules, signing and wire protocol name
|
|
85
|
+
* them. Systems Manager has a dual-stack host and Secrets Manager does not.
|
|
86
|
+
*/
|
|
87
|
+
export const SERVICES = Object.freeze({
|
|
88
|
+
ssm: Object.freeze({
|
|
89
|
+
label: "Systems Manager",
|
|
90
|
+
endpointPrefix: "ssm",
|
|
91
|
+
signingName: "ssm",
|
|
92
|
+
target: "AmazonSSM",
|
|
93
|
+
endpointVariable: "AWS_ENDPOINT_URL_SSM",
|
|
94
|
+
dualStackHost: true
|
|
95
|
+
}),
|
|
96
|
+
secretsmanager: Object.freeze({
|
|
97
|
+
label: "Secrets Manager",
|
|
98
|
+
endpointPrefix: "secretsmanager",
|
|
99
|
+
signingName: "secretsmanager",
|
|
100
|
+
target: "secretsmanager",
|
|
101
|
+
endpointVariable: "AWS_ENDPOINT_URL_SECRETS_MANAGER",
|
|
102
|
+
dualStackHost: false
|
|
103
|
+
})
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
/** The `aws` partition: the SDK's own pattern for its Regions, and its host suffixes. */
|
|
107
|
+
const AWS_PARTITION = Object.freeze({
|
|
108
|
+
regionPattern: /^(us|eu|ap|sa|ca|me|af|il|mx)-\w+-\d+$/,
|
|
109
|
+
dnsSuffix: "amazonaws.com",
|
|
110
|
+
dualStackDnsSuffix: "api.aws"
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
/** The hosts a configured `http:` URL may name, since the request carries the session token. */
|
|
114
|
+
const LOOPBACK_HOSTS = new Set(["127.0.0.1", "[::1]", "localhost"]);
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The error codes a line names, each mapped to its cure in Fjall's words.
|
|
118
|
+
* Each is a code a client models, one the SDK classes as throttling,
|
|
119
|
+
* transient or clock skew, or one the services' common-errors pages list, so
|
|
120
|
+
* each is an identifier by origin; anything else is "an error code the
|
|
121
|
+
* resolver does not name".
|
|
122
|
+
*/
|
|
123
|
+
export const NAMED_CODES = Object.freeze({
|
|
124
|
+
AccessDeniedException:
|
|
125
|
+
"the function's role may not read it, or decrypt it with its key",
|
|
126
|
+
InvalidKeyId: "its KMS key cannot be used to decrypt it",
|
|
127
|
+
ParameterNotFound: "it does not exist",
|
|
128
|
+
ResourceNotFoundException: "it does not exist",
|
|
129
|
+
DecryptionFailure: "Secrets Manager cannot decrypt it with its KMS key",
|
|
130
|
+
InvalidRequestException:
|
|
131
|
+
"it is not in a state to be read, as a secret scheduled for deletion is not",
|
|
132
|
+
InvalidParameterException:
|
|
133
|
+
"the request names it in a form the service refuses",
|
|
134
|
+
ValidationException: "the request names it in a form the service refuses",
|
|
135
|
+
ThrottlingException: "the service throttled the function's reads",
|
|
136
|
+
TooManyRequestsException: "the service throttled the function's reads",
|
|
137
|
+
InternalServerError: "the service failed",
|
|
138
|
+
InternalServiceError: "the service failed",
|
|
139
|
+
InternalFailure: "the service failed",
|
|
140
|
+
ServiceUnavailable: "the service was unavailable",
|
|
141
|
+
RequestTimeoutException: "the service timed the request out",
|
|
142
|
+
ExpiredTokenException: "the function's credentials had expired",
|
|
143
|
+
UnrecognizedClientException:
|
|
144
|
+
"the service did not recognise the function's credentials",
|
|
145
|
+
InvalidSignatureException: "the service refused the request's signature",
|
|
146
|
+
IncompleteSignature: "the service refused the request's signature"
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* The codes the SDK's standard strategy retries, mirrored from @smithy/core's
|
|
151
|
+
* retry module, whose `isThrottlingError` and `isTransientError` read them,
|
|
152
|
+
* and held to it by the retries test.
|
|
153
|
+
*/
|
|
154
|
+
export const RETRIED_CODES = Object.freeze({
|
|
155
|
+
throttling: Object.freeze([
|
|
156
|
+
"BandwidthLimitExceeded",
|
|
157
|
+
"EC2ThrottledException",
|
|
158
|
+
"LimitExceededException",
|
|
159
|
+
"PriorRequestNotComplete",
|
|
160
|
+
"ProvisionedThroughputExceededException",
|
|
161
|
+
"RequestLimitExceeded",
|
|
162
|
+
"RequestThrottled",
|
|
163
|
+
"RequestThrottledException",
|
|
164
|
+
"SlowDown",
|
|
165
|
+
"ThrottledException",
|
|
166
|
+
"Throttling",
|
|
167
|
+
"ThrottlingException",
|
|
168
|
+
"TooManyRequestsException",
|
|
169
|
+
"TransactionInProgressException"
|
|
170
|
+
]),
|
|
171
|
+
transient: Object.freeze([
|
|
172
|
+
"TimeoutError",
|
|
173
|
+
"RequestTimeout",
|
|
174
|
+
"RequestTimeoutException"
|
|
175
|
+
])
|
|
176
|
+
});
|
|
177
|
+
const THROTTLING_CODES = new Set(RETRIED_CODES.throttling);
|
|
178
|
+
const TRANSIENT_CODES = new Set(RETRIED_CODES.transient);
|
|
179
|
+
const THROTTLING_STATUS = 429;
|
|
180
|
+
const TRANSIENT_STATUSES = new Set([500, 502, 503, 504]);
|
|
181
|
+
const TRANSIENT_NETWORK_CODES = new Set([
|
|
182
|
+
"ECONNRESET",
|
|
183
|
+
"ECONNREFUSED",
|
|
184
|
+
"EPIPE",
|
|
185
|
+
"ETIMEDOUT",
|
|
186
|
+
"EHOSTUNREACH",
|
|
187
|
+
"ENETUNREACH",
|
|
188
|
+
"ENOTFOUND",
|
|
189
|
+
"EAI_AGAIN"
|
|
190
|
+
]);
|
|
191
|
+
|
|
192
|
+
/** How deep the SDK looks along an error's causes for a transient one. */
|
|
193
|
+
const CAUSE_DEPTH = 12;
|
|
194
|
+
|
|
195
|
+
/** The only request id a line repeats: a lowercase UUID. */
|
|
196
|
+
const REQUEST_ID_SHAPE =
|
|
197
|
+
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
198
|
+
|
|
199
|
+
const BUDGET = `the resolver's ${DEADLINE_MS / 1000}-second budget`;
|
|
200
|
+
|
|
201
|
+
/** Why a read that never started failed, which names no service, since none was asked. */
|
|
202
|
+
const NOT_STARTED = `no read of it started within ${BUDGET}, because the reads before it used the budget`;
|
|
203
|
+
|
|
204
|
+
const NO_CREDENTIALS =
|
|
205
|
+
"the function's environment holds no AWS credentials (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY), as Lambda sets them for on-demand and provisioned starts";
|
|
206
|
+
|
|
207
|
+
/** A read that failed, named in this module's words, so its message may be written. */
|
|
208
|
+
export class AwsReadFailure extends Error {}
|
|
209
|
+
|
|
210
|
+
const AGENTS = Object.freeze({
|
|
211
|
+
"http:": new HttpAgent({ keepAlive: true, maxSockets: READS_IN_FLIGHT }),
|
|
212
|
+
"https:": new HttpsAgent({ keepAlive: true, maxSockets: READS_IN_FLIGHT })
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
const isPresent = (value) => typeof value === "string" && value !== "";
|
|
216
|
+
|
|
217
|
+
/** A setting the SDK turns on only when it is exactly `true`, and leaves off for any other value. */
|
|
218
|
+
const isOn = (env, name) => env[name] === "true";
|
|
219
|
+
|
|
220
|
+
function serviceNamed(service) {
|
|
221
|
+
if (!Object.hasOwn(SERVICES, service)) {
|
|
222
|
+
throw new TypeError("the resolver reads only ssm and secretsmanager");
|
|
223
|
+
}
|
|
224
|
+
return SERVICES[service];
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Where `service` is read in `region`, by the SDK's precedence: no configured
|
|
229
|
+
* URL when AWS_IGNORE_CONFIGURED_ENDPOINT_URLS is on; otherwise the service's
|
|
230
|
+
* own variable, then AWS_ENDPOINT_URL; otherwise the `aws` partition's host,
|
|
231
|
+
* with AWS_USE_FIPS_ENDPOINT and AWS_USE_DUALSTACK_ENDPOINT. Of a configured
|
|
232
|
+
* URL it takes the scheme, host, port and path, as the SDK does, and sends
|
|
233
|
+
* neither its query, which the SDK drops, nor its userinfo.
|
|
234
|
+
*/
|
|
235
|
+
export function endpointFor(service, region, env) {
|
|
236
|
+
const spec = serviceNamed(service);
|
|
237
|
+
const variable = isOn(env, "AWS_IGNORE_CONFIGURED_ENDPOINT_URLS")
|
|
238
|
+
? undefined
|
|
239
|
+
: [spec.endpointVariable, "AWS_ENDPOINT_URL"].find((name) =>
|
|
240
|
+
isPresent(env[name])
|
|
241
|
+
);
|
|
242
|
+
if (variable !== undefined) {
|
|
243
|
+
const named = `the endpoint ${spec.endpointVariable} or AWS_ENDPOINT_URL names`;
|
|
244
|
+
let url;
|
|
245
|
+
try {
|
|
246
|
+
url = new URL(env[variable]);
|
|
247
|
+
} catch {
|
|
248
|
+
// The URL can hold userinfo, so neither it nor the parser's message is repeated.
|
|
249
|
+
throw new AwsReadFailure(`${named} is not a URL`);
|
|
250
|
+
}
|
|
251
|
+
const loopbackHttp =
|
|
252
|
+
url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname);
|
|
253
|
+
if (url.protocol !== "https:" && !loopbackHttp) {
|
|
254
|
+
throw new AwsReadFailure(
|
|
255
|
+
`${named} is not https, and the request carries the function's session token`
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
return {
|
|
259
|
+
protocol: url.protocol,
|
|
260
|
+
hostname: url.hostname.replace(/^\[(.*)\]$/, "$1"),
|
|
261
|
+
port: url.port,
|
|
262
|
+
host: url.host,
|
|
263
|
+
path: url.pathname
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
if (!AWS_PARTITION.regionPattern.test(region)) {
|
|
267
|
+
throw new AwsReadFailure(
|
|
268
|
+
`the function's Region ${region} is in a partition the resolver does not read from`
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
const fips = isOn(env, "AWS_USE_FIPS_ENDPOINT") ? "-fips" : "";
|
|
272
|
+
const suffix =
|
|
273
|
+
isOn(env, "AWS_USE_DUALSTACK_ENDPOINT") && spec.dualStackHost
|
|
274
|
+
? AWS_PARTITION.dualStackDnsSuffix
|
|
275
|
+
: AWS_PARTITION.dnsSuffix;
|
|
276
|
+
const host = `${spec.endpointPrefix}${fips}.${region}.${suffix}`;
|
|
277
|
+
return { protocol: "https:", hostname: host, port: "", host, path: "/" };
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** The function's credentials, from the variables Lambda sets at on-demand and provisioned starts. */
|
|
281
|
+
export function environmentCredentials(env) {
|
|
282
|
+
const accessKeyId = env.AWS_ACCESS_KEY_ID;
|
|
283
|
+
const secretAccessKey = env.AWS_SECRET_ACCESS_KEY;
|
|
284
|
+
const sessionToken = env.AWS_SESSION_TOKEN;
|
|
285
|
+
if (!isPresent(accessKeyId) || !isPresent(secretAccessKey)) {
|
|
286
|
+
throw new AwsReadFailure(NO_CREDENTIALS);
|
|
287
|
+
}
|
|
288
|
+
return {
|
|
289
|
+
accessKeyId,
|
|
290
|
+
secretAccessKey,
|
|
291
|
+
...(isPresent(sessionToken) && { sessionToken })
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
|
|
296
|
+
const hmac = (key, text) => createHmac("sha256", key).update(text).digest();
|
|
297
|
+
const escapeUri = (text) =>
|
|
298
|
+
encodeURIComponent(text).replace(
|
|
299
|
+
/[!'()*]/g,
|
|
300
|
+
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`
|
|
301
|
+
);
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* The request's path as SigV4 signs it for a service other than S3: empty
|
|
305
|
+
* and dot segments resolved, then the path, already percent-encoded as it is
|
|
306
|
+
* sent, encoded once more, with each `/` kept.
|
|
307
|
+
*/
|
|
308
|
+
function canonicalPath(path) {
|
|
309
|
+
const segments = [];
|
|
310
|
+
for (const segment of path.split("/")) {
|
|
311
|
+
if (segment === "" || segment === ".") continue;
|
|
312
|
+
if (segment === "..") segments.pop();
|
|
313
|
+
else segments.push(segment);
|
|
314
|
+
}
|
|
315
|
+
const lead = path.startsWith("/") ? "/" : "";
|
|
316
|
+
const trail = segments.length > 0 && path.endsWith("/") ? "/" : "";
|
|
317
|
+
return escapeUri(`${lead}${segments.join("/")}${trail}`).replace(/%2F/g, "/");
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* The headers a request is signed with, as SigV4 signs a JSON 1.1 POST:
|
|
322
|
+
* content-type, host, x-amz-date, x-amz-target and, with a session token,
|
|
323
|
+
* x-amz-security-token, then the Authorization header over them.
|
|
324
|
+
*/
|
|
325
|
+
export function signedHeaders({
|
|
326
|
+
service,
|
|
327
|
+
endpoint,
|
|
328
|
+
operation,
|
|
329
|
+
body,
|
|
330
|
+
region,
|
|
331
|
+
credentials,
|
|
332
|
+
date
|
|
333
|
+
}) {
|
|
334
|
+
const spec = serviceNamed(service);
|
|
335
|
+
const amzDate = date
|
|
336
|
+
.toISOString()
|
|
337
|
+
.replace(/\.\d{3}Z$/, "Z")
|
|
338
|
+
.replace(/[-:]/g, "");
|
|
339
|
+
const day = amzDate.slice(0, 8);
|
|
340
|
+
const headers = {
|
|
341
|
+
"content-type": JSON_CONTENT_TYPE,
|
|
342
|
+
host: endpoint.host,
|
|
343
|
+
"x-amz-date": amzDate,
|
|
344
|
+
"x-amz-target": `${spec.target}.${operation}`,
|
|
345
|
+
...(credentials.sessionToken !== undefined && {
|
|
346
|
+
"x-amz-security-token": credentials.sessionToken
|
|
347
|
+
})
|
|
348
|
+
};
|
|
349
|
+
const names = Object.keys(headers).sort();
|
|
350
|
+
const canonicalRequest = [
|
|
351
|
+
"POST",
|
|
352
|
+
canonicalPath(endpoint.path),
|
|
353
|
+
"",
|
|
354
|
+
...names.map(
|
|
355
|
+
(name) => `${name}:${headers[name].trim().replace(/\s+/g, " ")}`
|
|
356
|
+
),
|
|
357
|
+
"",
|
|
358
|
+
names.join(";"),
|
|
359
|
+
sha256Hex(body)
|
|
360
|
+
].join("\n");
|
|
361
|
+
const scope = `${day}/${region}/${spec.signingName}/aws4_request`;
|
|
362
|
+
const stringToSign = [
|
|
363
|
+
"AWS4-HMAC-SHA256",
|
|
364
|
+
amzDate,
|
|
365
|
+
scope,
|
|
366
|
+
sha256Hex(canonicalRequest)
|
|
367
|
+
].join("\n");
|
|
368
|
+
const signingKey = [day, region, spec.signingName, "aws4_request"].reduce(
|
|
369
|
+
hmac,
|
|
370
|
+
`AWS4${credentials.secretAccessKey}`
|
|
371
|
+
);
|
|
372
|
+
const signature = createHmac("sha256", signingKey)
|
|
373
|
+
.update(stringToSign)
|
|
374
|
+
.digest("hex");
|
|
375
|
+
return {
|
|
376
|
+
...headers,
|
|
377
|
+
authorization: `AWS4-HMAC-SHA256 Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${names.join(";")}, Signature=${signature}`
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** An error code as the SDK cuts one: at a comma, at a colon, and after a namespace's `#`. */
|
|
382
|
+
function sanitiseErrorCode(raw) {
|
|
383
|
+
let code = typeof raw === "number" ? String(raw) : raw;
|
|
384
|
+
if (code.includes(",")) code = code.split(",")[0];
|
|
385
|
+
if (code.includes(":")) code = code.split(":")[0];
|
|
386
|
+
if (code.includes("#")) code = code.split("#")[1];
|
|
387
|
+
return code;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* The error code of an answer that refused a read, read as the SDK's JSON 1.1
|
|
392
|
+
* protocol reads it: the body's `__type`, then its `code` field in any case,
|
|
393
|
+
* then the X-Amzn-ErrorType header. A body that is not JSON holds no code,
|
|
394
|
+
* the header's included, as the SDK reads none from one. A value that is
|
|
395
|
+
* neither a string nor a number is no code, where the SDK's own handler
|
|
396
|
+
* throws.
|
|
397
|
+
*/
|
|
398
|
+
export function readErrorCode(headers, text) {
|
|
399
|
+
let data = {};
|
|
400
|
+
if (text.length > 0) {
|
|
401
|
+
let parsed;
|
|
402
|
+
try {
|
|
403
|
+
parsed = JSON.parse(text);
|
|
404
|
+
} catch {
|
|
405
|
+
return undefined;
|
|
406
|
+
}
|
|
407
|
+
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed))
|
|
408
|
+
data = parsed;
|
|
409
|
+
}
|
|
410
|
+
const codeKey = Object.keys(data).find((key) => key.toLowerCase() === "code");
|
|
411
|
+
const raw = Object.hasOwn(data, "__type")
|
|
412
|
+
? data.__type
|
|
413
|
+
: codeKey !== undefined
|
|
414
|
+
? data[codeKey]
|
|
415
|
+
: headers["x-amzn-errortype"];
|
|
416
|
+
return typeof raw === "string" || typeof raw === "number"
|
|
417
|
+
? sanitiseErrorCode(raw)
|
|
418
|
+
: undefined;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function readRequestId(headers) {
|
|
422
|
+
const id = headers["x-amzn-requestid"];
|
|
423
|
+
return typeof id === "string" && REQUEST_ID_SHAPE.test(id) ? id : undefined;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/** Whether a failure with no answer is one the SDK retries, its causes followed as the SDK follows them. */
|
|
427
|
+
function isTransientNetworkError(error) {
|
|
428
|
+
let link = error;
|
|
429
|
+
for (
|
|
430
|
+
let depth = 0;
|
|
431
|
+
depth < CAUSE_DEPTH && typeof link === "object" && link !== null;
|
|
432
|
+
depth += 1
|
|
433
|
+
) {
|
|
434
|
+
if (link.name === "AbortError") return false;
|
|
435
|
+
if (
|
|
436
|
+
TRANSIENT_CODES.has(link.name) ||
|
|
437
|
+
TRANSIENT_NETWORK_CODES.has(link.code)
|
|
438
|
+
)
|
|
439
|
+
return true;
|
|
440
|
+
link = link.cause;
|
|
441
|
+
}
|
|
442
|
+
return false;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* How a failed attempt is retried: `throttling` and `transient` are the SDK's
|
|
447
|
+
* retriable classes, which choose the backoff base; `undefined` stops the read.
|
|
448
|
+
* An answer that is not JSON is retried, as the resolver always retried one,
|
|
449
|
+
* though no SDK class names it.
|
|
450
|
+
*/
|
|
451
|
+
export function retryClassOf(failure) {
|
|
452
|
+
switch (failure.kind) {
|
|
453
|
+
case "refused":
|
|
454
|
+
if (
|
|
455
|
+
failure.status === THROTTLING_STATUS ||
|
|
456
|
+
THROTTLING_CODES.has(failure.code)
|
|
457
|
+
)
|
|
458
|
+
return "throttling";
|
|
459
|
+
return TRANSIENT_CODES.has(failure.code) ||
|
|
460
|
+
TRANSIENT_STATUSES.has(failure.status)
|
|
461
|
+
? "transient"
|
|
462
|
+
: undefined;
|
|
463
|
+
case "network":
|
|
464
|
+
return isTransientNetworkError(failure.error) ? "transient" : undefined;
|
|
465
|
+
case "timeout":
|
|
466
|
+
case "unparseable":
|
|
467
|
+
return "transient";
|
|
468
|
+
default:
|
|
469
|
+
return undefined;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** What an answer that refused a read says, after the service's name. */
|
|
474
|
+
function refusalText({ status, code, requestId }) {
|
|
475
|
+
if (code !== undefined && Object.hasOwn(NAMED_CODES, code)) {
|
|
476
|
+
const id = requestId === undefined ? "" : `, request ${requestId}`;
|
|
477
|
+
return `answered ${code} (HTTP ${status}${id}): ${NAMED_CODES[code]}`;
|
|
478
|
+
}
|
|
479
|
+
const id = requestId === undefined ? "" : ` (request ${requestId})`;
|
|
480
|
+
return `answered HTTP ${status} with an error code the resolver does not name${id}`;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/** Why a read failed, from its last attempt, once it is not retried or its attempts are spent. */
|
|
484
|
+
function reasonFor(spec, failure, attempts) {
|
|
485
|
+
switch (failure.kind) {
|
|
486
|
+
case "refused":
|
|
487
|
+
return attempts === MAX_ATTEMPTS && retryClassOf(failure) !== undefined
|
|
488
|
+
? `${spec.label} failed ${attempts} attempts; the last ${refusalText(failure)}`
|
|
489
|
+
: `${spec.label} ${refusalText(failure)}`;
|
|
490
|
+
case "unparseable":
|
|
491
|
+
return `${spec.label} answered a body that is not valid JSON (${failure.length} characters)`;
|
|
492
|
+
case "oversize":
|
|
493
|
+
return `${spec.label} answered more than ${MAX_ANSWER_BYTES} bytes`;
|
|
494
|
+
default:
|
|
495
|
+
return describeErrorIdentity(failure.error);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function budgetSpent(spec) {
|
|
500
|
+
return `${spec.label} did not answer within ${BUDGET}. A function in a VPC needs a route to it: a NAT gateway or an interface endpoint.`;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/** What one answer was: the value read, or why it was not one. */
|
|
504
|
+
function answerOutcome(response, text) {
|
|
505
|
+
const status = response.statusCode;
|
|
506
|
+
if (status >= 200 && status < 300) {
|
|
507
|
+
try {
|
|
508
|
+
return { kind: "answered", value: JSON.parse(text) };
|
|
509
|
+
} catch {
|
|
510
|
+
// The body holds the values, and V8's message quotes a window of it.
|
|
511
|
+
return { kind: "unparseable", length: text.length };
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
return {
|
|
515
|
+
kind: "refused",
|
|
516
|
+
status,
|
|
517
|
+
code: readErrorCode(response.headers, text),
|
|
518
|
+
requestId: readRequestId(response.headers)
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/** One signed attempt, which resolves to its outcome and never rejects but on a caller's mistake. */
|
|
523
|
+
function attempt({
|
|
524
|
+
service,
|
|
525
|
+
endpoint,
|
|
526
|
+
operation,
|
|
527
|
+
body,
|
|
528
|
+
region,
|
|
529
|
+
credentials,
|
|
530
|
+
deadline
|
|
531
|
+
}) {
|
|
532
|
+
const timer = AbortSignal.timeout(ATTEMPT_TIMEOUT_MS);
|
|
533
|
+
const signal = AbortSignal.any([deadline, timer]);
|
|
534
|
+
const headers = {
|
|
535
|
+
...signedHeaders({
|
|
536
|
+
service,
|
|
537
|
+
endpoint,
|
|
538
|
+
operation,
|
|
539
|
+
body,
|
|
540
|
+
region,
|
|
541
|
+
credentials,
|
|
542
|
+
date: new Date()
|
|
543
|
+
}),
|
|
544
|
+
"content-length": String(Buffer.byteLength(body)),
|
|
545
|
+
"user-agent": USER_AGENT
|
|
546
|
+
};
|
|
547
|
+
const secure = endpoint.protocol === "https:";
|
|
548
|
+
return new Promise((resolve) => {
|
|
549
|
+
let settled = false;
|
|
550
|
+
const settle = (outcome) => {
|
|
551
|
+
if (settled) return;
|
|
552
|
+
settled = true;
|
|
553
|
+
resolve(outcome);
|
|
554
|
+
};
|
|
555
|
+
// The attempt's signal aborts only through the deadline or its own timer.
|
|
556
|
+
// The timer is read here, not through the signal, so the request's
|
|
557
|
+
// listeners hold it until it fires. On Node 20, AbortSignal.any holds its
|
|
558
|
+
// sources weakly (measured on 20.19.2, 2 November 2026), so a timer nothing
|
|
559
|
+
// else holds can be collected, and the attempt then runs to the deadline.
|
|
560
|
+
const ended = (error) =>
|
|
561
|
+
settle(
|
|
562
|
+
deadline.aborted
|
|
563
|
+
? { kind: "deadline" }
|
|
564
|
+
: timer.aborted
|
|
565
|
+
? { kind: "timeout", error }
|
|
566
|
+
: { kind: "network", error }
|
|
567
|
+
);
|
|
568
|
+
const request = (secure ? httpsRequest : httpRequest)({
|
|
569
|
+
protocol: endpoint.protocol,
|
|
570
|
+
hostname: endpoint.hostname,
|
|
571
|
+
...(endpoint.port !== "" && { port: Number(endpoint.port) }),
|
|
572
|
+
path: endpoint.path,
|
|
573
|
+
method: "POST",
|
|
574
|
+
agent: AGENTS[endpoint.protocol],
|
|
575
|
+
signal,
|
|
576
|
+
...(secure && { rejectUnauthorized: true })
|
|
577
|
+
});
|
|
578
|
+
request.on("error", ended);
|
|
579
|
+
request.on("response", (response) => {
|
|
580
|
+
const chunks = [];
|
|
581
|
+
let size = 0;
|
|
582
|
+
response.on("data", (chunk) => {
|
|
583
|
+
size += chunk.length;
|
|
584
|
+
if (size > MAX_ANSWER_BYTES) {
|
|
585
|
+
settle({ kind: "oversize" });
|
|
586
|
+
request.destroy();
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
chunks.push(chunk);
|
|
590
|
+
});
|
|
591
|
+
response.on("error", ended);
|
|
592
|
+
response.on("end", () =>
|
|
593
|
+
settle(answerOutcome(response, Buffer.concat(chunks).toString("utf8")))
|
|
594
|
+
);
|
|
595
|
+
});
|
|
596
|
+
try {
|
|
597
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
598
|
+
request.setHeader(name, value);
|
|
599
|
+
}
|
|
600
|
+
} catch (error) {
|
|
601
|
+
request.destroy();
|
|
602
|
+
throw error;
|
|
603
|
+
}
|
|
604
|
+
request.end(body);
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* Waits `ms`, or less when `deadline` aborts first, and says whether the wait
|
|
610
|
+
* ran its course. Its listener is on a signal of its own, so the reads in
|
|
611
|
+
* flight add none to the deadline they share.
|
|
612
|
+
*/
|
|
613
|
+
async function waitUnlessAborted(ms, deadline) {
|
|
614
|
+
try {
|
|
615
|
+
await delay(ms, undefined, { signal: AbortSignal.any([deadline]) });
|
|
616
|
+
return true;
|
|
617
|
+
} catch (error) {
|
|
618
|
+
if (deadline.aborted) return false;
|
|
619
|
+
throw error;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* `operation` on `service`, with `payload` as its JSON body, in `region`,
|
|
625
|
+
* signed with the credentials in `env`: resolves to the answer's JSON value,
|
|
626
|
+
* whose shape the caller checks. A throttled or transient failure is retried
|
|
627
|
+
* as the SDK's standard strategy retries it, with full-jitter backoff, up to
|
|
628
|
+
* `MAX_ATTEMPTS` attempts of `ATTEMPT_TIMEOUT_MS` each, all within
|
|
629
|
+
* `deadline`; anything else stops the read at once. A read entered after
|
|
630
|
+
* `deadline` has aborted is refused as one that never started. Rejects with
|
|
631
|
+
* an `AwsReadFailure`, whose message says why in words that may be written,
|
|
632
|
+
* or with a `TypeError`, for a service this module does not read or a header
|
|
633
|
+
* value Node refuses to send, which only the error's identity may name.
|
|
634
|
+
*/
|
|
635
|
+
export async function callAws({
|
|
636
|
+
service,
|
|
637
|
+
operation,
|
|
638
|
+
payload,
|
|
639
|
+
region,
|
|
640
|
+
env,
|
|
641
|
+
deadline
|
|
642
|
+
}) {
|
|
643
|
+
const spec = serviceNamed(service);
|
|
644
|
+
const endpoint = endpointFor(service, region, env);
|
|
645
|
+
const credentials = environmentCredentials(env);
|
|
646
|
+
if (deadline.aborted) throw new AwsReadFailure(NOT_STARTED);
|
|
647
|
+
const body = JSON.stringify(payload);
|
|
648
|
+
for (let attempts = 1; ; attempts += 1) {
|
|
649
|
+
const outcome = await attempt({
|
|
650
|
+
service,
|
|
651
|
+
endpoint,
|
|
652
|
+
operation,
|
|
653
|
+
body,
|
|
654
|
+
region,
|
|
655
|
+
credentials,
|
|
656
|
+
deadline
|
|
657
|
+
});
|
|
658
|
+
if (outcome.kind === "answered") return outcome.value;
|
|
659
|
+
if (outcome.kind === "deadline")
|
|
660
|
+
throw new AwsReadFailure(budgetSpent(spec));
|
|
661
|
+
const retryClass = retryClassOf(outcome);
|
|
662
|
+
if (retryClass === undefined || attempts === MAX_ATTEMPTS) {
|
|
663
|
+
throw new AwsReadFailure(reasonFor(spec, outcome, attempts));
|
|
664
|
+
}
|
|
665
|
+
const ceiling = RETRY_DELAY_BASE_MS[retryClass] * 2 ** (attempts - 1);
|
|
666
|
+
if (
|
|
667
|
+
!(await waitUnlessAborted(Math.floor(Math.random() * ceiling), deadline))
|
|
668
|
+
) {
|
|
669
|
+
throw new AwsReadFailure(budgetSpent(spec));
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
}
|
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* How the secrets resolver names a failure without anything it carries: the
|
|
3
3
|
* class name and code of the error and of up to two causes, as
|
|
4
|
-
* `TypeError (cause: AggregateError ECONNREFUSED)`.
|
|
5
|
-
* bytes of an answer it could not parse as HTTP on
|
|
4
|
+
* `TypeError (cause: AggregateError ECONNREFUSED)`. `node:https` keeps the
|
|
5
|
+
* bytes of an answer it could not parse as HTTP on the error's `rawPacket`
|
|
6
|
+
* (`lib/__tests__/secretsResolverErrorAnswers.test.ts`). Node's fetch, which
|
|
7
|
+
* the layers through 39.0.12 read with, keeps them on its cause and quotes a
|
|
6
8
|
* header value it refuses in its message (Node 20.19.2, 22.17.1, 24.18.1,
|
|
7
|
-
* 24.19.0 and 24.21.0, measured 2026-10-12)
|
|
9
|
+
* 24.19.0 and 24.21.0, measured 2026-10-12). So no message or field of an
|
|
10
|
+
* error is repeated.
|
|
8
11
|
*
|
|
9
12
|
* The rule is `describeErrorIdentity`'s in `@fjall/util` from 40.0.0, which
|
|
10
13
|
* this layer cannot load; 39.x's `@fjall/util` has no such function, so
|
|
@@ -40,7 +43,7 @@ function nameAndCode(link) {
|
|
|
40
43
|
* `err` named by its class name and code, and its causes', never by a
|
|
41
44
|
* message. A name or code is repeated only in the shape Node and undici give
|
|
42
45
|
* one; a shape is not proof of origin, so this is for errors the runtime
|
|
43
|
-
* built, as a failed
|
|
46
|
+
* built, as a failed request or body read is.
|
|
44
47
|
*/
|
|
45
48
|
export function describeErrorIdentity(err) {
|
|
46
49
|
const links = [];
|