firebase-tools 15.30.1 → 15.30.3-main.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.
@@ -94,7 +94,7 @@ exports.command = new command_1.Command("ext:migrate")
94
94
  throw new error_1.FirebaseError(`Failed to deploy. Please fix and retry with firebase deploy --only functions:${kitInstanceId}. After success you may remove the old extension with firebase ext:uninstall ${plan.instanceId} --project ${projectId} --immediate`, { original: err instanceof Error ? err : undefined, exit: 1 });
95
95
  }
96
96
  const shouldUninstall = await (0, prompt_1.confirm)({
97
- message: `Functions kit ${kitInstanceId} successfully deployed. After checking function logs to verify that your backend is performing correctly, you should uninstall extension instance ${plan.instanceId}. Uninstall it now?`,
97
+ message: `Functions kit ${kitInstanceId} successfully deployed. After checking function logs to verify that your backend is performing correctly, you should uninstall extension instance ${plan.instanceId}. It can take a few minutes for Eventarc to fully provision and new kits to react to events. Uninstall it now?`,
98
98
  default: false,
99
99
  nonInteractive: options.nonInteractive,
100
100
  force: options.force,
@@ -13,8 +13,10 @@ exports.isBlockingTriggered = isBlockingTriggered;
13
13
  exports.resolveBackend = resolveBackend;
14
14
  exports.envWithTypes = envWithTypes;
15
15
  exports.toBackend = toBackend;
16
- exports.applyPrefix = applyPrefix;
17
- exports.applyEnvSecretBindings = applyEnvSecretBindings;
16
+ exports.applyKitSecretRefPrefix = applyKitSecretRefPrefix;
17
+ exports.applyEndpointPrefix = applyEndpointPrefix;
18
+ exports.applyEnvSecretBindingsToParams = applyEnvSecretBindingsToParams;
19
+ exports.applyEnvSecretBindingsToBuild = applyEnvSecretBindingsToBuild;
18
20
  exports.parseSecretRef = parseSecretRef;
19
21
  const backend = require("./backend");
20
22
  const proto = require("../../gcp/proto");
@@ -23,9 +25,11 @@ const logger_1 = require("../../logger");
23
25
  const error_1 = require("../../error");
24
26
  const functional_1 = require("../../functional");
25
27
  const cel_1 = require("./cel");
28
+ const projects = require("../../management/projects");
29
+ const projectConfig_1 = require("../../functions/projectConfig");
26
30
  exports.REGION_TBD = "REGION_TBD";
27
31
  exports.SECRET_REF_PREFIX = "FIREBASE_SECRET_REF_";
28
- const GCP_PROJECT_ID_PATTERN = "([a-z][-a-z0-9]{4,28}[a-z0-9])";
32
+ const GCP_PROJECT_ID_OR_NUM_PATTERN = "((?:\\d+)|(?:[a-z][-a-z0-9]{4,28}[a-z0-9]))";
29
33
  exports.GCP_SECRET_ID_PATTERN = "([a-zA-Z0-9-_]+)";
30
34
  exports.SECRET_REF_SHORT_RE = new RegExp("^" +
31
35
  exports.GCP_SECRET_ID_PATTERN +
@@ -34,7 +38,7 @@ exports.SECRET_REF_SHORT_RE = new RegExp("^" +
34
38
  ")?$");
35
39
  exports.SECRET_REF_LONG_RE = new RegExp("^" +
36
40
  "projects/" +
37
- GCP_PROJECT_ID_PATTERN +
41
+ GCP_PROJECT_ID_OR_NUM_PATTERN +
38
42
  "/secrets/" +
39
43
  exports.GCP_SECRET_ID_PATTERN +
40
44
  "(?:(?:/versions/|:|#|@)" +
@@ -88,7 +92,6 @@ async function resolveBackend(opts) {
88
92
  userEnvs: envWithTypes(opts.build.params, opts.userEnvs),
89
93
  codebase: opts.codebase,
90
94
  nonInteractive: opts.nonInteractive,
91
- force: opts.force,
92
95
  isEmulator: opts.isEmulator,
93
96
  });
94
97
  return { backend: toBackend(opts.build, paramValues), envs: paramValues, secretRefs: secretRefs };
@@ -385,7 +388,18 @@ function discoverTrigger(endpoint, region, r) {
385
388
  }
386
389
  (0, functional_1.assertExhaustive)(endpoint);
387
390
  }
388
- function applyPrefix(build, prefix) {
391
+ function applyKitSecretRefPrefix(build, instanceId) {
392
+ const kitPrefix = (0, projectConfig_1.addKitPrefix)(instanceId);
393
+ for (const secretParam of build.params.filter((p) => params.isSecretParam(p))) {
394
+ secretParam.resourceId = `${kitPrefix}-${secretParam.name}`;
395
+ }
396
+ for (const endpoint of Object.values(build.endpoints)) {
397
+ for (const envVar of endpoint.secretEnvironmentVariables ?? []) {
398
+ envVar.secret = `${kitPrefix}-${envVar.secret}`;
399
+ }
400
+ }
401
+ }
402
+ function applyEndpointPrefix(build, prefix) {
389
403
  if (!prefix) {
390
404
  return;
391
405
  }
@@ -425,7 +439,19 @@ function applyPrefix(build, prefix) {
425
439
  }
426
440
  }
427
441
  }
428
- function applyEnvSecretBindings(build, envSecrets) {
442
+ function applyEnvSecretBindingsToParams(params, envSecrets) {
443
+ for (const key of Object.keys(envSecrets)) {
444
+ const { secretId, version } = envSecrets[key];
445
+ for (const param of params) {
446
+ if (param.type === "secret" && param.name.toUpperCase() === key.toUpperCase()) {
447
+ param.resourceId = secretId;
448
+ param.version = version;
449
+ param.inLocalEnvironment = true;
450
+ }
451
+ }
452
+ }
453
+ }
454
+ async function applyEnvSecretBindingsToBuild(build, envSecrets) {
429
455
  if (envSecrets.empty) {
430
456
  return;
431
457
  }
@@ -433,15 +459,20 @@ function applyEnvSecretBindings(build, envSecrets) {
433
459
  for (const endpointName of Object.keys(build.endpoints)) {
434
460
  logger_1.logger.debug(`${endpointName} declared secrets: ${JSON.stringify(build.endpoints[endpointName].secretEnvironmentVariables)}`);
435
461
  }
462
+ applyEnvSecretBindingsToParams(build.params, envSecrets);
463
+ const projectNumberToId = new Map();
436
464
  for (const key of Object.keys(envSecrets)) {
437
465
  const secretRef = envSecrets[key];
438
- const { projectId, secretId, version } = secretRef;
439
- for (const param of build.params) {
440
- if (param.type === "secret" && param.name.toUpperCase() === key) {
441
- param.resourceId = secretId;
442
- param.version = version;
443
- param.inLocalEnvironment = true;
466
+ let { projectId } = secretRef;
467
+ const { secretId, version } = secretRef;
468
+ if (projectId && /^\d+$/.test(projectId)) {
469
+ let resolvedId = projectNumberToId.get(projectId);
470
+ if (!resolvedId) {
471
+ const project = await projects.getProject(projectId);
472
+ resolvedId = project.projectId;
473
+ projectNumberToId.set(projectId, resolvedId);
444
474
  }
475
+ projectId = resolvedId;
445
476
  }
446
477
  for (const endpointName of Object.keys(build.endpoints)) {
447
478
  const endpoint = build.endpoints[endpointName];
@@ -9,19 +9,20 @@ exports.isTextInput = isTextInput;
9
9
  exports.isSelectInput = isSelectInput;
10
10
  exports.isResourceInput = isResourceInput;
11
11
  exports.isMultiSelectInput = isMultiSelectInput;
12
+ exports.isSecretParam = isSecretParam;
12
13
  exports.resolveParams = resolveParams;
13
14
  const clc = require("colorette");
14
15
  const logger_1 = require("../../logger");
15
16
  const error_1 = require("../../error");
16
17
  const prompt_1 = require("../../prompt");
17
18
  const secrets_1 = require("../../functions/secrets");
18
- const build = require("./build");
19
19
  const functional_1 = require("../../functional");
20
20
  const secretManager = require("../../gcp/secretManager");
21
21
  const storage_1 = require("../../gcp/storage");
22
22
  const cel_1 = require("./cel");
23
23
  const secretManager_1 = require("../../gcp/secretManager");
24
24
  const experiments = require("../../experiments");
25
+ const marked_1 = require("marked");
25
26
  function dependenciesCEL(expr) {
26
27
  const deps = [];
27
28
  const paramCapture = /{{ params\.(\w+) }}/g;
@@ -82,6 +83,9 @@ function isResourceInput(input) {
82
83
  function isMultiSelectInput(input) {
83
84
  return {}.hasOwnProperty.call(input, "multiSelect");
84
85
  }
86
+ function isSecretParam(param) {
87
+ return param.type === "secret";
88
+ }
85
89
  class ParamValue {
86
90
  constructor(rawValue, internal, types) {
87
91
  this.rawValue = rawValue;
@@ -164,7 +168,7 @@ function canSatisfyParam(param, value) {
164
168
  (0, functional_1.assertExhaustive)(param);
165
169
  }
166
170
  async function resolveParams(opts) {
167
- const { params, firebaseConfig, userEnvs, codebase, nonInteractive = false, force = false, isEmulator = false, } = opts;
171
+ const { params, firebaseConfig, userEnvs, codebase, nonInteractive = false, isEmulator = false, } = opts;
168
172
  const paramValues = populateDefaultParams(firebaseConfig);
169
173
  const secretRefs = {};
170
174
  const [resolved, outstanding] = (0, functional_1.partition)(params, (param) => {
@@ -176,7 +180,7 @@ async function resolveParams(opts) {
176
180
  const [needSecret, needPrompt] = (0, functional_1.partition)(outstanding, (param) => param.type === "secret");
177
181
  if (!isEmulator) {
178
182
  for (const param of needSecret) {
179
- secretRefs[param.name] = await ensureSecret(param, firebaseConfig.projectId, nonInteractive, force);
183
+ secretRefs[param.name] = await ensureSecret(param, firebaseConfig.projectId, nonInteractive);
180
184
  }
181
185
  }
182
186
  if (nonInteractive && needPrompt.length > 0) {
@@ -229,7 +233,7 @@ function populateDefaultParams(config) {
229
233
  }
230
234
  return defaultParams;
231
235
  }
232
- async function ensureSecret(secretParam, projectId, nonInteractive, force) {
236
+ async function ensureSecret(secretParam, projectId, nonInteractive) {
233
237
  const resourceId = secretParam.resourceId || secretParam.name;
234
238
  const version = secretParam.version || "latest";
235
239
  let secretAlreadyExisted = false;
@@ -240,26 +244,11 @@ async function ensureSecret(secretParam, projectId, nonInteractive, force) {
240
244
  "Set this secret before deploying:\n" +
241
245
  `\tfirebase functions:secrets:set ${resourceId}${secretParam.format === "json" ? " --format=json --data-file <file.json>" : ""}`);
242
246
  }
243
- if (experiments.isEnabled("secretEnvParams") && typeof secretParam.resourceId === "undefined") {
244
- if (force) {
245
- logger_1.logger.info(`--force: Using default resource ID for secret ${secretParam.name}`);
246
- secretParam.resourceId = secretParam.name;
247
- }
248
- else {
249
- secretParam.resourceId = await (0, prompt_1.input)({
250
- default: secretParam.name,
251
- message: `What resource ID do you want to use for the backing Secret resource for secret param ${secretParam.name}?`,
252
- validate: (id) => {
253
- if (new RegExp(`^${build.GCP_SECRET_ID_PATTERN}$`).test(id)) {
254
- return true;
255
- }
256
- return "GCP Secret identifiers must contain only letters, numbers, underscores, and hyphens.";
257
- },
258
- });
259
- }
260
- return ensureSecret(secretParam, projectId, nonInteractive, force);
261
- }
262
- const promptMessage = `The value for this secret (${secretParam.name}) will be stored in Cloud Secret Manager (https://cloud.google.com/secret-manager/pricing) as ${resourceId}. Enter ${secretParam.format === "json" ? "a JSON value" : "a value"} for ${secretParam.label || secretParam.name}:`;
247
+ const label = secretParam.label || secretParam.name;
248
+ const notice = `The value for this secret will be stored in Cloud Secret Manager (https://cloud.google.com/secret-manager/pricing) as ${resourceId}.`;
249
+ const desc = secretParam.description ? `${secretParam.description} ${notice}` : notice;
250
+ logger_1.logger.info(`\n${clc.bold(label)}: ${(await (0, marked_1.marked)(desc)).trim()}`);
251
+ const promptMessage = `Enter ${secretParam.format === "json" ? "a JSON value" : "a value"} for ${label}:`;
263
252
  const secretValue = await (0, prompt_1.password)({
264
253
  message: promptMessage,
265
254
  });
@@ -280,7 +269,8 @@ async function ensureSecret(secretParam, projectId, nonInteractive, force) {
280
269
  secretAlreadyExisted = true;
281
270
  }
282
271
  const secretRefString = typeof version === "undefined" ? resourceId : `${resourceId}:${version}`;
283
- if (experiments.isEnabled("secretEnvParams")) {
272
+ if (experiments.isEnabled("secretEnvParams") &&
273
+ experiments.isEnabled("writeDefaultSecretBindings")) {
284
274
  if (!secretParam.inLocalEnvironment && secretAlreadyExisted) {
285
275
  logger_1.logger.info(`Onetime (firebase-tools x.y.z+): storing a reference to existing secret ${secretParam.name}=${secretRefString} in .env files.`);
286
276
  }
@@ -288,6 +278,13 @@ async function ensureSecret(secretParam, projectId, nonInteractive, force) {
288
278
  return secretRefString;
289
279
  }
290
280
  async function promptParam(param, projectId, resolvedDefault) {
281
+ const label = param.label || param.name;
282
+ if (param.description) {
283
+ logger_1.logger.info(`\n${clc.bold(label)}: ${(await (0, marked_1.marked)(param.description)).trim()}`);
284
+ }
285
+ else {
286
+ logger_1.logger.info("");
287
+ }
291
288
  if (param.type === "string") {
292
289
  const provided = await promptStringParam(param, projectId, resolvedDefault);
293
290
  return new ParamValue(provided.toString(), false, { string: true });
@@ -314,33 +311,21 @@ async function promptList(param, projectId, resolvedDefault) {
314
311
  const defaultToText = { text: {} };
315
312
  param.input = defaultToText;
316
313
  }
317
- let prompt;
314
+ const label = param.label || param.name;
318
315
  if (isSelectInput(param.input)) {
319
316
  throw new error_1.FirebaseError("List params cannot have non-list selector inputs");
320
317
  }
321
318
  else if (isMultiSelectInput(param.input)) {
322
- prompt = `Select a value for ${param.label || param.name}:`;
323
- if (param.description) {
324
- prompt += ` \n(${param.description})`;
325
- }
326
- prompt += "\nSelect an option with the arrow keys, and use Enter to confirm your choice. ";
327
- return promptSelectMultiple(prompt, param.input, resolvedDefault, param.input.multiSelect.nonEmpty, (res) => res);
319
+ return promptSelectMultiple(`Select values for ${label}:`, param.input, resolvedDefault, param.input.multiSelect.nonEmpty, (res) => res);
328
320
  }
329
321
  else if (isTextInput(param.input)) {
330
- prompt = `Enter a list of strings (delimiter: ${param.delimiter ? param.delimiter : ","}) for ${param.label || param.name}:`;
331
- if (param.description) {
332
- prompt += ` \n(${param.description})`;
333
- }
334
- return promptText(prompt, param.input, resolvedDefault, param.input.text.nonEmpty, (res) => {
335
- return res.split(param.delimiter || ",");
322
+ const delimiter = param.delimiter ? param.delimiter : ",";
323
+ return promptText(`Enter a list of strings (delimiter: ${delimiter}) for ${label}:`, param.input, resolvedDefault, param.input.text.nonEmpty, (res) => {
324
+ return res.split(delimiter);
336
325
  });
337
326
  }
338
327
  else if (isResourceInput(param.input)) {
339
- prompt = `Select values for ${param.label || param.name}:`;
340
- if (param.description) {
341
- prompt += ` \n(${param.description})`;
342
- }
343
- return promptResourceStrings(prompt, param.input, projectId, false);
328
+ return promptResourceStrings(`Select values for ${label}:`, param.input, projectId, false);
344
329
  }
345
330
  else {
346
331
  (0, functional_1.assertExhaustive)(param.input);
@@ -352,24 +337,15 @@ async function promptBooleanParam(param, resolvedDefault) {
352
337
  param.input = defaultToText;
353
338
  }
354
339
  const isTruthyInput = (res) => ["true", "y", "yes", "1"].includes(res.toLowerCase());
355
- let prompt;
340
+ const label = param.label || param.name;
356
341
  if (isSelectInput(param.input)) {
357
- prompt = `Select a value for ${param.label || param.name}:`;
358
- if (param.description) {
359
- prompt += ` \n(${param.description})`;
360
- }
361
- prompt += "\nSelect an option with the arrow keys, and use Enter to confirm your choice. ";
362
- return promptSelect(prompt, param.input, resolvedDefault, isTruthyInput);
342
+ return promptSelect(`Select a value for ${label}:`, param.input, resolvedDefault, isTruthyInput);
363
343
  }
364
344
  else if (isMultiSelectInput(param.input)) {
365
345
  throw new error_1.FirebaseError("Non-list params cannot have multi selector inputs");
366
346
  }
367
347
  else if (isTextInput(param.input)) {
368
- prompt = `Enter a boolean value for ${param.label || param.name}:`;
369
- if (param.description) {
370
- prompt += ` \n(${param.description})`;
371
- }
372
- return promptText(prompt, param.input, resolvedDefault, false, isTruthyInput);
348
+ return promptText(`Enter a boolean value for ${label}:`, param.input, resolvedDefault, false, isTruthyInput);
373
349
  }
374
350
  else if (isResourceInput(param.input)) {
375
351
  throw new error_1.FirebaseError("Boolean params cannot have Cloud Resource selector inputs");
@@ -383,31 +359,18 @@ async function promptStringParam(param, projectId, resolvedDefault) {
383
359
  const defaultToText = { text: {} };
384
360
  param.input = defaultToText;
385
361
  }
386
- let prompt;
362
+ const label = param.label || param.name;
387
363
  if (isResourceInput(param.input)) {
388
- prompt = `Select a value for ${param.label || param.name}:`;
389
- if (param.description) {
390
- prompt += ` \n(${param.description})`;
391
- }
392
- return promptResourceString(prompt, param.input, projectId, resolvedDefault);
364
+ return promptResourceString(`Select a value for ${label}:`, param.input, projectId, resolvedDefault);
393
365
  }
394
366
  else if (isMultiSelectInput(param.input)) {
395
367
  throw new error_1.FirebaseError("Non-list params cannot have multi selector inputs");
396
368
  }
397
369
  else if (isSelectInput(param.input)) {
398
- prompt = `Select a value for ${param.label || param.name}:`;
399
- if (param.description) {
400
- prompt += ` \n(${param.description})`;
401
- }
402
- prompt += "\nSelect an option with the arrow keys, and use Enter to confirm your choice. ";
403
- return promptSelect(prompt, param.input, resolvedDefault, (res) => res);
370
+ return promptSelect(`Select a value for ${label}:`, param.input, resolvedDefault, (res) => res);
404
371
  }
405
372
  else if (isTextInput(param.input)) {
406
- prompt = `Enter a string value for ${param.label || param.name}:`;
407
- if (param.description) {
408
- prompt += ` \n(${param.description})`;
409
- }
410
- return promptText(prompt, param.input, resolvedDefault, param.input.text.nonEmpty, (res) => res);
373
+ return promptText(`Enter a string value for ${label}:`, param.input, resolvedDefault, param.input.text.nonEmpty, (res) => res);
411
374
  }
412
375
  else {
413
376
  (0, functional_1.assertExhaustive)(param.input);
@@ -418,14 +381,9 @@ async function promptIntParam(param, resolvedDefault) {
418
381
  const defaultToText = { text: {} };
419
382
  param.input = defaultToText;
420
383
  }
421
- let prompt;
384
+ const label = param.label || param.name;
422
385
  if (isSelectInput(param.input)) {
423
- prompt = `Select a value for ${param.label || param.name}:`;
424
- if (param.description) {
425
- prompt += ` \n(${param.description})`;
426
- }
427
- prompt += "\nSelect an option with the arrow keys, and use Enter to confirm your choice. ";
428
- return promptSelect(prompt, param.input, resolvedDefault, (res) => {
386
+ return promptSelect(`Select a value for ${label}:`, param.input, resolvedDefault, (res) => {
429
387
  if (isNaN(+res)) {
430
388
  return { message: `"${res}" could not be converted to a number.` };
431
389
  }
@@ -439,11 +397,7 @@ async function promptIntParam(param, resolvedDefault) {
439
397
  throw new error_1.FirebaseError("Non-list params cannot have multi selector inputs");
440
398
  }
441
399
  else if (isTextInput(param.input)) {
442
- prompt = `Enter an integer value for ${param.label || param.name}:`;
443
- if (param.description) {
444
- prompt += ` \n(${param.description})`;
445
- }
446
- return promptText(prompt, param.input, resolvedDefault, param.input.text.nonEmpty, (res) => {
400
+ return promptText(`Enter an integer value for ${label}:`, param.input, resolvedDefault, param.input.text.nonEmpty, (res) => {
447
401
  if (isNaN(+res)) {
448
402
  return { message: `"${res}" could not be converted to a number.` };
449
403
  }
@@ -533,6 +487,7 @@ async function promptSelect(prompt, input, resolvedDefault, converter) {
533
487
  const response = await (0, prompt_1.select)({
534
488
  default: resolvedDefault,
535
489
  message: prompt,
490
+ instructions: "(Use arrow keys to navigate, and Enter to confirm your choice)",
536
491
  choices: input.select.options.map((option) => {
537
492
  return {
538
493
  checked: false,
@@ -552,6 +507,7 @@ async function promptSelectMultiple(prompt, input, resolvedDefault, enforceNonEm
552
507
  const response = await (0, prompt_1.checkbox)({
553
508
  default: resolvedDefault,
554
509
  message: prompt,
510
+ instructions: "(Press Space to select, and Enter to confirm your choices)",
555
511
  choices: input.multiSelect.options.map((option) => {
556
512
  return {
557
513
  checked: false,
@@ -211,18 +211,18 @@ async function prepare(context, options, payload) {
211
211
  .filter((e) => e.codebase === codebase || e.codebase === undefined);
212
212
  await resolveDefaultRegionsForBuild(wantBuild, backend.of(...relevantEndpoints));
213
213
  const parsedSecretRefs = (0, functional_1.mapObject)(secretRefs, (unparsed) => build.parseSecretRef(unparsed));
214
- build.applyEnvSecretBindings(wantBuild, parsedSecretRefs);
214
+ await build.applyEnvSecretBindingsToBuild(wantBuild, parsedSecretRefs);
215
215
  const { backend: wantBackend, envs: resolvedEnvs, secretRefs: resolvedSecretRefs, } = await build.resolveBackend({
216
216
  build: wantBuild,
217
217
  firebaseConfig,
218
218
  userEnvs,
219
219
  codebase,
220
220
  nonInteractive: options.nonInteractive,
221
- force: options.force,
222
221
  isEmulator: false,
223
222
  });
224
223
  functionsEnv.writeResolvedParams(resolvedEnvs, userEnvs, userEnvOpt);
225
- if (experiments.isEnabled("secretEnvParams")) {
224
+ if (experiments.isEnabled("secretEnvParams") &&
225
+ experiments.isEnabled("writeDefaultSecretBindings")) {
226
226
  functionsEnv.writeResolvedSecretRefs(resolvedSecretRefs, secretRefs, userEnvOpt);
227
227
  }
228
228
  let hasEnvsFromParams = false;
@@ -537,7 +537,10 @@ async function loadCodebases(config, options, firebaseConfig, runtimeConfig, fil
537
537
  const prefix = (0, projectConfig_1.isKitConfig)(codebaseConfig)
538
538
  ? (0, projectConfig_1.addKitPrefix)(codebase)
539
539
  : codebaseConfig.prefix || "";
540
- build.applyPrefix(discoveredBuild, prefix);
540
+ build.applyEndpointPrefix(discoveredBuild, prefix);
541
+ if ((0, projectConfig_1.isKitConfig)(codebaseConfig)) {
542
+ build.applyKitSecretRefPrefix(discoveredBuild, codebase);
543
+ }
541
544
  wantBuilds[codebase] = discoveredBuild;
542
545
  }
543
546
  return wantBuilds;
@@ -13,6 +13,10 @@ const logger_1 = require("../../../../logger");
13
13
  const python_1 = require("../../../../functions/python");
14
14
  const error_1 = require("../../../../error");
15
15
  const functional_1 = require("../../../../functional");
16
+ const utils_1 = require("../../../../utils");
17
+ const FORCE_KILL_DELAY_MS = 10000;
18
+ const SHUTDOWN_TIMEOUT_MS = 15000;
19
+ const QUITQUITQUIT_TIMEOUT_MS = 5000;
16
20
  async function tryCreateDelegate(context) {
17
21
  const requirementsTextPath = path.join(context.sourceDir, "requirements.txt");
18
22
  if (!(await (0, util_1.promisify)(fs.exists)(requirementsTextPath))) {
@@ -120,31 +124,58 @@ class Delegate {
120
124
  };
121
125
  const args = [this.bin, `"${path.join(modulesDir, "private", "serving.py")}"`];
122
126
  logger_1.logger.debug(`Running admin server with args: ${JSON.stringify(args)} and env: ${JSON.stringify(envWithAdminPort)} in ${this.sourceDir}`);
123
- const childProcess = (0, python_1.runWithVirtualEnv)(args, this.sourceDir, envWithAdminPort);
127
+ const childProcess = (0, python_1.runWithVirtualEnv)(args, this.sourceDir, envWithAdminPort, {
128
+ detached: !utils_1.IS_WINDOWS,
129
+ });
124
130
  childProcess.stdout?.on("data", (chunk) => {
125
131
  logger_1.logger.info(chunk.toString("utf8"));
126
132
  });
127
133
  childProcess.stderr?.on("data", (chunk) => {
128
134
  logger_1.logger.error(chunk.toString("utf8"));
129
135
  });
130
- return Promise.resolve(async () => {
131
- try {
132
- await fetch(`http://127.0.0.1:${port}/__/quitquitquit`);
133
- }
134
- catch (e) {
135
- logger_1.logger.debug("Failed to call quitquitquit. This often means the server failed to start", e);
136
- }
137
- const quitTimeout = setTimeout(() => {
138
- if (!childProcess.killed) {
139
- childProcess.kill("SIGKILL");
140
- }
141
- }, 10000);
142
- clearTimeout(quitTimeout);
143
- return new Promise((resolve, reject) => {
144
- childProcess.once("exit", resolve);
145
- childProcess.once("error", reject);
136
+ const exited = new Promise((resolve) => {
137
+ childProcess.once("exit", () => resolve());
138
+ childProcess.once("error", () => resolve());
139
+ });
140
+ (0, python_1.trackVirtualEnvChild)(childProcess);
141
+ return Promise.resolve(() => this.shutdownAdmin(childProcess, port, exited));
142
+ }
143
+ async shutdownAdmin(childProcess, port, exited) {
144
+ try {
145
+ await fetch(`http://127.0.0.1:${port}/__/quitquitquit`, {
146
+ signal: AbortSignal.timeout(QUITQUITQUIT_TIMEOUT_MS),
146
147
  });
148
+ }
149
+ catch (e) {
150
+ logger_1.logger.debug("Failed to call quitquitquit. This often means the server failed to start", e);
151
+ }
152
+ const forceKill = setTimeout(() => {
153
+ if (childProcess.pid) {
154
+ logger_1.logger.debug(`Discovery admin server on port ${port} did not shut down when asked. Force-killing it.`);
155
+ (0, python_1.killProcessTree)(childProcess.pid);
156
+ }
157
+ }, FORCE_KILL_DELAY_MS);
158
+ let giveUp;
159
+ const timedOut = new Promise((resolve) => {
160
+ giveUp = setTimeout(() => resolve(false), SHUTDOWN_TIMEOUT_MS);
147
161
  });
162
+ try {
163
+ const exitedCleanly = await Promise.race([exited.then(() => true), timedOut]);
164
+ if (exitedCleanly) {
165
+ (0, python_1.untrackVirtualEnvChild)(childProcess);
166
+ }
167
+ else {
168
+ logger_1.logger.debug(`Discovery admin server on port ${port} survived being force-killed. ` +
169
+ `Continuing without it; it may need to be cleaned up manually.`);
170
+ }
171
+ }
172
+ finally {
173
+ clearTimeout(forceKill);
174
+ clearTimeout(giveUp);
175
+ childProcess.stdout?.destroy();
176
+ childProcess.stderr?.destroy();
177
+ childProcess.unref();
178
+ }
148
179
  }
149
180
  async discoverBuild(_configValues, envs) {
150
181
  let discovered = await discovery.detectFromYaml(this.sourceDir, this.projectId, this.runtime);
@@ -5,6 +5,10 @@ const crypto_1 = require("crypto");
5
5
  const types_1 = require("../types");
6
6
  const emulatorLogger_1 = require("../emulatorLogger");
7
7
  const registry_1 = require("../registry");
8
+ const AUTH_V2_ACTION_MAP = {
9
+ create: "created",
10
+ delete: "deleted",
11
+ };
8
12
  class AuthCloudFunction {
9
13
  constructor(projectId) {
10
14
  this.projectId = projectId;
@@ -16,17 +20,32 @@ class AuthCloudFunction {
16
20
  if (!this.enabled)
17
21
  return;
18
22
  const userInfoPayload = this.createUserInfoPayload(user);
19
- const multicastEventBody = this.createEventRequestBody(action, userInfoPayload);
23
+ const legacyEventBody = this.createEventRequestBody(action, userInfoPayload);
24
+ const v2CloudEventBody = this.createCloudEventRequestBody(action, userInfoPayload);
20
25
  const c = registry_1.EmulatorRegistry.client(types_1.Emulators.FUNCTIONS);
21
- let res;
26
+ const errStatus = [];
22
27
  let err;
23
28
  try {
24
- res = await c.post(`/functions/projects/${this.projectId}/trigger_multicast`, multicastEventBody);
29
+ const legacyRes = await c.post(`/functions/projects/${this.projectId}/trigger_multicast`, legacyEventBody);
30
+ if (legacyRes.status !== 200) {
31
+ errStatus.push(legacyRes.status);
32
+ }
25
33
  }
26
34
  catch (e) {
27
- err = e;
35
+ err = e instanceof Error ? e : new Error(String(e));
28
36
  }
29
- if (err || res?.status !== 200) {
37
+ try {
38
+ const v2Res = await c.post(`/functions/projects/${this.projectId}/trigger_multicast`, v2CloudEventBody, {
39
+ headers: { "Content-Type": "application/cloudevents+json; charset=UTF-8" },
40
+ });
41
+ if (v2Res.status !== 200) {
42
+ errStatus.push(v2Res.status);
43
+ }
44
+ }
45
+ catch (e) {
46
+ err = e instanceof Error ? e : new Error(String(e));
47
+ }
48
+ if (err || errStatus.length > 0) {
30
49
  this.logger.logLabeled("WARN", "functions", `Firebase Authentication function was not triggered due to emulation error. Please file a bug.`);
31
50
  }
32
51
  }
@@ -43,6 +62,22 @@ class AuthCloudFunction {
43
62
  data: userInfoPayload,
44
63
  };
45
64
  }
65
+ createCloudEventRequestBody(action, userInfoPayload) {
66
+ const ceAction = AUTH_V2_ACTION_MAP[action];
67
+ const cloudEvent = {
68
+ specversion: "1.0",
69
+ id: (0, crypto_1.randomUUID)(),
70
+ time: new Date().toISOString(),
71
+ type: `google.firebase.auth.user.v2.${ceAction}`,
72
+ source: `//identitytoolkit.googleapis.com/projects/${this.projectId}`,
73
+ subject: `users/${userInfoPayload.uid}`,
74
+ data: action === "create" ? { value: userInfoPayload } : { oldValue: userInfoPayload },
75
+ };
76
+ if (userInfoPayload.tenantId) {
77
+ cloudEvent.tenantid = userInfoPayload.tenantId;
78
+ }
79
+ return cloudEvent;
80
+ }
46
81
  createUserInfoPayload(user) {
47
82
  return {
48
83
  uid: user.localId,
@@ -54,36 +54,36 @@
54
54
  },
55
55
  "dataconnect": {
56
56
  "darwin": {
57
- "version": "3.4.19",
58
- "expectedSize": 33412928,
59
- "expectedChecksum": "5a65cd626d5c022eab4c2036b18f0314",
60
- "expectedChecksumSHA256": "4a63243e720d26de7e2e5bd5060fc92768f09446ec42b3369fb6ddc06a9cdddf",
61
- "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-macos-amd64-v3.4.19",
62
- "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.19"
57
+ "version": "3.4.20",
58
+ "expectedSize": 33787120,
59
+ "expectedChecksum": "a8c044198a62239fc20a31ef545f8eea",
60
+ "expectedChecksumSHA256": "4cbef4430bb5ad72f8fbe2293b938463a1e912b5c17b5577c6546343fe3149a9",
61
+ "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-macos-amd64-v3.4.20",
62
+ "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.20"
63
63
  },
64
64
  "darwin_arm64": {
65
- "version": "3.4.19",
66
- "expectedSize": 31539602,
67
- "expectedChecksum": "cd914718f705a9e614bc3024f443bb52",
68
- "expectedChecksumSHA256": "dafb2e532c29d876cb30d5c2bf32b2e50a614386dc16ba82b0ed6a9fca2a6db3",
69
- "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-macos-arm64-v3.4.19",
70
- "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.19"
65
+ "version": "3.4.20",
66
+ "expectedSize": 31883698,
67
+ "expectedChecksum": "8c8cf2b1c8b99cb7ebd459ca383aa8ed",
68
+ "expectedChecksumSHA256": "873e9aab3aa09a946d4a729e5755d38c5d607655796f5a031f7b21c339fa5ef7",
69
+ "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-macos-arm64-v3.4.20",
70
+ "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.20"
71
71
  },
72
72
  "win32": {
73
- "version": "3.4.19",
74
- "expectedSize": 33444864,
75
- "expectedChecksum": "e2f84df8d6c536bea29d2ccc4cb21e79",
76
- "expectedChecksumSHA256": "756e370334ef982547e7252b3f91fd75b35f85c5d3666e8f3773a4a19a00c8f8",
77
- "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-windows-amd64-v3.4.19",
78
- "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.19.exe"
73
+ "version": "3.4.20",
74
+ "expectedSize": 33819136,
75
+ "expectedChecksum": "2bb404ba566f5e2d7224a802c860035c",
76
+ "expectedChecksumSHA256": "5e613eddc18378c8b917a94bd7380e6174918ccb29f5bed915927434078bc4a7",
77
+ "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-windows-amd64-v3.4.20",
78
+ "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.20.exe"
79
79
  },
80
80
  "linux": {
81
- "version": "3.4.19",
82
- "expectedSize": 32542904,
83
- "expectedChecksum": "63f099c9b9dad6e7d2adddae8af884a3",
84
- "expectedChecksumSHA256": "bc74b68cc4bafcccc57dbe659a74b4403c225f01f851b5a4a61dcea81e8b1310",
85
- "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-linux-amd64-v3.4.19",
86
- "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.19"
81
+ "version": "3.4.20",
82
+ "expectedSize": 32911544,
83
+ "expectedChecksum": "9ae887603b8085e50ff992dd7c86385c",
84
+ "expectedChecksumSHA256": "0500ecb9f22c8e26df1f650e656497b542f26b47b3b5730fde850a918643ca2f",
85
+ "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-linux-amd64-v3.4.20",
86
+ "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.20"
87
87
  }
88
88
  }
89
89
  }