Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
23 changes: 5 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,42 +283,30 @@
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 };
}


Check failure on line 309 in src/deploy/functions/build.ts

View workflow job for this annotation

GitHub Actions / unit (20)

Delete `⏎`

Check failure on line 309 in src/deploy/functions/build.ts

View workflow job for this annotation

GitHub Actions / unit (22)

Delete `⏎`

Check failure on line 309 in src/deploy/functions/build.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Delete `⏎`

Check failure on line 309 in src/deploy/functions/build.ts

View workflow job for this annotation

GitHub Actions / unit (22)

Delete `⏎`
// Exported for testing
/**
*
Expand Down Expand Up @@ -470,7 +457,7 @@
// List param, we try resolving a String param instead.
try {
regions = params.resolveList(bdEndpoint.region, paramValues);
} catch (err: any) {

Check warning on line 460 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.writeResolvedEnvsToFile(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.writeResolvedEnvsToFile(resolution.envs, userEnvs, userEnvOpt);
const discoveredBackend = resolution.backend;
const endpoints = backend.allEndpoints(discoveredBackend);
prepareEndpoints(endpoints);
Expand Down
87 changes: 87 additions & 0 deletions src/functions/env.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -758,4 +758,91 @@
expect(env.parseStrict(input)).to.deep.equal(expected);
});
});

describe("writeResolvedEnvsToFile", () => {
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: { internal: false, toString: () => "existing" },
NEW_PARAM: { internal: false, toString: () => "new_value" },
INTERNAL_PARAM: { internal: true, toString: () => "internal" },
};
const userEnvs = { EXISTING_PARAM: "old_value" };
const userEnvOpt = {
projectId: "test-project",
functionsSource: tmpdir,
};

env.writeResolvedEnvsToFile(resolvedEnvs, userEnvs, userEnvOpt);

// Check the written file
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: { internal: false, toString: () => "existing" },
INTERNAL_PARAM: { internal: true, toString: () => "internal" },
};
const userEnvs = { EXISTING_PARAM: "old_value" };
const userEnvOpt = {
projectId: "test-project",
functionsSource: tmpdir,
};

env.writeResolvedEnvsToFile(resolvedEnvs, userEnvs, userEnvOpt);

// Check that no file was created
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: { internal: false, toString: () => "emulator_value" },
};
const userEnvs = {};
const userEnvOpt = {
projectId: "test-project",
functionsSource: tmpdir,
isEmulator: true,
};

env.writeResolvedEnvsToFile(resolvedEnvs, userEnvs, userEnvOpt);

// Check the written file is .env.local
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: { internal: false, toString: () => "value with\nnewline" },
};
const userEnvs = {};
const userEnvOpt = {
projectId: "test-project",
functionsSource: tmpdir,
};

env.writeResolvedEnvsToFile(resolvedEnvs, userEnvs, userEnvOpt);

// Check the written file handles special chars correctly
const writtenContent = fs.readFileSync(path.join(tmpdir, ".env.test-project"), "utf-8");
expect(writtenContent).to.include("NEW_PARAM=\"value with\\nnewline\"");

Check failure on line 845 in src/functions/env.spec.ts

View workflow job for this annotation

GitHub Actions / unit (20)

Replace `"NEW_PARAM=\"value·with\\nnewline\""` with `'NEW_PARAM="value·with\\nnewline"'`

Check failure on line 845 in src/functions/env.spec.ts

View workflow job for this annotation

GitHub Actions / unit (22)

Replace `"NEW_PARAM=\"value·with\\nnewline\""` with `'NEW_PARAM="value·with\\nnewline"'`

Check failure on line 845 in src/functions/env.spec.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Replace `"NEW_PARAM=\"value·with\\nnewline\""` with `'NEW_PARAM="value·with\\nnewline"'`

Check failure on line 845 in src/functions/env.spec.ts

View workflow job for this annotation

GitHub Actions / unit (22)

Replace `"NEW_PARAM=\"value·with\\nnewline\""` with `'NEW_PARAM="value·with\\nnewline"'`
});
});
});
23 changes: 23 additions & 0 deletions src/functions/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -414,3 +414,26 @@
GCLOUD_PROJECT: projectId,
};
}

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

Check failure on line 428 in src/functions/env.ts

View workflow job for this annotation

GitHub Actions / unit (20)

Delete `··`

Check failure on line 428 in src/functions/env.ts

View workflow job for this annotation

GitHub Actions / unit (22)

Delete `··`

Check failure on line 428 in src/functions/env.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Delete `··`

Check failure on line 428 in src/functions/env.ts

View workflow job for this annotation

GitHub Actions / unit (22)

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

Check failure on line 435 in src/functions/env.ts

View workflow job for this annotation

GitHub Actions / unit (20)

Delete `··`

Check failure on line 435 in src/functions/env.ts

View workflow job for this annotation

GitHub Actions / unit (22)

Delete `··`

Check failure on line 435 in src/functions/env.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Delete `··`

Check failure on line 435 in src/functions/env.ts

View workflow job for this annotation

GitHub Actions / unit (22)

Delete `··`
if (Object.keys(toWrite).length > 0) {
writeUserEnvs(toWrite, userEnvOpt);
}
}
Loading