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
59 changes: 59 additions & 0 deletions spec/params/params.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,34 @@ describe("Params value extraction", () => {
expect(trueExpr.thenElse(twentytwo, 0).value()).to.equal(22);
expect(falseExpr.thenElse(1, twentytwo).value()).to.equal(22);
});

it("can select between RegExp/RegExp[] literals via a ternary expression", () => {
const localPattern = /^http:\/\/localhost:8080$/;
const prodPattern = /^https:\/\/example\.com$/;
const trueExpr = params.defineString("A_STRING").equals(params.defineString("SAME_STRING"));
const falseExpr = params.defineInt("AN_INT").equals(params.defineInt("DIFF_INT"));

expect(trueExpr.thenElse(localPattern, prodPattern).value()).to.equal(localPattern);
expect(falseExpr.thenElse(localPattern, prodPattern).value()).to.equal(prodPattern);

const localPatterns = [localPattern];
const prodPatterns = [prodPattern];
expect(trueExpr.thenElse(localPatterns, prodPatterns).value()).to.equal(localPatterns);
expect(falseExpr.thenElse(localPatterns, prodPatterns).value()).to.equal(prodPatterns);

// Nested thenElse, mirroring a boolean-param-selected CORS origin config.
// The outer test is false so that the nested expression is the one resolved.
const otherPatterns = [/^https:\/\/other\.example\.com$/];
const stagingExpr = params.defineBoolean("TRUE");
expect(
falseExpr.thenElse(localPatterns, stagingExpr.thenElse(prodPatterns, otherPatterns)).value()
).to.equal(prodPatterns);
expect(
falseExpr
.thenElse(localPatterns, stagingExpr.equals(false).thenElse(prodPatterns, otherPatterns))
.value()
).to.equal(otherPatterns);
});
});

describe("defineJsonSecret", () => {
Expand Down Expand Up @@ -457,6 +485,37 @@ describe("Params as CEL", () => {
cmpExpr.thenElse(params.defineString("FOO"), params.defineString("BAR")).toCEL()
).to.equal("{{ params.A != params.B ? params.FOO : params.BAR }}");
});

it("represents RegExp array branches as their string form, not '{}'", () => {
const booleanExpr = params.defineBoolean("BOOL");
const localPattern = /^http:\/\/localhost$/;
const prodPattern = /^https:\/\/example\.com$/;
const cel = booleanExpr.thenElse([localPattern], [prodPattern]).toCEL();

// Regression check: JSON.stringify(regexArray) alone would render each RegExp
// as "{}", silently dropping the pattern.
expect(cel).to.not.include("{}");
expect(cel).to.equal(
`{{ params.BOOL ? ${JSON.stringify([localPattern.toString()])} : ${JSON.stringify([
prodPattern.toString(),
])} }}`
);
});

it("represents a bare RegExp branch as a quoted string form, not unquoted source", () => {
const booleanExpr = params.defineBoolean("BOOL");
const localPattern = /^http:\/\/localhost$/;
const prodPattern = /^https:\/\/example\.com$/;
const cel = booleanExpr.thenElse(localPattern, prodPattern).toCEL();

// Regression check: arg.toString() alone would render the RegExp as an
// unquoted /pattern/, which is not a valid CEL string literal.
expect(cel).to.equal(
`{{ params.BOOL ? ${JSON.stringify(localPattern.toString())} : ${JSON.stringify(
prodPattern.toString()
)} }}`
);
});
});

describe("expr template tag", () => {
Expand Down
83 changes: 83 additions & 0 deletions spec/v2/providers/https.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,89 @@ describe("onRequest", () => {
}
});

it("should allow a RegExp[] chosen dynamically via a ternary expression", async () => {
const isStaging = defineBoolean("IS_STAGING");
const localPattern = /^http:\/\/localhost:8080$/;
const stagingPattern = /^https:\/\/staging\.example\.com$/;

try {
process.env.IS_STAGING = "true";
const func = https.onRequest(
{
cors: isStaging.equals(true).thenElse([stagingPattern], [localPattern]),
},
(req, res) => {
res.send("42");
}
);
const req = request({
headers: {
referrer: "https://staging.example.com",
"content-type": "application/json",
origin: "https://staging.example.com",
},
method: "OPTIONS",
});

const response = await runHandler(func, req);

expect(response.status).to.equal(204);
expect(response.headers).to.deep.equal({
"Access-Control-Allow-Origin": "https://staging.example.com",
"Access-Control-Allow-Methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"Content-Length": "0",
Vary: "Origin, Access-Control-Request-Headers",
});
} finally {
delete process.env.IS_STAGING;
clearParams();
}
});

it("should resolve the other RegExp[] branch when the ternary expression is false", async () => {
const isStaging = defineBoolean("IS_STAGING");
const localPattern = /^http:\/\/localhost:8080$/;
const stagingPattern = /^https:\/\/staging\.example\.com$/;

try {
process.env.IS_STAGING = "false";
const func = https.onRequest(
{
cors: isStaging.equals(true).thenElse([stagingPattern], [localPattern]),
},
(req, res) => {
res.send("42");
}
);
const preflight = (origin: string) =>
request({
headers: {
referrer: origin,
"content-type": "application/json",
origin,
},
method: "OPTIONS",
});

const allowed = await runHandler(func, preflight("http://localhost:8080"));

expect(allowed.status).to.equal(204);
expect(allowed.headers).to.deep.equal({
"Access-Control-Allow-Origin": "http://localhost:8080",
"Access-Control-Allow-Methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"Content-Length": "0",
Vary: "Origin, Access-Control-Request-Headers",
});

const denied = await runHandler(func, preflight("https://staging.example.com"));

expect(denied.headers).to.not.have.property("Access-Control-Allow-Origin");
} finally {
delete process.env.IS_STAGING;
clearParams();
}
});

it("should add CORS headers if debug feature is enabled", async () => {
sinon.stub(debug, "isDebugFeatureEnabled").withArgs("enableCors").returns(true);

Expand Down
2 changes: 2 additions & 0 deletions src/common/providers/https.ts
Original file line number Diff line number Diff line change
Expand Up @@ -715,6 +715,8 @@ export type CorsOption =
| string
| Expression<string>
| Expression<string[]>
| Expression<RegExp>
| Expression<Array<string | RegExp>>
| boolean
| RegExp
| Array<string | RegExp>;
Expand Down
1 change: 1 addition & 0 deletions src/params/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export type {
SelectInput,
SelectOptions,
MultiSelectInput,
ExpressionValue,
Param,
SecretParam,
JsonSecretParam,
Expand Down
43 changes: 27 additions & 16 deletions src/params/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,26 @@ import * as logger from "../logger";

const EXPRESSION_TAG = Symbol.for("firebase-functions:Expression:Tag");

/**
* The types an `Expression` can resolve to. `string`, `number`, `boolean` and
* `string[]` cover the values a param itself can hold; `RegExp` and
* `Array<string | RegExp>` are additionally allowed so that expressions can
* select between literals for options that accept them, such as `cors`.
*/
export type ExpressionValue =
| string
| number
| boolean
| string[]
| RegExp
| Array<string | RegExp>;

/*
* A CEL expression which can be evaluated during function deployment, and
* resolved to a value of the generic type parameter: i.e, you can pass
* an Expression<number> as the value of an option that normally accepts numbers.
*/
export abstract class Expression<T extends string | number | boolean | string[]> {
export abstract class Expression<T extends ExpressionValue> {
/**
* Handle the "Dual-Package Hazard" .
*
Expand Down Expand Up @@ -144,13 +158,11 @@ export class TransformedStringExpression extends Expression<string> {
}
}

export function valueOf<T extends string | number | boolean | string[]>(arg: T | Expression<T>): T {
export function valueOf<T extends ExpressionValue>(arg: T | Expression<T>): T {
return arg instanceof Expression ? arg.runtimeValue() : arg;
}

export function celOf<T extends string | number | boolean | string[]>(
arg: T | Expression<T>
): T | string {
export function celOf<T extends ExpressionValue>(arg: T | Expression<T>): T | string {
return arg instanceof Expression ? arg.toCEL() : arg;
}

Expand All @@ -171,13 +183,17 @@ export function transform(
* - Arrays are represented as []-delimited, parsable JSON
* - Numbers and booleans are not quoted explicitly
*/
function refOf<T extends string | number | boolean | string[]>(arg: T | Expression<T>): string {
function refOf<T extends ExpressionValue>(arg: T | Expression<T>): string {
if (arg instanceof Expression) {
return arg.toString();
} else if (typeof arg === "string") {
return `"${arg}"`;
} else if (arg instanceof RegExp) {
return JSON.stringify(arg.toString());
} else if (Array.isArray(arg)) {
Comment thread
IzaakGough marked this conversation as resolved.
return JSON.stringify(arg);
// RegExp has no useful JSON representation (JSON.stringify(/foo/) === "{}"),
// so fall back to its string form instead of silently dropping the pattern.
return JSON.stringify(arg.map((item) => (item instanceof RegExp ? item.toString() : item)));
} else {
return arg.toString();
}
Expand All @@ -186,9 +202,7 @@ function refOf<T extends string | number | boolean | string[]>(arg: T | Expressi
/**
* A CEL expression corresponding to a ternary operator, e.g {{ cond ? ifTrue : ifFalse }}
*/
export class TernaryExpression<
T extends string | number | boolean | string[]
> extends Expression<T> {
export class TernaryExpression<T extends ExpressionValue> extends Expression<T> {
constructor(
private readonly test: Expression<boolean>,
private readonly ifTrue: T | Expression<T>,
Expand Down Expand Up @@ -263,7 +277,7 @@ export class CompareExpression<
}

/** Returns a `TernaryExpression` which can resolve to one of two values, based on the resolution of this comparison. */
thenElse<retT extends string | number | boolean | string[]>(
thenElse<retT extends ExpressionValue>(
ifTrue: retT | Expression<retT>,
ifFalse: retT | Expression<retT>
) {
Expand Down Expand Up @@ -719,14 +733,11 @@ export class BooleanParam extends Param<boolean> {
}

/** @deprecated */
then<T extends string | number | boolean>(ifTrue: T | Expression<T>, ifFalse: T | Expression<T>) {
then<T extends ExpressionValue>(ifTrue: T | Expression<T>, ifFalse: T | Expression<T>) {
return this.thenElse(ifTrue, ifFalse);
}

thenElse<T extends string | number | boolean>(
ifTrue: T | Expression<T>,
ifFalse: T | Expression<T>
) {
thenElse<T extends ExpressionValue>(ifTrue: T | Expression<T>, ifFalse: T | Expression<T>) {
return new TernaryExpression(this, ifTrue, ifFalse);
}
}
Expand Down
8 changes: 1 addition & 7 deletions src/v2/providers/https.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,7 @@ export interface HttpsOptions extends Omit<GlobalOptions, "region" | "enforceApp
* If this is an `Array`, allows requests from domains matching at least one entry of the array.
* Defaults to true for {@link https.CallableFunction} and false otherwise.
*/
cors?:
| string
| Expression<string>
| Expression<string[]>
| boolean
| RegExp
| Array<string | RegExp>;
cors?: CorsOption;

/**
* Amount of memory to allocate to a function.
Expand Down
Loading