@fjall/components-infrastructure 39.0.11 → 39.0.13

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.
@@ -1,132 +1,99 @@
1
1
  /**
2
- * Fjall Secrets Resolver — runs before the Lambda handler via
3
- * AWS_LAMBDA_EXEC_WRAPPER.
2
+ * Fjall Secrets Resolver — runs before the Lambda runtime starts, through the
3
+ * wrapper beside this file, which AWS_LAMBDA_EXEC_WRAPPER names.
4
4
  *
5
- * Resolves secrets from two sources using the AWS Parameters and Secrets
6
- * Extension HTTP cache at localhost:2773:
5
+ * It reads each secret the function's configuration names, with the
6
+ * function's own credentials, through the AWS client beside it (`callAws` in
7
+ * `aws-read.mjs`):
7
8
  *
8
- * 1. SSM Parameter Store (user-managed secrets via `fjall secrets set`)
9
- * Reads SSM_SECRETS_PATH + SSM_SECRET_NAMES and fetches each parameter.
9
+ * 1. SSM Parameter Store (secrets set with `fjall secrets set`):
10
+ * SSM_SECRETS_PATH and SSM_SECRET_NAMES name each parameter, read with
11
+ * Systems Manager's GetParameters, with decryption, up to
12
+ * GET_PARAMETERS_BATCH_SIZE names a call.
10
13
  *
11
- * 2. Secrets Manager (CDK-managed secrets, e.g. database credentials)
12
- * Scans for *_SECRET_ARN env vars, fetches each secret, optionally
13
- * extracts a JSON field via the matching *_SECRET_FIELD var, and names it
14
- * by the prefix (e.g. DATABASE_PASSWORD_SECRET_ARN → DATABASE_PASSWORD).
14
+ * 2. Secrets Manager (CDK-managed secrets, e.g. database credentials): each
15
+ * *_SECRET_ARN variable names a secret, read with GetSecretValue, one call
16
+ * per secret. The matching *_SECRET_FIELD variable names a field of its
17
+ * JSON, and the value is named by the prefix (e.g.
18
+ * DATABASE_PASSWORD_SECRET_ARN → DATABASE_PASSWORD).
19
+ *
20
+ * Every read starts at once, up to READS_IN_FLIGHT at a time, and each
21
+ * carries one deadline, aborted DEADLINE_MS after the first starts by a timer
22
+ * this script clears once every read has settled. A backstop BACKSTOP_MS
23
+ * after the same start ends the process with a line of its own, for a read
24
+ * that ignores its abort; it is cleared at the same moment, before any line
25
+ * is built.
15
26
  *
16
27
  * Writes one `NAME=VALUE` line per secret to stdout, VALUE as `encodeValue`
17
- * writes it. The bash wrapper beside this file decodes each VALUE with
18
- * `printf '%b'` and execs into the Lambda runtime with it in the
19
- * environment, never evaluating it.
28
+ * writes it, the SSM names in SSM_SECRET_NAMES order and then the Secrets
29
+ * Manager prefixes in the environment's order. The bash wrapper beside this
30
+ * file decodes each VALUE with `printf '%b'` and execs into the Lambda
31
+ * runtime with it in the environment, never evaluating it. A read that fails
32
+ * stops the function, naming each parameter or secret it could not read, in
33
+ * that order, rather than start it without the secret. Three outcomes stay
34
+ * 39.0.6's, and 40.0.0 stops the function for each. An answer without a value
35
+ * is skipped, and a NUL or an unpaired surrogate is handed over as
36
+ * `encodeValue` says. Three refusals are new on this line. A field is read only
37
+ * as a JSON object's own key, so a field asked of a secret that is not an
38
+ * object stops the function, and so does a field holding an object or a list,
39
+ * where through 39.0.12 the function got `[object Object]`, a list's items
40
+ * joined by commas, or a value the prototype gave. A 200 to `GetParameters`
41
+ * that is not an object, or whose `Parameters` is not a list, stops it too
42
+ * (`NOT_GET_PARAMETERS`, FJL-1470's design § 5), where through 39.0.12 an
43
+ * answer without a parameter was skipped. The inference that these reach no
44
+ * start an earlier release made is FJL-1470's design § 8.2, since no 39.x
45
+ * release has started a function with secrets through the resolver on Lambda.
46
+ * The exit status is 1 unless the values were written:
47
+ * it becomes 0 only in the stdout write's callback, when that callback
48
+ * receives no error, or when there is nothing to write. The process ends at
49
+ * its verdict, once the line that carries it is written, whatever its event
50
+ * loop still holds. A lookup an aborted read started can hold the loop open
51
+ * well past the deadline.
20
52
  *
21
53
  * Every line it writes to stderr, which Lambda sends to the function's
22
- * CloudWatch Logs, is identifier-only: fixed text; what the function's
23
- * configuration holds, a parameter path or a secret's name, ARN and field;
24
- * the position of a name it refuses; an HTTP status; a length or a count; and
25
- * an error's class name and code (`describeErrorIdentity`, in
26
- * `error-identity.mjs` beside this file). It
27
- * never repeats the extension's answer, an error's message or a name it
28
- * refuses: it runs alone in its layer and cannot load `@fjall/util`'s mask.
54
+ * CloudWatch Logs, is identifier-only: fixed text; an error code from the
55
+ * client's closed list `NAMED_CODES`, with its HTTP status and a request id
56
+ * in lowercase UUID shape; the position of a name it refuses; a length or a
57
+ * count; an error's class name and code (`describeErrorIdentity`, in
58
+ * `error-identity.mjs` beside this file); and what the function's
59
+ * configuration holds. It never repeats an answer's body or message, a value,
60
+ * a configured URL or a name it refuses.
29
61
  *
30
- * The Extension may not be ready immediately during INIT phase, so all HTTP
31
- * calls use a retry loop with exponential backoff.
62
+ * Messages are pre-masked at construction. A string of the configuration a
63
+ * line names (the parameter's path, or its name when SSM_SECRETS_PATH is out
64
+ * of its shape; the prefix; the secret's ARN; the field) is named only in its
65
+ * shape (`SECRETS_PATH_SHAPE` with a name in `VALID_ENV_NAME`'s,
66
+ * `VALID_ENV_NAME`, `SECRET_ARN_SHAPE`, `FIELD_SHAPE`), and is then masked
67
+ * whole as `maskSensitiveOutput(text)` in `failureLines`, through `mask.mjs`
68
+ * beside this file: a copy of `@fjall/util`'s mask, generated into the layer
69
+ * because the resolver runs alone in it and cannot load `@fjall/util`. Every
70
+ * spelling a line builds from one of them is built from its masked text. A
71
+ * string out of its shape is described, never quoted or cut. The copy is
72
+ * imported only once a line must be built, so a start whose reads all
73
+ * succeed never loads it.
32
74
  */
33
75
 
76
+ import {
77
+ AwsReadFailure,
78
+ BACKSTOP_MS,
79
+ callAws,
80
+ DEADLINE_MS,
81
+ GET_PARAMETERS_BATCH_SIZE,
82
+ READS_IN_FLIGHT
83
+ } from "./aws-read.mjs";
34
84
  import { describeErrorIdentity } from "./error-identity.mjs";
35
85
 
36
- const EXTENSION_PORT =
37
- process.env.PARAMETERS_SECRETS_EXTENSION_HTTP_PORT || "2773";
38
- const EXTENSION_URL = `http://localhost:${EXTENSION_PORT}`;
39
- const MAX_RETRIES = 5;
40
- const INITIAL_DELAY_MS = 100;
41
- /** Per-request timeout — generous for localhost; total budget bounded by Lambda INIT timeout */
42
- const REQUEST_TIMEOUT_MS = 2000;
86
+ // Every way this process can end before its values are written is a
87
+ // failure: a main() that never settles, with nothing left to wait on, ends
88
+ // with this status.
89
+ process.exitCode = 1;
43
90
 
44
- /** A failure in this script's own words, so its message may be written. */
45
- class ResolverFailure extends Error {
46
- constructor(message, { retriable = false } = {}) {
47
- super(message);
48
- this.retriable = retriable;
49
- }
50
- }
91
+ // Node warns, in a line of its own on stderr, when a TLS connection is made
92
+ // under NODE_TLS_REJECT_UNAUTHORIZED=0, even beside rejectUnauthorized: true.
93
+ // The runtime's environment keeps the function's setting.
94
+ delete process.env.NODE_TLS_REJECT_UNAUTHORIZED;
51
95
 
52
- /**
53
- * What a function's operator checks when the extension refuses a read. Its
54
- * refusal can be for a parameter or secret that does not exist, a role that
55
- * may not read or decrypt it, or throttling, and the body that would say
56
- * which is not repeated.
57
- */
58
- const REFUSAL_CURE =
59
- "Check that it exists, that the function's role may read it and decrypt it with its key, and that Systems Manager or Secrets Manager was not throttling the function's requests.";
60
-
61
- /**
62
- * An answer the extension refused with, named by its status and its body's
63
- * length. The body is AWS's error, which can name the parameter or secret
64
- * and the function's role in words this repository does not control.
65
- */
66
- async function describeRefusal(response) {
67
- const body = await response.text().then(
68
- (text) => `a body of ${text.length} characters, not repeated here`,
69
- () => "a body that could not be read"
70
- );
71
- return `Extension returned ${response.status} with ${body}`;
72
- }
73
-
74
- /**
75
- * Fetch from the Extension HTTP API with retry and exponential backoff.
76
- * The Extension starts during INIT phase 1 (Extension init) and the wrapper
77
- * runs during INIT phase 2 (Runtime init), so it is usually ready — but
78
- * a retry loop handles the timing edge case.
79
- */
80
- async function fetchWithRetry(path) {
81
- let delay = INITIAL_DELAY_MS;
82
- let lastFailure;
83
-
84
- for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
85
- try {
86
- const response = await fetch(`${EXTENSION_URL}${path}`, {
87
- headers: {
88
- "X-Aws-Parameters-Secrets-Token": process.env.AWS_SESSION_TOKEN
89
- },
90
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
91
- });
92
- if (response.ok) {
93
- const body = await response.text();
94
- try {
95
- return JSON.parse(body);
96
- } catch {
97
- // The body carries the parameter's value or the secret string, and
98
- // V8's message quotes a window of it, so only its length is named.
99
- throw new ResolverFailure(
100
- `Extension returned a body that is not valid JSON (${body.length} characters)`,
101
- { retriable: true }
102
- );
103
- }
104
- }
105
- // 4xx errors (e.g. secret not found) — don't retry; 5xx — retriable
106
- if (response.status >= 400 && response.status < 500) {
107
- throw new ResolverFailure(
108
- `${await describeRefusal(response)}. ${REFUSAL_CURE}`
109
- );
110
- }
111
- throw new ResolverFailure(await describeRefusal(response), {
112
- retriable: true
113
- });
114
- } catch (err) {
115
- if (err instanceof ResolverFailure && !err.retriable) throw err;
116
- lastFailure = describeFailure(err);
117
- }
118
-
119
- // Retry with backoff (both 5xx and network errors)
120
- if (attempt < MAX_RETRIES - 1) {
121
- await new Promise((r) => setTimeout(r, delay));
122
- delay *= 2;
123
- }
124
- }
125
-
126
- throw new ResolverFailure(
127
- `Failed to reach Extension after ${MAX_RETRIES} attempts: ${lastFailure}`
128
- );
129
- }
96
+ const TAG = "[fjall-resolver]";
130
97
 
131
98
  /**
132
99
  * A value as the wrapper's `printf '%b'` reads it back: each backslash
@@ -139,9 +106,9 @@ function encodeValue(value) {
139
106
  return value.replace(/\\/g, "\\\\").replace(/\n/g, "\\n");
140
107
  }
141
108
 
142
- /** What a failure to resolve one secret says: this script's words, or the error's identity. */
109
+ /** What a failure to resolve one secret says: the client's words, or the error's identity. */
143
110
  function describeFailure(err) {
144
- return err instanceof ResolverFailure
111
+ return err instanceof AwsReadFailure
145
112
  ? err.message
146
113
  : describeErrorIdentity(err);
147
114
  }
@@ -149,137 +116,395 @@ function describeFailure(err) {
149
116
  // POSIX env var names: letters, digits, underscores; must not start with a digit
150
117
  const VALID_ENV_NAME = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
151
118
 
119
+ /** SSM_SECRETS_PATH in its shape: `/` and then letters, digits or `_./-`. */
120
+ const SECRETS_PATH_SHAPE = /^\/[A-Za-z0-9_./-]+$/;
121
+
152
122
  /**
153
- * Stops the resolver when `name` cannot name an environment variable,
154
- * naming it by `where` alone: the name is the operator's text, and an entry
155
- * written by mistake can hold a value (`DB_PASSWORD=<value>`).
123
+ * A Secrets Manager ARN in its shape: the partition `aws`, alone or followed
124
+ * by hyphenated lowercase words, a Region of hyphenated lowercase words
125
+ * ending in a number, a twelve-digit account, and a name of letters, digits
126
+ * or `/_+=.@-`.
156
127
  */
157
- function assertValidEnvName(name, where) {
158
- if (!VALID_ENV_NAME.test(name)) {
159
- process.stderr.write(
160
- `[fjall-resolver] ${where} is not a valid environment variable name, and is not repeated here. ` +
161
- `Names must match [a-zA-Z_][a-zA-Z0-9_]* (no dots, hyphens or '=').\n`
162
- );
163
- process.exit(1);
128
+ const SECRET_ARN_SHAPE =
129
+ /^arn:aws(?:-[a-z]+)*:secretsmanager:[a-z]+(?:-[a-z]+)*-[0-9]+:[0-9]{12}:secret:[A-Za-z0-9/_+=.@-]+$/;
130
+
131
+ /** A *_SECRET_FIELD value in its shape: one to 128 letters, digits or `_.-`. */
132
+ const FIELD_SHAPE = /^[A-Za-z0-9_.-]{1,128}$/;
133
+
134
+ const SECRET_ARN_SUFFIX = "_SECRET_ARN";
135
+
136
+ /** A name refused before any read, by `where` alone, with the shape it must have. */
137
+ function badNameLine(where) {
138
+ return (
139
+ `${TAG} ${where} is not a valid environment variable name, and is not repeated here. ` +
140
+ `Names must match [a-zA-Z_][a-zA-Z0-9_]* (no dots, hyphens or '=').`
141
+ );
142
+ }
143
+
144
+ /**
145
+ * The secrets the configuration names, in its order: each SSM_SECRET_NAMES
146
+ * entry, then each *_SECRET_ARN variable in the environment's order. A name
147
+ * that cannot name an environment variable stops the resolver before any
148
+ * read, named by where it is alone: the name is the operator's text, and an
149
+ * entry written by mistake can hold a value (`DB_PASSWORD=<value>`).
150
+ */
151
+ function configuredUnits(env) {
152
+ const units = [];
153
+ const basePath = env.SSM_SECRETS_PATH;
154
+ const secretNames = env.SSM_SECRET_NAMES;
155
+ if (basePath && secretNames) {
156
+ // Positions count the empty entries a doubled comma leaves, so each names
157
+ // the entry an operator reading SSM_SECRET_NAMES counts to.
158
+ for (const [index, name] of secretNames.split(",").entries()) {
159
+ if (name === "") continue;
160
+ if (!VALID_ENV_NAME.test(name)) {
161
+ return {
162
+ refusal: badNameLine(`Entry ${index + 1} of SSM_SECRET_NAMES`)
163
+ };
164
+ }
165
+ units.push({ kind: "ssm", name, path: `${basePath}/${name}` });
166
+ }
167
+ }
168
+ for (const [key, arn] of Object.entries(env)) {
169
+ if (!key.endsWith(SECRET_ARN_SUFFIX) || !arn) continue;
170
+ const prefix = key.slice(0, -SECRET_ARN_SUFFIX.length);
171
+ if (!VALID_ENV_NAME.test(prefix)) {
172
+ return {
173
+ refusal: badNameLine(
174
+ "The prefix of an environment variable ending _SECRET_ARN"
175
+ )
176
+ };
177
+ }
178
+ units.push({
179
+ kind: "sm",
180
+ prefix,
181
+ arn,
182
+ field: env[`${prefix}_SECRET_FIELD`]
183
+ });
184
+ }
185
+ return { units };
186
+ }
187
+
188
+ /** `items` in runs of at most `size`, in order. */
189
+ function batched(items, size) {
190
+ const batches = [];
191
+ for (let at = 0; at < items.length; at += size) {
192
+ batches.push(items.slice(at, at + size));
164
193
  }
194
+ return batches;
165
195
  }
166
196
 
167
197
  /**
168
- * Resolve SSM Parameter Store secrets.
169
- * Reads SSM_SECRETS_PATH and SSM_SECRET_NAMES, fetches each SecureString parameter.
198
+ * Each of `reads` started at once, up to `limit` at a time, in order, and
199
+ * how each settled. It never rejects: a read's rejection is its outcome.
170
200
  */
171
- async function resolveSsmSecrets() {
172
- const basePath = process.env.SSM_SECRETS_PATH;
173
- const secretNames = process.env.SSM_SECRET_NAMES;
201
+ async function settledInTurn(reads, limit) {
202
+ const settled = new Array(reads.length);
203
+ let next = 0;
204
+ const worker = async () => {
205
+ while (next < reads.length) {
206
+ const index = next;
207
+ next += 1;
208
+ try {
209
+ settled[index] = { ok: true, value: await reads[index]() };
210
+ } catch (error) {
211
+ settled[index] = { ok: false, error };
212
+ }
213
+ }
214
+ };
215
+ await Promise.all(
216
+ Array.from({ length: Math.min(limit, reads.length) }, worker)
217
+ );
218
+ return settled;
219
+ }
174
220
 
175
- if (!basePath || !secretNames) return [];
221
+ const isRecord = (value) =>
222
+ typeof value === "object" && value !== null && !Array.isArray(value);
176
223
 
177
- const lines = [];
224
+ /** A field's own value, never one its prototype gives. */
225
+ const own = (record, key) =>
226
+ Object.hasOwn(record, key) ? record[key] : undefined;
178
227
 
179
- // Positions count the empty entries a doubled comma leaves, so each names
180
- // the entry an operator reading SSM_SECRET_NAMES counts to.
181
- for (const [index, name] of secretNames.split(",").entries()) {
182
- if (name === "") continue;
183
- assertValidEnvName(name, `Entry ${index + 1} of SSM_SECRET_NAMES`);
184
- const paramPath = `${basePath}/${name}`;
185
- const encodedPath = encodeURIComponent(paramPath);
228
+ /** A read that gave no value and stops nothing. As through 39.0.6; 40.0.0 stops the function instead. */
229
+ const SKIPPED = Object.freeze({ ok: true, skipped: true });
186
230
 
187
- try {
188
- const data = await fetchWithRetry(
189
- `/systemsmanager/parameters/get?name=${encodedPath}&withDecryption=true`
190
- );
191
- const value = data?.Parameter?.Value;
192
- // As through 39.0.6; 40.0.0 stops the function instead.
193
- if (value === undefined || value === null) continue;
194
- lines.push(`${name}=${encodeValue(value)}`);
195
- } catch (err) {
196
- process.stderr.write(
197
- `[fjall-resolver] Failed to resolve SSM parameter ${paramPath}: ${describeFailure(err)}\n`
198
- );
199
- process.exit(1);
231
+ const NOT_FOUND =
232
+ "Systems Manager answered that it does not exist. Set it with fjall secrets set, or take it out of the function's secrets.";
233
+ const NO_PARAMETER_VALUE =
234
+ "Systems Manager answered without the parameter's value";
235
+ const NOT_GET_PARAMETERS =
236
+ "Systems Manager answered a body that is not a GetParameters answer";
237
+
238
+ /**
239
+ * Each path of one GetParameters call, and what its answer held for it: the
240
+ * value, why there is none, or that it is skipped. A name the answer lists as
241
+ * invalid is one that does not exist, which stops the start, as the extension's
242
+ * 400 for it did. A name in neither list, or listed without a value, is
243
+ * skipped. Its answers come in alphabetical order, so each is matched by its
244
+ * Name.
245
+ */
246
+ function parameterOutcomes(paths, read) {
247
+ const every = (outcome) => paths.map((path) => [path, outcome]);
248
+ if (!read.ok)
249
+ return every({ ok: false, reason: describeFailure(read.error) });
250
+ const answer = read.value;
251
+ if (!isRecord(answer))
252
+ return every({ ok: false, reason: NOT_GET_PARAMETERS });
253
+ const parameters = own(answer, "Parameters");
254
+ const invalid = Object.hasOwn(answer, "InvalidParameters")
255
+ ? answer.InvalidParameters
256
+ : [];
257
+ if (!Array.isArray(parameters) || !Array.isArray(invalid)) {
258
+ return every({ ok: false, reason: NOT_GET_PARAMETERS });
259
+ }
260
+ return paths.map((path) => {
261
+ if (invalid.includes(path)) {
262
+ return [path, { ok: false, reason: NOT_FOUND }];
200
263
  }
264
+ const found = parameters.find(
265
+ (entry) => isRecord(entry) && own(entry, "Name") === path
266
+ );
267
+ if (found === undefined) return [path, SKIPPED];
268
+ const value = own(found, "Value");
269
+ if (value === undefined || value === null) return [path, SKIPPED];
270
+ return typeof value === "string"
271
+ ? [path, { ok: true, value }]
272
+ : [path, { ok: false, reason: NO_PARAMETER_VALUE }];
273
+ });
274
+ }
275
+
276
+ /**
277
+ * What one Secrets Manager unit's secret gave it: the value, why there is
278
+ * none, or that it is skipped, as a secret with no SecretString and a field
279
+ * holding null are. A reason that names the field is a function of the field
280
+ * as a line names it, so the field is masked with the rest of the line.
281
+ */
282
+ function secretOutcome(unit, read) {
283
+ if (!read.ok) return { ok: false, reason: describeFailure(read.error) };
284
+ const secretString = read.value?.SecretString;
285
+ if (secretString === undefined || secretString === null) return SKIPPED;
286
+ const { field } = unit;
287
+ if (!(field && secretString)) {
288
+ return { ok: true, value: String(secretString) };
289
+ }
290
+ let parsed;
291
+ try {
292
+ parsed = JSON.parse(secretString);
293
+ } catch {
294
+ return {
295
+ ok: false,
296
+ reason: (named) =>
297
+ `Secret is not valid JSON but field ${named} was requested. Store the secret as a JSON object.`
298
+ };
299
+ }
300
+ if (!isRecord(parsed)) {
301
+ return {
302
+ ok: false,
303
+ reason: (named) =>
304
+ `Secret is not a JSON object but field ${named} was requested. Store the secret as a JSON object.`
305
+ };
201
306
  }
307
+ const value = own(parsed, field);
308
+ if (value === undefined) {
309
+ const present = Object.keys(parsed).length;
310
+ return {
311
+ ok: false,
312
+ reason: (named) =>
313
+ `Field ${named} not found in secret (${present} fields present).`
314
+ };
315
+ }
316
+ if (value === null) return SKIPPED;
317
+ if (typeof value === "object") {
318
+ return {
319
+ ok: false,
320
+ reason: (named) =>
321
+ `Field ${named} holds an object or a list in the secret. Store a string, a number or a boolean there.`
322
+ };
323
+ }
324
+ return { ok: true, value: String(value) };
325
+ }
202
326
 
203
- return lines;
327
+ /**
328
+ * Every unit's outcome, in configuration order. The SSM names are sent once
329
+ * each, in batches; each secret once, whatever number of prefixes name it.
330
+ */
331
+ async function readUnits(units, env, deadline) {
332
+ const region = env.AWS_REGION;
333
+ const ssmPaths = [
334
+ ...new Set(units.filter((unit) => unit.kind === "ssm").map((u) => u.path))
335
+ ];
336
+ const arns = [
337
+ ...new Set(units.filter((unit) => unit.kind === "sm").map((u) => u.arn))
338
+ ];
339
+ const batches = batched(ssmPaths, GET_PARAMETERS_BATCH_SIZE);
340
+ const reads = [
341
+ ...batches.map(
342
+ (names) => () =>
343
+ callAws({
344
+ service: "ssm",
345
+ operation: "GetParameters",
346
+ payload: { Names: names, WithDecryption: true },
347
+ region,
348
+ env,
349
+ deadline
350
+ })
351
+ ),
352
+ ...arns.map(
353
+ (arn) => () =>
354
+ callAws({
355
+ service: "secretsmanager",
356
+ operation: "GetSecretValue",
357
+ payload: { SecretId: arn },
358
+ region,
359
+ env,
360
+ deadline
361
+ })
362
+ )
363
+ ];
364
+ const settled = await settledInTurn(reads, READS_IN_FLIGHT);
365
+ const parameters = new Map(
366
+ batches.flatMap((names, index) => parameterOutcomes(names, settled[index]))
367
+ );
368
+ const secrets = new Map(
369
+ arns.map((arn, index) => [arn, settled[batches.length + index]])
370
+ );
371
+ return units.map((unit) => ({
372
+ unit,
373
+ outcome:
374
+ unit.kind === "ssm"
375
+ ? parameters.get(unit.path)
376
+ : secretOutcome(unit, secrets.get(unit.arn))
377
+ }));
204
378
  }
205
379
 
206
380
  /**
207
- * Resolve Secrets Manager secrets.
208
- * Scans for *_SECRET_ARN env vars, fetches each secret from SM,
209
- * optionally extracts a JSON field, and writes it as NAME=VALUE under the
210
- * prefix.
381
+ * One line for each unit that could not be read, in configuration order,
382
+ * each string of the configuration it names masked whole by
383
+ * `maskSensitiveOutput`, or described when it is out of its shape. An SSM
384
+ * name listed more than once is named once.
211
385
  */
212
- async function resolveSecretsManagerSecrets() {
386
+ function failureLines(failed, env, maskSensitiveOutput) {
387
+ const masked = (text) => maskSensitiveOutput(text);
388
+ const ssmPathInShape = SECRETS_PATH_SHAPE.test(env.SSM_SECRETS_PATH ?? "");
213
389
  const lines = [];
214
-
215
- for (const [key, arn] of Object.entries(process.env)) {
216
- if (!key.endsWith("_SECRET_ARN") || !arn) continue;
217
-
218
- const prefix = key.slice(0, -"_SECRET_ARN".length);
219
- assertValidEnvName(
220
- prefix,
221
- "The prefix of an environment variable ending _SECRET_ARN"
390
+ const named = new Set();
391
+ for (const { unit, outcome } of failed) {
392
+ if (unit.kind === "ssm") {
393
+ if (named.has(unit.path)) continue;
394
+ named.add(unit.path);
395
+ const subject = ssmPathInShape
396
+ ? masked(unit.path)
397
+ : `${masked(unit.name)} (under the value of SSM_SECRETS_PATH, not repeated here)`;
398
+ lines.push(
399
+ `${TAG} Failed to resolve SSM parameter ${subject}: ${outcome.reason}`
400
+ );
401
+ continue;
402
+ }
403
+ const prefix = masked(unit.prefix);
404
+ const arn = SECRET_ARN_SHAPE.test(unit.arn)
405
+ ? masked(unit.arn)
406
+ : `the value of ${prefix}${SECRET_ARN_SUFFIX}, not repeated here`;
407
+ const reason =
408
+ typeof outcome.reason === "function"
409
+ ? outcome.reason(
410
+ FIELD_SHAPE.test(unit.field ?? "")
411
+ ? `'${masked(unit.field)}'`
412
+ : `(the value of ${prefix}_SECRET_FIELD, not repeated here)`
413
+ )
414
+ : outcome.reason;
415
+ lines.push(
416
+ `${TAG} Failed to resolve SM secret ${prefix} (${arn}): ${reason}`
222
417
  );
223
- const fieldKey = `${prefix}_SECRET_FIELD`;
224
- const field = process.env[fieldKey];
225
-
226
- const encodedArn = encodeURIComponent(arn);
418
+ }
419
+ return lines;
420
+ }
227
421
 
228
- try {
229
- const data = await fetchWithRetry(
230
- `/secretsmanager/get?secretId=${encodedArn}`
231
- );
232
- const secretString = data?.SecretString;
233
- // As through 39.0.6; 40.0.0 stops the function instead.
234
- if (secretString === undefined || secretString === null) continue;
422
+ /**
423
+ * Writes `text` to stderr and ends the process with status 1 once it is
424
+ * written, whatever the event loop still holds.
425
+ */
426
+ function failWith(text) {
427
+ process.stderr.write(text, () => process.exit(1));
428
+ }
235
429
 
236
- let value;
237
- if (field && secretString) {
238
- let parsed;
239
- try {
240
- parsed = JSON.parse(secretString);
241
- } catch {
242
- throw new ResolverFailure(
243
- `Secret is not valid JSON but field '${field}' was requested. Store the secret as a JSON object.`
244
- );
245
- }
246
- value = parsed[field];
247
- if (value === undefined) {
248
- throw new ResolverFailure(
249
- `Field '${field}' not found in secret (${Object.keys(parsed).length} fields present).`
250
- );
251
- }
252
- // As through 39.0.6; 40.0.0 stops the function instead.
253
- if (value === null) continue;
254
- } else {
255
- value = secretString;
256
- }
430
+ /**
431
+ * The resolver's stdout failing, as when its reader has gone: one line, and
432
+ * the process ends with status 1. Its error and the write's callback can both
433
+ * report the same failure, so the line is written once.
434
+ */
435
+ let outputFailed = false;
436
+ function outputNotWritten(error) {
437
+ if (outputFailed) return;
438
+ outputFailed = true;
439
+ failWith(
440
+ `${TAG} Fatal error: the resolver's output could not be written: ${describeErrorIdentity(error)}\n`
441
+ );
442
+ }
443
+ process.stdout.on("error", outputNotWritten);
257
444
 
258
- lines.push(`${prefix}=${encodeValue(String(value))}`);
259
- } catch (err) {
260
- process.stderr.write(
261
- `[fjall-resolver] Failed to resolve SM secret ${prefix} (${arn}): ${describeFailure(err)}\n`
262
- );
263
- process.exit(1);
445
+ function writeValues(lines) {
446
+ process.stdout.write(`${lines.join("\n")}\n`, (error) => {
447
+ if (error === null || error === undefined) {
448
+ process.exit(0);
449
+ return;
264
450
  }
265
- }
451
+ outputNotWritten(error);
452
+ });
453
+ }
266
454
 
267
- return lines;
455
+ /** Ends a start whose reads outlived their deadline, as a read ignoring its abort would. */
456
+ function backstopFired() {
457
+ failWith(`${TAG} Fatal error: the reads outlived the resolver's deadline\n`);
268
458
  }
269
459
 
270
460
  async function main() {
271
- const ssmLines = await resolveSsmSecrets();
272
- const smLines = await resolveSecretsManagerSecrets();
273
- const allLines = [...ssmLines, ...smLines];
274
-
275
- if (allLines.length > 0) {
276
- process.stdout.write(allLines.join("\n") + "\n");
461
+ const env = process.env;
462
+ const configured = configuredUnits(env);
463
+ if ("refusal" in configured) {
464
+ failWith(`${configured.refusal}\n`);
465
+ return;
466
+ }
467
+ const { units } = configured;
468
+ if (units.length === 0) {
469
+ process.exit(0);
470
+ return;
471
+ }
472
+ if (!env.AWS_REGION) {
473
+ failWith(
474
+ `${TAG} The function's environment names no AWS_REGION, so no service can be read\n`
475
+ );
476
+ return;
477
+ }
478
+ const deadline = new AbortController();
479
+ const deadlineTimer = setTimeout(() => deadline.abort(), DEADLINE_MS);
480
+ const backstop = setTimeout(backstopFired, BACKSTOP_MS);
481
+ let outcomes;
482
+ try {
483
+ outcomes = await readUnits(units, env, deadline.signal);
484
+ } finally {
485
+ clearTimeout(deadlineTimer);
486
+ clearTimeout(backstop);
487
+ }
488
+ const failed = outcomes.filter(({ outcome }) => !outcome.ok);
489
+ if (failed.length > 0) {
490
+ const { maskSensitiveOutput } = await import("./mask.mjs");
491
+ failWith(`${failureLines(failed, env, maskSensitiveOutput).join("\n")}\n`);
492
+ return;
277
493
  }
494
+ const lines = outcomes.flatMap(({ unit, outcome }) =>
495
+ outcome.skipped
496
+ ? []
497
+ : [
498
+ `${unit.kind === "ssm" ? unit.name : unit.prefix}=${encodeValue(outcome.value)}`
499
+ ]
500
+ );
501
+ if (lines.length === 0) {
502
+ process.exit(0);
503
+ return;
504
+ }
505
+ writeValues(lines);
278
506
  }
279
507
 
280
508
  main().catch((err) => {
281
- process.stderr.write(
282
- `[fjall-resolver] Fatal error: ${describeFailure(err)}\n`
283
- );
284
- process.exit(1);
509
+ failWith(`${TAG} Fatal error: ${describeFailure(err)}\n`);
285
510
  });