firebase-tools 15.29.0 → 15.30.1

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.
Files changed (38) hide show
  1. package/lib/commands/ext-export.js +28 -2
  2. package/lib/commands/ext-migrate.js +73 -4
  3. package/lib/commands/ext-uninstall.js +36 -23
  4. package/lib/commands/functions-kits-install.js +4 -1
  5. package/lib/commands/functions-kits-uninstall.js +25 -16
  6. package/lib/deploy/functions/build.js +9 -7
  7. package/lib/deploy/functions/delete.js +47 -22
  8. package/lib/deploy/functions/ensure.js +42 -2
  9. package/lib/deploy/functions/functionsDeployHelper.js +7 -0
  10. package/lib/deploy/functions/params.js +2 -1
  11. package/lib/deploy/functions/prepare.js +3 -4
  12. package/lib/deploy/functions/release/executor.js +14 -8
  13. package/lib/deploy/functions/release/fabricator.js +42 -20
  14. package/lib/deploy/functions/release/planner.js +2 -4
  15. package/lib/deploy/functions/release/sourceTokenScraper.js +16 -2
  16. package/lib/emulator/downloadableEmulatorInfo.json +31 -31
  17. package/lib/emulator/tasksEmulator.js +2 -2
  18. package/lib/extensions/export.js +64 -2
  19. package/lib/extensions/extensionsHelper.js +1 -2
  20. package/lib/extensions/manifest.js +5 -4
  21. package/lib/extensions/migrate.js +71 -2
  22. package/lib/functions/env.js +21 -4
  23. package/lib/functions/kits/install.js +27 -10
  24. package/lib/gcp/iam.js +8 -17
  25. package/lib/gcp/resourceManager.js +31 -22
  26. package/lib/gcp/run.js +2 -2
  27. package/lib/mcp/onemcp/index.js +19 -0
  28. package/lib/mcp/onemcp/onemcp_server.js +12 -7
  29. package/lib/mcp/tools/dataconnect/execute.js +33 -19
  30. package/lib/mcp/tools/dataconnect/index.js +1 -1
  31. package/lib/throttler/throttler.js +2 -11
  32. package/lib/tsconfig.compile.tsbuildinfo +1 -1
  33. package/lib/tsconfig.publish.tsbuildinfo +1 -1
  34. package/lib/utils.js +26 -0
  35. package/package.json +1 -1
  36. package/templates/init/functions/typescript/index-kit-migration.ts +1 -0
  37. package/templates/init/functions/typescript/index-kit.ts +1 -0
  38. package/templates/init/functions/typescript/tsconfig.json +2 -1
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.command = void 0;
4
+ exports.hasNonEmptyProjectEnv = hasNonEmptyProjectEnv;
4
5
  exports.handleSecretEjection = handleSecretEjection;
5
6
  const checkMinRequiredVersion_1 = require("../checkMinRequiredVersion");
6
7
  const command_1 = require("../command");
@@ -25,6 +26,7 @@ const config_1 = require("../config");
25
26
  const projectConfig_1 = require("../functions/projectConfig");
26
27
  const error_1 = require("../error");
27
28
  const experiments = require("../experiments");
29
+ const migrate_1 = require("../extensions/migrate");
28
30
  exports.command = new command_1.Command("ext:export")
29
31
  .description("export Extension instances installed on a project to a local Firebase directory")
30
32
  .option(`--mode <target>`, `experimental: controls the target system of the export (supports "extensions", "functions")`)
@@ -100,7 +102,7 @@ async function fnHandler(options) {
100
102
  return;
101
103
  }
102
104
  const projectId = (0, projectUtils_1.needProjectId)(options);
103
- const instance = await (0, extensionsApi_1.getInstance)(projectId, options.instance);
105
+ let instance = await (0, extensionsApi_1.getInstance)(projectId, options.instance);
104
106
  if (typeof instance === "undefined") {
105
107
  logger_1.logger.info(`No extension matching instance ID ${options.instance} found`);
106
108
  return;
@@ -108,6 +110,14 @@ async function fnHandler(options) {
108
110
  if (instance.state !== "ACTIVE" && !options.force) {
109
111
  throw new error_1.FirebaseError(`Extension ${options.instance} is in state ${instance.state}. To export a non-ACTIVE extension, use the --force option.`);
110
112
  }
113
+ instance = await (0, extensionsHelper_1.ensureInstanceSpec)(instance);
114
+ if (!instance.config?.source?.spec) {
115
+ throw new error_1.FirebaseError(`Could not load extension specification for ${options.instance}. Unable to export configuration.`);
116
+ }
117
+ instance = await (0, migrate_1.ensureInstanceUpToDate)(projectId, instance, {
118
+ nonInteractive: options.nonInteractive,
119
+ force: options.force,
120
+ });
111
121
  const instanceId = (0, utils_1.last)(instance.name.split("/")) ?? "";
112
122
  if (instanceId !== options.instance) {
113
123
  return;
@@ -115,7 +125,7 @@ async function fnHandler(options) {
115
125
  await handleSecretEjection(options, instance);
116
126
  const convertedEnv = (0, export_1.functionsEnvFromInstance)(instance);
117
127
  const writeLocation = kitExportTarget(instanceId, projectId, options);
118
- if ((0, env_1.hasUserEnvs)(writeLocation)) {
128
+ if (hasNonEmptyProjectEnv(writeLocation)) {
119
129
  logger_1.logger.info(`Exported extensions config appears to already exist in /${instanceId}, aborting write.`);
120
130
  }
121
131
  else {
@@ -126,6 +136,22 @@ async function fnHandler(options) {
126
136
  (0, env_1.writeUserEnvs)(convertedEnv, writeLocation);
127
137
  }
128
138
  }
139
+ function hasNonEmptyProjectEnv(opts) {
140
+ const configDir = opts.configDir || opts.functionsSource;
141
+ const files = [
142
+ `.env.${opts.projectId}`,
143
+ ...(opts.projectAlias ? [`.env.${opts.projectAlias}`] : []),
144
+ ];
145
+ return files.some((f) => {
146
+ const fullPath = (0, path_1.join)(configDir, f);
147
+ try {
148
+ return (0, fs_1.statSync)(fullPath).size > 0;
149
+ }
150
+ catch {
151
+ return false;
152
+ }
153
+ });
154
+ }
129
155
  async function handleSecretEjection(options, instance) {
130
156
  const secrets = await (0, export_1.secretsNeedingEjection)(instance);
131
157
  if (secrets.length === 0) {
@@ -5,21 +5,42 @@ const clc = require("colorette");
5
5
  const checkMinRequiredVersion_1 = require("../checkMinRequiredVersion");
6
6
  const command_1 = require("../command");
7
7
  const projectUtils_1 = require("../projectUtils");
8
+ const experiments = require("../experiments");
8
9
  const extensionsHelper_1 = require("../extensions/extensionsHelper");
9
10
  const requirePermissions_1 = require("../requirePermissions");
11
+ const requireConfig_1 = require("../requireConfig");
10
12
  const migrate_1 = require("../extensions/migrate");
13
+ const export_1 = require("../extensions/export");
14
+ const install_1 = require("../functions/kits/install");
11
15
  const kits_1 = require("../functions/kits");
12
- const logger_1 = require("../logger");
13
16
  const utils_1 = require("../utils");
17
+ const error_1 = require("../error");
18
+ const deploy_1 = require("../deploy");
19
+ const checkIam_1 = require("../deploy/functions/checkIam");
20
+ const prompt_1 = require("../prompt");
14
21
  exports.command = new command_1.Command("ext:migrate")
15
22
  .description("migrate an extension instance to a function kit")
16
23
  .option("-p, --package <package>", "optional kit package override to use")
17
- .option("-i, --ext-instance <instanceId>", "extension instance ID to migrate")
24
+ .option("--ext-instance <instanceId>", "extension instance ID to migrate")
18
25
  .option("-e, --extension <extensionRef>", "extension reference or name to migrate")
19
26
  .option("-f, --force", "force update and migration without prompting")
20
- .before(requirePermissions_1.requirePermissions, ["firebaseextensions.instances.list"])
27
+ .before(() => {
28
+ experiments.assertEnabled("extMigrationFeatures", "migrate an extension instance to a function kit");
29
+ experiments.assertEnabled("kits", "migrate an extension instance to a function kit");
30
+ experiments.assertEnabled("secretEnvParams", "migrate an extension instance to a function kit");
31
+ })
32
+ .before(requireConfig_1.requireConfig)
33
+ .before(requirePermissions_1.requirePermissions, [
34
+ "firebaseextensions.instances.list",
35
+ "firebaseextensions.instances.delete",
36
+ ...deploy_1.TARGET_PERMISSIONS["functions"],
37
+ ])
21
38
  .before(extensionsHelper_1.ensureExtensionsApiEnabled)
22
39
  .before(checkMinRequiredVersion_1.checkMinRequiredVersion, "extMinVersion")
40
+ .before((options) => {
41
+ const projectId = (0, projectUtils_1.needProjectId)(options);
42
+ return (0, checkIam_1.checkServiceAccountIam)(projectId);
43
+ })
23
44
  .action(async (options) => {
24
45
  const projectId = (0, projectUtils_1.needProjectId)(options);
25
46
  if (options.package) {
@@ -33,7 +54,55 @@ exports.command = new command_1.Command("ext:migrate")
33
54
  force: options.force,
34
55
  });
35
56
  (0, utils_1.logLabeledBullet)(extensionsHelper_1.logPrefix, `Selected instance ${clc.bold(plan.instanceId)} (${plan.kitPackage}) for migration.`);
57
+ plan.instance = await (0, extensionsHelper_1.ensureInstanceSpec)(plan.instance);
58
+ if (!plan.instance.config?.source?.spec) {
59
+ throw new error_1.FirebaseError(`Could not load extension specification for ${clc.bold(plan.instanceId)}. Unable to export configuration.`);
60
+ }
36
61
  plan.instance = await (0, migrate_1.ensureInstanceUpToDate)(projectId, plan.instance, options);
37
- logger_1.logger.info("TODO: Draw the rest of the owl");
62
+ if (plan.instance.state !== "ACTIVE") {
63
+ (0, utils_1.logLabeledWarning)(extensionsHelper_1.logPrefix, `Extension instance ${clc.bold(plan.instanceId)} is in state ${plan.instance.state}. Migration may not function as expected.`);
64
+ }
65
+ const exportedEnvs = (0, export_1.functionsEnvFromInstance)(plan.instance);
66
+ await (0, migrate_1.migrateSecrets)(plan.instance, { force: options.force });
67
+ (0, utils_1.logLabeledBullet)(extensionsHelper_1.logPrefix, `Installing kit ${clc.bold(plan.kitPackage)} for instance ${clc.bold(plan.instanceId)}...`);
68
+ const installResult = await (0, install_1.installKitOrInstance)({
69
+ ...options,
70
+ config: options.config,
71
+ package: plan.kitPackage,
72
+ template: "migration",
73
+ defaultInstanceId: plan.instanceId,
74
+ seedEnv: {
75
+ projectId,
76
+ envs: exportedEnvs,
77
+ },
78
+ });
79
+ const kitInstanceId = installResult.instanceId;
80
+ if (!kitInstanceId) {
81
+ throw new error_1.FirebaseError("Kit installation failed: no instance ID returned.", { exit: 1 });
82
+ }
83
+ (0, utils_1.logLabeledBullet)(extensionsHelper_1.logPrefix, `Deploying functions kit instance ${clc.bold(kitInstanceId)}...`);
84
+ const deployOptions = {
85
+ ...options,
86
+ only: `functions:${kitInstanceId}`,
87
+ filteredTargets: ["functions"],
88
+ project: projectId,
89
+ };
90
+ try {
91
+ await (0, deploy_1.deploy)(["functions"], deployOptions);
92
+ }
93
+ catch (err) {
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
+ }
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?`,
98
+ default: false,
99
+ nonInteractive: options.nonInteractive,
100
+ force: options.force,
101
+ });
102
+ if (!shouldUninstall) {
103
+ (0, utils_1.logLabeledBullet)(extensionsHelper_1.logPrefix, `You may safely uninstall extension instance ${clc.bold(plan.instanceId)} in the future with the command ${clc.bold(`firebase ext:uninstall ${plan.instanceId} --project ${projectId} --immediate`)}`);
104
+ return plan;
105
+ }
106
+ await (0, migrate_1.uninstallExtension)(projectId, plan.instanceId, options, true);
38
107
  return plan;
39
108
  });
@@ -7,14 +7,16 @@ const extensionsHelper_1 = require("../extensions/extensionsHelper");
7
7
  const requirePermissions_1 = require("../requirePermissions");
8
8
  const utils_1 = require("../utils");
9
9
  const manifest = require("../extensions/manifest");
10
- const extensionsApi_1 = require("../extensions/extensionsApi");
11
10
  const projectUtils_1 = require("../projectUtils");
12
- const prompt_1 = require("../prompt");
11
+ const migrate_1 = require("../extensions/migrate");
12
+ const extensionsApi_1 = require("../extensions/extensionsApi");
13
+ const export_1 = require("../extensions/export");
13
14
  const error_1 = require("../error");
15
+ const prompt_1 = require("../prompt");
14
16
  exports.command = new command_1.Command("ext:uninstall <extensionInstanceId>")
15
17
  .description("uninstall an extension that is installed in your Firebase project by instance ID")
16
18
  .option("--local", "deprecated")
17
- .option("--immediate", "immediately destroy GCP resources instead of waiting on next deploy. Can be run outside a firebase project directory.")
19
+ .option("--immediate", "immediately destroy GCP resources instead of waiting on next deploy. Can be run outside a firebase project directory if --project is specified.")
18
20
  .withForce()
19
21
  .before(requirePermissions_1.requirePermissions, ["firebaseextensions.instances.delete"])
20
22
  .before(extensionsHelper_1.ensureExtensionsApiEnabled)
@@ -26,31 +28,42 @@ exports.command = new command_1.Command("ext:uninstall <extensionInstanceId>")
26
28
  }
27
29
  if (options.immediate) {
28
30
  const projectId = (0, projectUtils_1.needProjectId)(options);
29
- let config;
31
+ let instance;
30
32
  try {
31
- config = manifest.loadConfig(options);
32
- }
33
- catch {
34
- (0, utils_1.logLabeledBullet)(extensionsHelper_1.logPrefix, "No firebase.json found. Proceeding to immediate extension instance teardown.");
33
+ instance = await (0, extensionsApi_1.getInstance)(projectId, instanceId);
35
34
  }
36
- if (config && manifest.instanceExists(instanceId, config)) {
37
- manifest.removeFromManifest(instanceId, config);
38
- }
39
- if (!(await (0, prompt_1.confirm)({
40
- message: `About to delete Extensions instance ${projectId}/${instanceId}, its associated resources, and service account. Continue?`,
41
- nonInteractive: options.nonInteractive,
42
- force: options.force,
43
- default: true,
44
- }))) {
45
- return;
35
+ catch (err) {
36
+ if (err instanceof error_1.FirebaseError && err.status === 404) {
37
+ (0, utils_1.logLabeledWarning)(extensionsHelper_1.logPrefix, "ext:uninstall called with --immediate, but no deployed GCP resources found for the extension.");
38
+ const config = manifest.loadConfig(options);
39
+ manifest.removeFromManifest(instanceId, config);
40
+ return;
41
+ }
42
+ throw new error_1.FirebaseError(`Failed to retrieve extension instance ${instanceId}: ${err instanceof Error ? err.message : String(err)}`, {
43
+ original: err instanceof Error ? err : undefined,
44
+ exit: 1,
45
+ });
46
46
  }
47
- try {
48
- await (0, extensionsApi_1.deleteInstance)(projectId, instanceId);
47
+ if (!instance) {
48
+ throw new error_1.FirebaseError(`Failed to retrieve extension instance ${instanceId}`);
49
49
  }
50
- catch (err) {
51
- throw new error_1.FirebaseError(`Error when attempting deletion: ${err instanceof Error ? err.message : String(err)}`, { original: err instanceof Error ? err : undefined });
50
+ instance = await (0, extensionsHelper_1.ensureInstanceSpec)(instance);
51
+ const outstandingSecrets = await (0, export_1.secretsNeedingEjection)(instance);
52
+ if (outstandingSecrets.length > 0) {
53
+ const shouldContinue = await (0, prompt_1.confirm)({
54
+ message: `Extension instance ${instanceId} has secrets with the "firebase-extensions-managed" label:\n${outstandingSecrets.join(", ")}\nContinuing with extension uninstall will permanently destroy these secrets.\nYou can keep these secrets by running ext:export, or by manually removing the label in the Cloud Console.\nContinue?`,
55
+ default: false,
56
+ nonInteractive: options.nonInteractive,
57
+ force: options.force,
58
+ });
59
+ if (!shouldContinue) {
60
+ if (options.nonInteractive && !options.force) {
61
+ throw new error_1.FirebaseError(`Extension instance ${instanceId} has managed secrets that would be permanently destroyed. Re-run with --force in non-interactive mode to confirm deletion.`);
62
+ }
63
+ return;
64
+ }
52
65
  }
53
- (0, utils_1.logLabeledSuccess)(extensionsHelper_1.logPrefix, `Deleted Extensions instance ${projectId}/${instanceId}.`);
66
+ await (0, migrate_1.uninstallExtension)(projectId, instanceId, options, false);
54
67
  return;
55
68
  }
56
69
  const config = manifest.loadConfig(options);
@@ -9,14 +9,17 @@ const requireAuth_1 = require("../requireAuth");
9
9
  const requireConfig_1 = require("../requireConfig");
10
10
  exports.command = new command_1.Command("functions:kits:install")
11
11
  .description("install a function kit into your project")
12
+ .before(() => {
13
+ experiments.assertEnabled("kits", "install a function kit");
14
+ })
12
15
  .before(requireConfig_1.requireConfig)
13
16
  .before(requireAuth_1.requireAuth)
17
+ .withForce()
14
18
  .option("--package <package>", "NPM package name or specifier to install as a function kit")
15
19
  .option("--directory <directory>", "path to a local functions codebase directory to install as a function kit")
16
20
  .option(`--template <template>`, `template to use for the kit index file (${Object.keys(install_1.TEMPLATES).join("|")})`)
17
21
  .option("--no-configure", "skip parameter prompting and configuration during installation")
18
22
  .action(async (options) => {
19
- experiments.assertEnabled("kits", "install a function kit");
20
23
  if (!options.config) {
21
24
  throw new error_1.FirebaseError("Not in a Firebase project directory (firebase.json not found).");
22
25
  }
@@ -14,11 +14,12 @@ const utils_1 = require("../utils");
14
14
  const logger_1 = require("../logger");
15
15
  const delete_1 = require("../deploy/functions/delete");
16
16
  exports.command = new command_1.Command("functions:kits:uninstall")
17
- .description("uninstall a function kit or kit instance from your project")
17
+ .description("uninstall a function kit or kit instance from your project. Deletes all running resources and the associated managed service account.")
18
18
  .before(requireConfig_1.requireConfig)
19
19
  .before(requireAuth_1.requireAuth)
20
20
  .option("--kit <kitId>", "")
21
21
  .option("--instance <instanceId>", "")
22
+ .withForce()
22
23
  .action(async (options) => {
23
24
  const firebaseConfig = options.config;
24
25
  if (options.instance && options.kit) {
@@ -72,19 +73,15 @@ async function handleInstance(options, config) {
72
73
  const instanceConfigDirPath = kitForInstance.instances[instanceId];
73
74
  const conservativeDeletion = nonstandardKitLayout(kitForInstance);
74
75
  logger_1.logger.debug(`Kit ${kitForInstance.kit} uninstall mode: conservativeDeletion=${conservativeDeletion}`);
75
- const projectsWithConfigs = [];
76
76
  const configDirContents = config.lsProjectDir(instanceConfigDirPath);
77
- const fileNames = configDirContents.filter((f) => f.isFile()).map((f) => f.name);
78
- for (const fileName of fileNames) {
79
- if (!fileName.startsWith(".env.")) {
80
- continue;
81
- }
82
- projectsWithConfigs.push(fileName.slice(".env.".length));
83
- }
84
- if (projectsWithConfigs.length > 0 && !projectsWithConfigs.includes(projectId)) {
77
+ const envFileNames = configDirContents
78
+ .filter((f) => f.isFile() && f.name.startsWith(".env."))
79
+ .map((f) => f.name.slice(".env.".length));
80
+ const projectNamesInEnvs = envFileNames.map((envName) => options.rc ? options.rc.resolveAlias(envName) : envName);
81
+ if (projectNamesInEnvs.length > 0 && !projectNamesInEnvs.includes(projectId)) {
85
82
  throw new error_1.FirebaseError(`Instance at ${instanceConfigDirPath} contains no .env file for current project`);
86
83
  }
87
- if (projectsWithConfigs.length === 0 || projectsWithConfigs.length === 1) {
84
+ if (envFileNames.length === 0 || envFileNames.length === 1) {
88
85
  if (Object.keys(kitForInstance.instances).length > 1) {
89
86
  await uninstallInstance(options, config, instanceId, instanceConfigDirPath, conservativeDeletion);
90
87
  return;
@@ -101,7 +98,15 @@ async function handleInstance(options, config) {
101
98
  await uninstallKit(options, config, kitForInstance);
102
99
  return;
103
100
  }
104
- await uninstallProjectInstance(options, config, projectId, instanceId, instanceConfigDirPath);
101
+ let filesystemNameForProject = projectId;
102
+ const envFilesWhichAliasToProject = envFileNames.filter((name) => (options.rc?.resolveAlias(name) || name) === projectId);
103
+ if (envFilesWhichAliasToProject.length > 1) {
104
+ throw new error_1.FirebaseError(`Instance ${instanceId} contains multiple .env files which ambiguously resolve to the current project ${envFilesWhichAliasToProject.map((s) => ".env." + s).join(", ")}`);
105
+ }
106
+ if (envFilesWhichAliasToProject.length === 1) {
107
+ filesystemNameForProject = envFilesWhichAliasToProject[0];
108
+ }
109
+ await uninstallProjectInstance(options, config, filesystemNameForProject, instanceId, instanceConfigDirPath);
105
110
  }
106
111
  async function uninstallInstance(options, config, instanceId, instanceConfigDirPath, onlyDeleteEmpty) {
107
112
  const configDirContents = config.lsProjectDir(instanceConfigDirPath);
@@ -110,8 +115,8 @@ async function uninstallInstance(options, config, instanceId, instanceConfigDirP
110
115
  if (!fileName.startsWith(".env.")) {
111
116
  continue;
112
117
  }
113
- const projectId = fileName.replace(new RegExp("^.env."), "");
114
- await uninstallProjectInstance(options, config, projectId, instanceId, instanceConfigDirPath);
118
+ const projectIdOrAlias = fileName.slice(".env.".length);
119
+ await uninstallProjectInstance(options, config, projectIdOrAlias, instanceId, instanceConfigDirPath);
115
120
  }
116
121
  if (!onlyDeleteEmpty || configDirEmpty(config, instanceConfigDirPath)) {
117
122
  config.deleteProjectDir(instanceConfigDirPath);
@@ -134,8 +139,12 @@ async function uninstallInstance(options, config, instanceId, instanceConfigDirP
134
139
  config.set("functions", functionsConfig);
135
140
  config.writeProjectFile("firebase.json", config.src);
136
141
  }
137
- async function uninstallProjectInstance(options, config, projectId, instanceId, kitInstancePath) {
138
- const envFilePath = (0, path_1.join)(kitInstancePath, `.env.${projectId}`);
142
+ async function uninstallProjectInstance(options, config, envName, instanceId, kitInstancePath) {
143
+ const projectId = options.rc?.resolveAlias(envName) || envName;
144
+ const envFilePath = (0, path_1.join)(kitInstancePath, `.env.${envName}`);
145
+ if (!config.projectFileExists(envFilePath)) {
146
+ throw new error_1.FirebaseError(`Expected to clean up project kit instance .env file at ${envFilePath}, but it doesn't exist.`);
147
+ }
139
148
  const epFilters = [{ codebase: instanceId }];
140
149
  const deployContext = { projectId: projectId, filters: epFilters };
141
150
  const deletionCount = await (0, delete_1.deleteFunctionsByEndpointFilters)(deployContext, options);
@@ -82,7 +82,15 @@ exports.AllIngressSettings = [
82
82
  "ALLOW_INTERNAL_AND_GCLB",
83
83
  ];
84
84
  async function resolveBackend(opts) {
85
- const { paramValues: paramValues, secretRefs: secretRefs } = await params.resolveParams(opts.build.params, opts.firebaseConfig, envWithTypes(opts.build.params, opts.userEnvs), opts.codebase, opts.nonInteractive, opts.force, opts.isEmulator);
85
+ const { paramValues: paramValues, secretRefs: secretRefs } = await params.resolveParams({
86
+ params: opts.build.params,
87
+ firebaseConfig: opts.firebaseConfig,
88
+ userEnvs: envWithTypes(opts.build.params, opts.userEnvs),
89
+ codebase: opts.codebase,
90
+ nonInteractive: opts.nonInteractive,
91
+ force: opts.force,
92
+ isEmulator: opts.isEmulator,
93
+ });
86
94
  return { backend: toBackend(opts.build, paramValues), envs: paramValues, secretRefs: secretRefs };
87
95
  }
88
96
  function envWithTypes(definedParams, rawEnvs) {
@@ -392,12 +400,6 @@ function applyPrefix(build, prefix) {
392
400
  throw new error_1.FirebaseError(`Function id '${newId}' is invalid after applying prefix '${prefix}'. Function names must start with a letter and can contain letters, numbers, underscores, and hyphens, with a maximum length of 63 characters.`);
393
401
  }
394
402
  newEndpoints[newId] = endpoint;
395
- if (endpoint.secretEnvironmentVariables) {
396
- endpoint.secretEnvironmentVariables = endpoint.secretEnvironmentVariables.map((secret) => ({
397
- ...secret,
398
- secret: `${prefix}-${secret.secret}`,
399
- }));
400
- }
401
403
  }
402
404
  build.endpoints = newEndpoints;
403
405
  if (build.lifecycleHooks) {
@@ -8,33 +8,57 @@ const fabricator = require("./release/fabricator");
8
8
  const functionsDeployHelper_1 = require("./functionsDeployHelper");
9
9
  const getProjectNumber_1 = require("../../getProjectNumber");
10
10
  const reporter = require("./release/reporter");
11
- const error_1 = require("../../error");
12
- const functional_1 = require("../../functional");
13
- const prompt_1 = require("../../prompt");
11
+ const prompt = require("../../prompt");
14
12
  const functionsConfig = require("../../functionsConfig");
13
+ const error_1 = require("../../error");
14
+ const projectConfig_1 = require("../../functions/projectConfig");
15
15
  async function deleteFunctionsByEndpointFilters(context, options) {
16
- let haveBackend = await backend.existingBackend(context);
17
- if (options?.region) {
18
- haveBackend = backend.matchingBackend(haveBackend, (endpoint) => endpoint.region === options.region);
16
+ const allExistingBackend = await backend.existingBackend(context);
17
+ const targetedRegionBackend = options?.region
18
+ ? backend.matchingBackend(allExistingBackend, (endpoint) => endpoint.region === options.region)
19
+ : allExistingBackend;
20
+ const codebases = new Set(backend.allEndpoints(allExistingBackend).map((ep) => ep.codebase || projectConfig_1.DEFAULT_CODEBASE));
21
+ const deploymentPlan = {};
22
+ for (const codebase of codebases) {
23
+ const allCodebaseBackend = backend.matchingBackend(allExistingBackend, (ep) => (ep.codebase || projectConfig_1.DEFAULT_CODEBASE) === codebase);
24
+ const targetedCodebaseBackend = backend.matchingBackend(targetedRegionBackend, (ep) => (ep.codebase || projectConfig_1.DEFAULT_CODEBASE) === codebase);
25
+ const totalEndpointsInGcp = backend.allEndpoints(allCodebaseBackend);
26
+ const endpointsToDelete = backend
27
+ .allEndpoints(targetedCodebaseBackend)
28
+ .filter((e) => (0, functionsDeployHelper_1.endpointMatchesAnyFilter)(e, context.filters));
29
+ let existingManagedSA;
30
+ if (endpointsToDelete.length > 0 && endpointsToDelete.length === totalEndpointsInGcp.length) {
31
+ const ep = totalEndpointsInGcp.find((e) => typeof e.serviceAccount === "string" && e.serviceAccount.startsWith("firebase-fn-"));
32
+ existingManagedSA = ep?.serviceAccount;
33
+ }
34
+ deploymentPlan[codebase] = await planner.createDeploymentPlan({
35
+ wantBackend: backend.empty(),
36
+ haveBackend: targetedCodebaseBackend,
37
+ codebase,
38
+ projectId: context.projectId,
39
+ filters: context.filters,
40
+ deleteAll: true,
41
+ existingManagedSA,
42
+ });
19
43
  }
20
- const plan = await planner.createDeploymentPlan({
21
- wantBackend: backend.empty(),
22
- haveBackend: haveBackend,
23
- codebase: "",
24
- projectId: context.projectId,
25
- filters: context.filters,
26
- deleteAll: true,
27
- });
28
- const allEpToDelete = Object.values(plan.regionalChangesets)
29
- .map((changes) => changes.endpointsToDelete)
30
- .reduce(functional_1.reduceFlat, [])
44
+ const allEpToDelete = Object.values(deploymentPlan)
45
+ .flatMap((plan) => Object.values(plan.regionalChangesets).flatMap((changes) => changes.endpointsToDelete))
31
46
  .sort(backend.compareFunctions);
32
47
  if (allEpToDelete.length === 0) {
33
48
  return 0;
34
49
  }
35
50
  const deleteList = allEpToDelete.map((func) => `\t${(0, functionsDeployHelper_1.getFunctionLabel)(func)}`).join("\n");
36
- const confirmDeletion = await (0, prompt_1.confirm)({
37
- message: "You are about to delete the following Cloud Functions:\n" + deleteList + "\n Are you sure?",
51
+ const saToDelete = Object.values(deploymentPlan)
52
+ .map((p) => p.serviceAccountToDelete)
53
+ .filter((sa) => !!sa);
54
+ let message = "You are about to delete the following Cloud Functions:\n" + deleteList;
55
+ if (saToDelete.length > 0) {
56
+ const saList = saToDelete.map((sa) => `\t${sa}`).join("\n");
57
+ message += "\n\nThe following managed service accounts will also be deleted:\n" + saList;
58
+ }
59
+ message += "\n Are you sure?";
60
+ const confirmDeletion = await prompt.confirm({
61
+ message,
38
62
  default: false,
39
63
  force: options?.force,
40
64
  nonInteractive: options?.nonInteractive,
@@ -63,7 +87,7 @@ async function deleteFunctionsByEndpointFilters(context, options) {
63
87
  projectNumber: await (0, getProjectNumber_1.getProjectNumber)({ projectId: context.projectId }),
64
88
  projectId: context.projectId,
65
89
  });
66
- const summary = await fab.applyPlan({ default: plan });
90
+ const summary = await fab.applyPlan(deploymentPlan);
67
91
  await reporter.logAndTrackDeployStats(summary);
68
92
  reporter.printErrors(summary);
69
93
  if (summary.results.some((r) => r.error)) {
@@ -72,8 +96,9 @@ async function deleteFunctionsByEndpointFilters(context, options) {
72
96
  return allEpToDelete.length;
73
97
  }
74
98
  catch (err) {
75
- throw new error_1.FirebaseError(`Failed to delete functions: ${err}`, {
76
- original: err,
99
+ const message = err instanceof Error ? err.message : String(err);
100
+ throw new error_1.FirebaseError(`Failed to delete functions: ${message}`, {
101
+ original: err instanceof Error ? err : undefined,
77
102
  exit: 1,
78
103
  });
79
104
  }
@@ -1,12 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.REQUIRED_SECURITY_APIS = void 0;
3
4
  exports.defaultServiceAccount = defaultServiceAccount;
4
5
  exports.cloudBuildEnabled = cloudBuildEnabled;
5
6
  exports.secretsAccessDelta = secretsAccessDelta;
6
7
  exports.checkSecretAccess = checkSecretAccess;
7
8
  exports.grantSecretAccess = grantSecretAccess;
9
+ exports.checkDeclarativeSecurityApisEnabled = checkDeclarativeSecurityApisEnabled;
8
10
  const clc = require("colorette");
9
- const ensureApiEnabled_1 = require("../../ensureApiEnabled");
11
+ const ensureApiEnabled = require("../../ensureApiEnabled");
10
12
  const error_1 = require("../../error");
11
13
  const utils_1 = require("../../utils");
12
14
  const secretManager_1 = require("../../gcp/secretManager");
@@ -15,6 +17,7 @@ const functional_1 = require("../../functional");
15
17
  const api_1 = require("../../api");
16
18
  const backend = require("./backend");
17
19
  const computeEngine_1 = require("../../gcp/computeEngine");
20
+ const logger_1 = require("../../logger");
18
21
  const FAQ_URL = "https://firebase.google.com/support/faq#functions-runtime";
19
22
  const metadataCallCache = new Map();
20
23
  async function defaultServiceAccount(e) {
@@ -57,7 +60,7 @@ function isPermissionError(e) {
57
60
  }
58
61
  async function cloudBuildEnabled(projectId) {
59
62
  try {
60
- await (0, ensureApiEnabled_1.ensure)(projectId, (0, api_1.cloudbuildOrigin)(), "functions");
63
+ await ensureApiEnabled.ensure(projectId, (0, api_1.cloudbuildOrigin)(), "functions");
61
64
  }
62
65
  catch (e) {
63
66
  if ((0, error_1.isBillingError)(e)) {
@@ -119,3 +122,40 @@ async function grantSecretAccess(args) {
119
122
  await (0, secretManager_1.ensureServiceAgentRole)({ name: secret, projectId }, serviceAccounts, "roles/secretmanager.secretAccessor");
120
123
  (0, utils_1.logLabeledSuccess)("functions", `ensured ${clc.bold(serviceAccounts.join(", "))} access to ${clc.bold(secret)}.`);
121
124
  }
125
+ exports.REQUIRED_SECURITY_APIS = [
126
+ "iam.googleapis.com",
127
+ "cloudresourcemanager.googleapis.com",
128
+ ];
129
+ async function checkDeclarativeSecurityApisEnabled(projectId, codebase) {
130
+ const checks = await Promise.all(exports.REQUIRED_SECURITY_APIS.map(async (api) => {
131
+ try {
132
+ return await ensureApiEnabled.check(projectId, api, "functions", true);
133
+ }
134
+ catch (err) {
135
+ const isPermissionDenied = err?.status === 403 ||
136
+ isPermissionError(err);
137
+ if (isPermissionDenied) {
138
+ logger_1.logger.debug(`Silencing permission error checking enablement for API ${api}:`, err);
139
+ return true;
140
+ }
141
+ throw err;
142
+ }
143
+ }));
144
+ const disabledApis = exports.REQUIRED_SECURITY_APIS.filter((_, idx) => !checks[idx]);
145
+ if (disabledApis.length > 0) {
146
+ const apiBulletList = disabledApis.map((api) => ` - ${clc.bold(api)}`).join("\n");
147
+ const enableCmd = clc.bold(`gcloud services enable ${disabledApis.join(" ")} --project ${projectId}`);
148
+ const consoleLinks = disabledApis
149
+ .map((api) => ` - ${api}: ${ensureApiEnabled.enableApiURI(projectId, api)}`)
150
+ .join("\n");
151
+ throw new error_1.FirebaseError(`Cannot deploy functions with declarative security in codebase "${codebase}". ` +
152
+ `The following required Google Cloud API(s) are not enabled on project ${clc.bold(projectId)}:\n` +
153
+ apiBulletList +
154
+ `\n\nDeclarative security requires these APIs to provision and configure managed service accounts and IAM roles.\n` +
155
+ `To enable them, run:\n\n` +
156
+ ` ${enableCmd}\n\n` +
157
+ `Or ask a project owner to enable them in the Google Cloud Console:\n` +
158
+ consoleLinks +
159
+ `\n`, { exit: 1 });
160
+ }
161
+ }
@@ -11,6 +11,7 @@ exports.targetCodebases = targetCodebases;
11
11
  exports.groupEndpointsByCodebase = groupEndpointsByCodebase;
12
12
  exports.isCodebaseFiltered = isCodebaseFiltered;
13
13
  exports.isEndpointFiltered = isEndpointFiltered;
14
+ exports.isCodebasePartiallyFiltered = isCodebasePartiallyFiltered;
14
15
  exports.parseDeleteFilters = parseDeleteFilters;
15
16
  exports.detectCodebaseAndIdCollisions = detectCodebaseAndIdCollisions;
16
17
  const backend = require("./backend");
@@ -140,6 +141,12 @@ function isCodebaseFiltered(codebase, filters) {
140
141
  function isEndpointFiltered(endpoint, filters) {
141
142
  return filters.some((filter) => endpointMatchesFilter(endpoint, filter));
142
143
  }
144
+ function isCodebasePartiallyFiltered(codebase, filters) {
145
+ if (!filters) {
146
+ return false;
147
+ }
148
+ return filters.some((f) => (!f.codebase || f.codebase === codebase) && !!f.idChunks && f.idChunks.length > 0);
149
+ }
143
150
  function parseDeleteFilters(filters, activeCodebases) {
144
151
  const liveCodebasesConfig = activeCodebases.map((codebase) => ({ source: "", codebase }));
145
152
  return filters.flatMap((f) => {
@@ -163,7 +163,8 @@ function canSatisfyParam(param, value) {
163
163
  }
164
164
  (0, functional_1.assertExhaustive)(param);
165
165
  }
166
- async function resolveParams(params, firebaseConfig, userEnvs, codebase, nonInteractive, force, isEmulator = false) {
166
+ async function resolveParams(opts) {
167
+ const { params, firebaseConfig, userEnvs, codebase, nonInteractive = false, force = false, isEmulator = false, } = opts;
167
168
  const paramValues = populateDefaultParams(firebaseConfig);
168
169
  const secretRefs = {};
169
170
  const [resolved, outstanding] = (0, functional_1.partition)(params, (param) => {
@@ -57,8 +57,7 @@ async function discoverSecurityDetails(codebase, want, have, projectId, filters)
57
57
  const requiredRoles = want.requiredRoles;
58
58
  const existingManagedSA = backend.findEndpoint(have, (e) => typeof e.serviceAccount === "string" && e.serviceAccount.startsWith("firebase-fn-"))?.serviceAccount ?? undefined;
59
59
  const haveRolesEtag = backend.findEndpoint(have, (e) => !!e.labels?.[exports.DECLARATIVE_SECURITY_ETAG_LABEL])?.labels?.[exports.DECLARATIVE_SECURITY_ETAG_LABEL];
60
- const isPartiallyFiltered = !!(filters &&
61
- filters.some((f) => (!f.codebase || f.codebase === codebase) && f.idChunks && f.idChunks.length > 0));
60
+ const isPartiallyFiltered = (0, functionsDeployHelper_1.isCodebasePartiallyFiltered)(codebase, filters);
62
61
  const isEnrolling = !!requiredRoles && !existingManagedSA;
63
62
  const isUnenrolling = !requiredRoles && !!existingManagedSA && !!haveRolesEtag;
64
63
  if (isPartiallyFiltered && (isEnrolling || isUnenrolling)) {
@@ -95,13 +94,13 @@ async function discoverSecurityDetails(codebase, want, have, projectId, filters)
95
94
  existingManagedSA,
96
95
  };
97
96
  }
97
+ await ensure.checkDeclarativeSecurityApisEnabled(projectId, codebase);
98
98
  let managedSA = existingManagedSA;
99
99
  if (!managedSA) {
100
100
  const saToCreate = await iam.generateManagedServiceAccountName(projectId, "firebase-fn");
101
101
  managedSA = `${saToCreate}@${projectId}.iam.gserviceaccount.com`;
102
102
  }
103
- const existingSalt = haveRolesEtag ? haveRolesEtag.split("-")[0] : undefined;
104
- const newEtag = iam.computeRolesEtag(requiredRoles, existingSalt);
103
+ const newEtag = iam.computeRolesEtag(requiredRoles);
105
104
  for (const endpoint of backend.allEndpoints(want)) {
106
105
  endpoint.serviceAccount = managedSA;
107
106
  endpoint.labels = endpoint.labels || {};