Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 4 additions & 18 deletions src/deploy/functions/build.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import * as backend from "./backend";
import * as proto from "../../gcp/proto";
import * as api from "../../.../../api";
import * as api from "../../api";
import * as params from "./params";
import { FirebaseError } from "../../error";
import { assertExhaustive, mapObject, nullsafeVisitor } from "../../functional";
import { UserEnvsOpts, writeUserEnvs } from "../../functions/env";
import { FirebaseConfig } from "./args";
import { Runtime } from "./runtimes/supported";
import { ExprParseError } from "./cel";
Expand Down Expand Up @@ -284,39 +283,26 @@
interface ResolveBackendOpts {
build: Build;
firebaseConfig: FirebaseConfig;
userEnvOpt: UserEnvsOpts;
userEnvs: Record<string, string>;
nonInteractive?: boolean;
isEmulator?: boolean;
}

/**
* Resolves user-defined parameters inside a Build, and generates a Backend.
* Returns both the Backend and the literal resolved values of any params, since
* the latter also have to be uploaded so user code can see them in process.env
* Resolves user-defined parameters inside a Build and generates a Backend.
* Callers are responsible for persisting resolved env vars.
*/
export async function resolveBackend(
opts: ResolveBackendOpts,
): Promise<{ backend: backend.Backend; envs: Record<string, params.ParamValue> }> {
let paramValues: Record<string, params.ParamValue> = {};
paramValues = await params.resolveParams(
const paramValues = await params.resolveParams(
opts.build.params,
opts.firebaseConfig,
envWithTypes(opts.build.params, opts.userEnvs),
opts.nonInteractive,
opts.isEmulator,
);

const toWrite: Record<string, string> = {};
for (const paramName of Object.keys(paramValues)) {
const paramValue = paramValues[paramName];
if (Object.prototype.hasOwnProperty.call(opts.userEnvs, paramName) || paramValue.internal) {
continue;
}
toWrite[paramName] = paramValue.toString();
}
writeUserEnvs(toWrite, opts.userEnvOpt);

return { backend: toBackend(opts.build, paramValues), envs: paramValues };
}

Expand Down Expand Up @@ -470,7 +456,7 @@
// List param, we try resolving a String param instead.
try {
regions = params.resolveList(bdEndpoint.region, paramValues);
} catch (err: any) {

Check warning on line 459 in src/deploy/functions/build.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unexpected any. Specify a different type
if (err instanceof ExprParseError) {
regions = [params.resolveString(bdEndpoint.region, paramValues)];
} else {
Expand Down
3 changes: 2 additions & 1 deletion src/deploy/functions/prepare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,12 +135,13 @@
const { backend: wantBackend, envs: resolvedEnvs } = await build.resolveBackend({
build: wantBuild,
firebaseConfig,
userEnvOpt,
userEnvs,
nonInteractive: options.nonInteractive,
isEmulator: false,
});

functionsEnv.writeResolvedParams(resolvedEnvs, userEnvs, userEnvOpt);

let hasEnvsFromParams = false;
wantBackend.environmentVariables = envs;
for (const envName of Object.keys(resolvedEnvs)) {
Expand Down Expand Up @@ -379,7 +380,7 @@
.filter(
(ep) =>
backend.isBlockingTriggered(ep) &&
AUTH_BLOCKING_EVENTS.includes(ep.blockingTrigger.eventType as any),

Check warning on line 383 in src/deploy/functions/prepare.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unexpected any. Specify a different type

Check warning on line 383 in src/deploy/functions/prepare.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe argument of type `any` assigned to a parameter of type `"providers/cloud.auth/eventTypes/user.beforeCreate" | "providers/cloud.auth/eventTypes/user.beforeSignIn" | "providers/cloud.auth/eventTypes/user.beforeSendEmail" | "providers/cloud.auth/eventTypes/user.beforeSendSms"`
) as (backend.Endpoint & backend.BlockingTriggered)[];

if (authBlockingEndpoints.length === 0) {
Expand Down Expand Up @@ -495,7 +496,7 @@
// Genkit almost always requires an API key, so warn if the customer is about to deploy
// a function and doesn't have one. To avoid repetitive nagging, only warn on the first
// deploy of the function.
export async function warnIfNewGenkitFunctionIsMissingSecrets(

Check warning on line 499 in src/deploy/functions/prepare.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing JSDoc comment

Check warning on line 499 in src/deploy/functions/prepare.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing return type on function
have: backend.Backend,
want: backend.Backend,
options: DeployOptions,
Expand Down Expand Up @@ -529,7 +530,7 @@

// Enable required APIs. This may come implicitly from triggers (e.g. scheduled triggers
// require cloudscheduler and, in v1, require pub/sub), use of features (secrets), or explicit dependencies.
export async function ensureAllRequiredAPIsEnabled(

Check warning on line 533 in src/deploy/functions/prepare.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing JSDoc comment
projectNumber: string,
wantBackend: backend.Backend,
): Promise<void> {
Expand Down
2 changes: 1 addition & 1 deletion src/deploy/functions/runtimes/discovery/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import { ChildProcess } from "child_process";

import { logger } from "../../../../logger";
import * as api from "../../.../../../../api";
import * as api from "../../../../api";
import * as build from "../../build";
import { Runtime } from "../supported";
import * as v1alpha1 from "./v1alpha1";
Expand All @@ -13,7 +13,7 @@

const TIMEOUT_OVERRIDE_ENV_VAR = "FUNCTIONS_DISCOVERY_TIMEOUT";

export function getFunctionDiscoveryTimeout(): number {

Check warning on line 16 in src/deploy/functions/runtimes/discovery/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing JSDoc comment
return +(process.env[TIMEOUT_OVERRIDE_ENV_VAR] || 0) * 1000; /* ms */
}

Expand All @@ -21,16 +21,16 @@
* Converts the YAML retrieved from discovery into a Build object for param interpolation.
*/
export function yamlToBuild(
yaml: any,

Check warning on line 24 in src/deploy/functions/runtimes/discovery/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unexpected any. Specify a different type
project: string,
region: string,
runtime: Runtime,
): build.Build {
try {
if (!yaml.specVersion) {

Check warning on line 30 in src/deploy/functions/runtimes/discovery/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe member access .specVersion on an `any` value
throw new FirebaseError("Expect manifest yaml to specify a version number");
}
if (yaml.specVersion === "v1alpha1") {

Check warning on line 33 in src/deploy/functions/runtimes/discovery/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe member access .specVersion on an `any` value
return v1alpha1.buildFromV1Alpha1(yaml, project, region, runtime);
}
throw new FirebaseError(
Expand Down
1 change: 0 additions & 1 deletion src/deploy/functions/runtimes/node/parseTriggers.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ async function resolveBackend(bd: build.Build): Promise<backend.Backend> {
storageBucket: "foo.appspot.com",
databaseURL: "https://foo.firebaseio.com",
},
userEnvOpt: { functionsSource: "", projectId: "PROJECT" },
userEnvs: {},
})
).backend;
Expand Down
3 changes: 2 additions & 1 deletion src/emulator/functionsEmulator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -580,11 +580,12 @@ export class FunctionsEmulator implements EmulatorInstance {
const resolution = await resolveBackend({
build: discoveredBuild,
firebaseConfig: JSON.parse(firebaseConfig),
userEnvOpt,
userEnvs,
nonInteractive: false,
isEmulator: true,
});

functionsEnv.writeResolvedParams(resolution.envs, userEnvs, userEnvOpt);
const discoveredBackend = resolution.backend;
const endpoints = backend.allEndpoints(discoveredBackend);
prepareEndpoints(endpoints);
Expand Down
84 changes: 84 additions & 0 deletions src/functions/env.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { expect } from "chai";

import * as env from "./env";
import { FirebaseError } from "../error";
import { ParamValue } from "../deploy/functions/params";

describe("functions/env", () => {
describe("parse", () => {
Expand Down Expand Up @@ -758,4 +759,87 @@ FOO=foo
expect(env.parseStrict(input)).to.deep.equal(expected);
});
});

describe("writeResolvedParams", () => {
let tmpdir: string;

beforeEach(() => {
tmpdir = fs.mkdtempSync(path.join(os.tmpdir(), "firebase-functions-test-"));
});

afterEach(() => {
rmSync(tmpdir, { recursive: true, force: true });
});

it("should write only new, non-internal params", () => {
const resolvedEnvs = {
EXISTING_PARAM: new ParamValue("existing", false, { string: true }),
NEW_PARAM: new ParamValue("new_value", false, { string: true }),
INTERNAL_PARAM: new ParamValue("internal", true, { string: true }),
};
const userEnvs = { EXISTING_PARAM: "old_value" };
const userEnvOpt = {
projectId: "test-project",
functionsSource: tmpdir,
};

env.writeResolvedParams(resolvedEnvs, userEnvs, userEnvOpt);

const writtenContent = fs.readFileSync(path.join(tmpdir, ".env.test-project"), "utf-8");
expect(writtenContent).to.include("NEW_PARAM=new_value");
expect(writtenContent).not.to.include("EXISTING_PARAM");
expect(writtenContent).not.to.include("INTERNAL_PARAM");
});

it("should not create file when no params to write", () => {
const resolvedEnvs = {
EXISTING_PARAM: new ParamValue("existing", false, { string: true }),
INTERNAL_PARAM: new ParamValue("internal", true, { string: true }),
};
const userEnvs = { EXISTING_PARAM: "old_value" };
const userEnvOpt = {
projectId: "test-project",
functionsSource: tmpdir,
};

env.writeResolvedParams(resolvedEnvs, userEnvs, userEnvOpt);

const envFile = path.join(tmpdir, ".env.test-project");
expect(fs.existsSync(envFile)).to.be.false;
});

it("should write to .env.local for emulator", () => {
const resolvedEnvs = {
NEW_PARAM: new ParamValue("emulator_value", false, { string: true }),
};
const userEnvs = {};
const userEnvOpt = {
projectId: "test-project",
functionsSource: tmpdir,
isEmulator: true,
};

env.writeResolvedParams(resolvedEnvs, userEnvs, userEnvOpt);

const writtenContent = fs.readFileSync(path.join(tmpdir, ".env.local"), "utf-8");
expect(writtenContent).to.include("NEW_PARAM=emulator_value");
expect(fs.existsSync(path.join(tmpdir, ".env.test-project"))).to.be.false;
});

it("should handle params with special characters in values", () => {
const resolvedEnvs = {
NEW_PARAM: new ParamValue("value with\nnewline", false, { string: true }),
};
const userEnvs = {};
const userEnvOpt = {
projectId: "test-project",
functionsSource: tmpdir,
};

env.writeResolvedParams(resolvedEnvs, userEnvs, userEnvOpt);

const writtenContent = fs.readFileSync(path.join(tmpdir, ".env.test-project"), "utf-8");
expect(writtenContent).to.include('NEW_PARAM="value with\\nnewline"');
});
});
});
22 changes: 22 additions & 0 deletions src/functions/env.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as clc from "colorette";
import * as fs from "fs";
import * as path from "path";
import { ParamValue } from "../deploy/functions/params";

import { FirebaseError } from "../error";
import { logger } from "../logger";
Expand Down Expand Up @@ -414,3 +415,24 @@ export function loadFirebaseEnvs(
GCLOUD_PROJECT: projectId,
};
}

/**
* Writes newly resolved params to the appropriate .env file.
* Skips internal params and params that already exist in userEnvs.
*/
export function writeResolvedParams(
resolvedEnvs: Readonly<Record<string, ParamValue>>,
userEnvs: Readonly<Record<string, string>>,
userEnvOpt: UserEnvsOpts,
): void {
const toWrite: Record<string, string> = {};

for (const paramName of Object.keys(resolvedEnvs)) {
const paramValue = resolvedEnvs[paramName];
if (!paramValue.internal && !Object.prototype.hasOwnProperty.call(userEnvs, paramName)) {
toWrite[paramName] = paramValue.toString();
}
}

writeUserEnvs(toWrite, userEnvOpt);
}
Loading