Skip to content

feat: Add validation for function prefixes and source/prefix pairs #8911

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
3 changes: 3 additions & 0 deletions schema/firebase-config.json
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,9 @@
}
]
},
"prefix": {
"type": "string"
},
"runtime": {
"enum": [
"nodejs18",
Expand Down
42 changes: 42 additions & 0 deletions scripts/emulator-tests/functionsEmulator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import * as secretManager from "../../src/gcp/secretManager";

if ((process.env.DEBUG || "").toLowerCase().includes("spec")) {
const dropLogLevels = (info: logform.TransformableInfo) => info.message;

Check warning on line 22 in scripts/emulator-tests/functionsEmulator.spec.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing return type on function
logger.add(
new winston.transports.Console({
level: "debug",
Expand Down Expand Up @@ -49,7 +49,7 @@
// bin: path.join(MODULE_ROOT, "node_modules/.bin/ts-node"),
};

async function setupEnvFiles(envs: Record<string, string>) {

Check warning on line 52 in scripts/emulator-tests/functionsEmulator.spec.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing return type on function
const envFiles: string[] = [];
for (const [filename, data] of Object.entries(envs)) {
const envPath = path.join(FUNCTIONS_DIR, filename);
Expand Down Expand Up @@ -760,6 +760,48 @@
}).timeout(TIMEOUT_MED);
});

it("should support multiple codebases with the same source and apply prefixes", async () => {
const backend1: EmulatableBackend = {
...TEST_BACKEND,
codebase: "one",
prefix: "prefix-one",
};
const backend2: EmulatableBackend = {
...TEST_BACKEND,
codebase: "two",
prefix: "prefix-two",
};

emu = new FunctionsEmulator({
projectId: TEST_PROJECT_ID,
projectDir: MODULE_ROOT,
emulatableBackends: [backend1, backend2],
verbosity: "QUIET",
debugPort: false,
});

await writeSource(() => {
return {
functionId: require("firebase-functions").https.onRequest(
(req: express.Request, res: express.Response) => {
res.json({ path: req.path });
},
),
};
});

await emu.start();
await emu.connect();

await supertest(emu.createHubServer())
.get(`/${TEST_PROJECT_ID}/us-central1/prefix-one-functionId`)
.expect(200);

await supertest(emu.createHubServer())
.get(`/${TEST_PROJECT_ID}/us-central1/prefix-two-functionId`)
.expect(200);
});

describe("user-defined environment variables", () => {
let cleanup: (() => Promise<void>) | undefined;

Expand Down
21 changes: 21 additions & 0 deletions src/deploy/functions/build.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,27 @@ describe("toBackend", () => {
expect(endpointDef.func.serviceAccount).to.equal("service-account-1@");
}
});

it("should apply the prefix to the function name", () => {
const desiredBuild: build.Build = build.of({
func: {
platform: "gcfv1",
region: ["us-central1"],
project: "project",
runtime: "nodejs16",
entryPoint: "func",
httpsTrigger: {},
},
});
const backend = build.toBackend(desiredBuild, {}, "my-prefix");
expect(Object.keys(backend.endpoints).length).to.equal(1);
const regionalEndpoints = Object.values(backend.endpoints)[0];
const endpoint = Object.values(regionalEndpoints)[0];
expect(endpoint).to.not.equal(undefined);
if (endpoint) {
expect(endpoint.id).to.equal("my-prefix-func");
}
});
});

describe("envWithType", () => {
Expand Down
6 changes: 4 additions & 2 deletions src/deploy/functions/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,7 @@ interface ResolveBackendOpts {
userEnvs: Record<string, string>;
nonInteractive?: boolean;
isEmulator?: boolean;
prefix?: string;
}

/**
Expand Down Expand Up @@ -316,7 +317,7 @@ export async function resolveBackend(
}
writeUserEnvs(toWrite, opts.userEnvOpt);

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

// Exported for testing
Expand Down Expand Up @@ -446,6 +447,7 @@ class Resolver {
export function toBackend(
build: Build,
paramValues: Record<string, params.ParamValue>,
prefix?: string,
): backend.Backend {
const r = new Resolver(paramValues);
const bkEndpoints: Array<backend.Endpoint> = [];
Expand Down Expand Up @@ -481,7 +483,7 @@ export function toBackend(
throw new FirebaseError("platform can't be undefined");
}
const bkEndpoint: backend.Endpoint = {
id: endpointId,
id: prefix ? `${prefix}-${endpointId}` : endpointId,
project: bdEndpoint.project,
region: region,
entryPoint: bdEndpoint.entryPoint,
Expand Down
1 change: 1 addition & 0 deletions src/deploy/functions/prepare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ export async function prepare(
userEnvs,
nonInteractive: options.nonInteractive,
isEmulator: false,
prefix: config.prefix,
});

let hasEnvsFromParams = false;
Expand Down
1 change: 1 addition & 0 deletions src/emulator/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,7 @@ export async function startAll(
functionsDir,
runtime,
codebase: cfg.codebase,
prefix: cfg.prefix,
env: {
...options.extDevEnv,
},
Expand Down
2 changes: 2 additions & 0 deletions src/emulator/functionsEmulator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ export interface EmulatableBackend {
env: Record<string, string>;
secretEnv: backend.SecretEnvVar[];
codebase: string;
prefix?: string;
predefinedTriggers?: ParsedTriggerDefinition[];
runtime?: Runtime;
bin?: string;
Expand Down Expand Up @@ -570,6 +571,7 @@ export class FunctionsEmulator implements EmulatorInstance {
userEnvs,
nonInteractive: false,
isEmulator: true,
prefix: emulatableBackend.prefix,
});
const discoveredBackend = resolution.backend;
const endpoints = backend.allEndpoints(discoveredBackend);
Expand Down
1 change: 1 addition & 0 deletions src/firebaseConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ export type FunctionConfig = {
ignore?: string[];
runtime?: ActiveRuntime;
codebase?: string;
prefix?: string;
} & Deployable;

export type FunctionsConfig = FunctionConfig | FunctionConfig[];
Expand Down
79 changes: 68 additions & 11 deletions src/functions/projectConfig.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,41 @@ describe("projectConfig", () => {
);
});

it("fails validation given config w/ duplicate source", () => {
expect(() =>
projectConfig.validate([TEST_CONFIG_0, { ...TEST_CONFIG_0, codebase: "unique-codebase" }]),
).to.throw(FirebaseError, /source must be unique/);
it("passes validation for multi-instance config with same source", () => {
const config = [
{ source: "foo", codebase: "bar" },
{ source: "foo", codebase: "baz", prefix: "prefix-two" },
];
expect(projectConfig.validate(config as projectConfig.NormalizedConfig)).to.deep.equal(
config,
);
});

it("passes validation for multi-instance config with one missing codebase", () => {
const config = [{ source: "foo", codebase: "bar", prefix: "bar-prefix" }, { source: "foo" }];
const expected = [
{ source: "foo", codebase: "bar", prefix: "bar-prefix" },
{ source: "foo", codebase: "default" },
];
expect(projectConfig.validate(config as projectConfig.NormalizedConfig)).to.deep.equal(
expected,
);
});

it("fails validation for multi-instance config with missing codebase and a default codebase", () => {
const config = [{ source: "foo", codebase: "default" }, { source: "foo" }];
expect(() => projectConfig.validate(config as projectConfig.NormalizedConfig)).to.throw(
FirebaseError,
/functions.codebase must be unique but 'default' was used more than once./,
);
});

it("fails validation for multi-instance config with multiple missing codebases", () => {
const config = [{ source: "foo" }, { source: "foo" }];
expect(() => projectConfig.validate(config as projectConfig.NormalizedConfig)).to.throw(
FirebaseError,
/functions.codebase must be unique but 'default' was used more than once./,
);
});

it("fails validation given codebase name with capital letters", () => {
Expand All @@ -72,6 +103,39 @@ describe("projectConfig", () => {
]),
).to.throw(FirebaseError, /Invalid codebase name/);
});

it("fails validation given prefix with invalid characters", () => {
expect(() => projectConfig.validate([{ ...TEST_CONFIG_0, prefix: "abc.efg" }])).to.throw(
FirebaseError,
/Invalid prefix/,
);
});

it("fails validation given prefix with capital letters", () => {
expect(() => projectConfig.validate([{ ...TEST_CONFIG_0, prefix: "ABC" }])).to.throw(
FirebaseError,
/Invalid prefix/,
);
});

it("fails validation given a duplicate source/prefix pair", () => {
const config = [
{ source: "foo", codebase: "bar", prefix: "a" },
{ source: "foo", codebase: "baz", prefix: "a" },
];
expect(() => projectConfig.validate(config as projectConfig.NormalizedConfig)).to.throw(
FirebaseError,
/More than one functions config specifies the same source directory/,
);
});

it("should allow a single function in an array to have a default codebase", () => {
const config = [{ source: "foo" }];
const expected = [{ source: "foo", codebase: "default" }];
expect(projectConfig.validate(config as projectConfig.NormalizedConfig)).to.deep.equal(
expected,
);
});
});

describe("normalizeAndValidate", () => {
Expand Down Expand Up @@ -104,13 +168,6 @@ describe("projectConfig", () => {
);
});

it("fails validation given config w/ duplicate source", () => {
expect(() => projectConfig.normalizeAndValidate([TEST_CONFIG_0, TEST_CONFIG_0])).to.throw(
FirebaseError,
/functions.source must be unique/,
);
});

it("fails validation given config w/ duplicate codebase", () => {
expect(() =>
projectConfig.normalizeAndValidate([
Expand Down
36 changes: 33 additions & 3 deletions src/functions/projectConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { FirebaseError } from "../error";

export type NormalizedConfig = [FunctionConfig, ...FunctionConfig[]];
export type ValidatedSingle = FunctionConfig & { source: string; codebase: string };
export type ValidatedSingle = FunctionConfig & { source:string; codebase: string };

Check failure on line 5 in src/functions/projectConfig.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Insert `·`

Check failure on line 5 in src/functions/projectConfig.ts

View workflow job for this annotation

GitHub Actions / unit (22)

Insert `·`

Check failure on line 5 in src/functions/projectConfig.ts

View workflow job for this annotation

GitHub Actions / unit (20)

Insert `·`

Check failure on line 5 in src/functions/projectConfig.ts

View workflow job for this annotation

GitHub Actions / unit (22)

Insert `·`
export type ValidatedConfig = [ValidatedSingle, ...ValidatedSingle[]];

export const DEFAULT_CODEBASE = "default";
Expand Down Expand Up @@ -37,6 +37,20 @@
}
}

/**
* Check that the prefix contains only allowed characters.
*/
export function validatePrefix(prefix: string): void {
if (prefix.length > 30) {
throw new FirebaseError("Invalid prefix. Prefix must be 30 characters or less.");
}
if (!/^[a-z0-9-]+$/.test(prefix)) {
throw new FirebaseError(
"Invalid prefix. Prefix can contain only lowercase letters, numeric characters, and dashes.",
);
}
}

function validateSingle(config: FunctionConfig): ValidatedSingle {
if (!config.source) {
throw new FirebaseError("codebase source must be specified");
Expand All @@ -45,6 +59,9 @@
config.codebase = DEFAULT_CODEBASE;
}
validateCodebase(config.codebase);
if (config.prefix) {
validatePrefix(config.prefix);
}

return { ...config, source: config.source, codebase: config.codebase };
}
Expand Down Expand Up @@ -72,13 +89,26 @@
}
}

function assertUniqueSourcePrefixPair(config: ValidatedConfig): void {
const sourcePrefixPairs = new Set<string>();
for (const c of config) {
const key = `${c.source || ""}-${c.prefix || ""}`;
if (sourcePrefixPairs.has(key)) {
throw new FirebaseError(
`More than one functions config specifies the same source directory ('${c.source}') and function name prefix ('${c.prefix || ""}').`,
);
}
sourcePrefixPairs.add(key);
}
}

/**
* Validate functions config.
*/
export function validate(config: NormalizedConfig): ValidatedConfig {
const validated = config.map((cfg) => validateSingle(cfg)) as ValidatedConfig;
assertUnique(validated, "source");
assertUnique(validated, "codebase");
assertUniqueSourcePrefixPair(validated);
return validated;
}

Expand All @@ -100,4 +130,4 @@
throw new FirebaseError(`No functions config found for codebase ${codebase}`);
}
return codebaseCfg;
}
}

Check failure on line 133 in src/functions/projectConfig.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Insert `⏎`

Check failure on line 133 in src/functions/projectConfig.ts

View workflow job for this annotation

GitHub Actions / unit (22)

Insert `⏎`

Check failure on line 133 in src/functions/projectConfig.ts

View workflow job for this annotation

GitHub Actions / unit (20)

Insert `⏎`

Check failure on line 133 in src/functions/projectConfig.ts

View workflow job for this annotation

GitHub Actions / unit (22)

Insert `⏎`
Loading