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
39 changes: 39 additions & 0 deletions spec/params/params.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,29 @@ 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.
const stagingExpr = params.defineBoolean("TRUE");
const nested = trueExpr.thenElse(
localPatterns,
stagingExpr.thenElse(prodPatterns, [/^https:\/\/other\.example\.com$/])
);
expect(nested.value()).to.equal(localPatterns);
});
});

describe("defineJsonSecret", () => {
Expand Down Expand Up @@ -457,6 +480,22 @@ 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(),
])} }}`
);
});
});

describe("expr template tag", () => {
Expand Down
39 changes: 39 additions & 0 deletions spec/v2/providers/https.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,45 @@ 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 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
33 changes: 22 additions & 11 deletions src/params/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ const EXPRESSION_TAG = Symbol.for("firebase-functions:Expression:Tag");
* 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 string | number | boolean | string[] | RegExp | Array<string | RegExp>
> {
/**
* Handle the "Dual-Package Hazard" .
*
Expand Down Expand Up @@ -144,13 +146,15 @@ 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 string | number | boolean | string[] | RegExp | Array<string | RegExp>
>(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 string | number | boolean | string[] | RegExp | Array<string | RegExp>
>(arg: T | Expression<T>): T | string {
return arg instanceof Expression ? arg.toCEL() : arg;
}

Expand All @@ -171,13 +175,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 string | number | boolean | string[] | RegExp | Array<string | RegExp>>(
arg: T | Expression<T>
): string {
if (arg instanceof Expression) {
return arg.toString();
} else if (typeof arg === "string") {
return `"${arg}"`;
} 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 @@ -187,7 +195,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[]
T extends string | number | boolean | string[] | RegExp | Array<string | RegExp>
> extends Expression<T> {
constructor(
private readonly test: Expression<boolean>,
Expand Down Expand Up @@ -263,7 +271,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 string | number | boolean | string[] | RegExp | Array<string | RegExp>>(
ifTrue: retT | Expression<retT>,
ifFalse: retT | Expression<retT>
) {
Expand Down Expand Up @@ -719,11 +727,14 @@ export class BooleanParam extends Param<boolean> {
}

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

thenElse<T extends string | number | boolean>(
thenElse<T extends string | number | boolean | string[] | RegExp | Array<string | RegExp>>(
ifTrue: T | Expression<T>,
ifFalse: T | Expression<T>
) {
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