Skip to content

Commit

Permalink
CORS origins of an array of one are made a scalar. (#1536)
Browse files Browse the repository at this point in the history
The access-control-allowed-origins CORS header only allows
a single origin or "*" as its response. To support multiple origins,
the cors middleware makes this header dynamic based on the origin
header of the request when the middleware is configured with anything
but a single string.

To help avoid a few edge cases customers may encounter, we can unwrap
an array of one element into a scalar to encourage the cors middleware
to make the access-control-allowed-origin header static.

As a very minor performance boost, this change also instantiates the
cors middleware once and uses it on all requests rather than
constructing it dynamically within a request.
  • Loading branch information
inlined authored Mar 19, 2024
1 parent 3d8d595 commit 0aaedc4
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/v2/providers/https.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,12 +265,19 @@ export function onRequest(
// Respect `cors: false` to turn off cors even if debug feature is enabled.
origin = opts.cors === false ? false : true;
}
// Arrays cause the access-control-allow-origin header to be dynamic based
// on the origin header of the request. If there is only one element in the
// array, this is unnecessary.
if (Array.isArray(origin) && origin.length === 1) {
origin = origin[1];
}
const middleware = cors({ origin });

const userProvidedHandler = handler;
handler = (req: Request, res: express.Response): void | Promise<void> => {
return new Promise((resolve) => {
res.on("finish", resolve);
cors({ origin })(req, res, () => {
middleware(req, res, () => {
resolve(userProvidedHandler(req, res));
});
});
Expand Down Expand Up @@ -363,7 +370,13 @@ export function onCall<T = any, Return = any | Promise<any>>(
opts = optsOrHandler as CallableOptions;
}

const origin = isDebugFeatureEnabled("enableCors") ? true : "cors" in opts ? opts.cors : true;
let origin = isDebugFeatureEnabled("enableCors") ? true : "cors" in opts ? opts.cors : true;
// Arrays cause the access-control-allow-origin header to be dynamic based
// on the origin header of the request. If there is only one element in the
// array, this is unnecessary.
if (Array.isArray(origin) && origin.length === 1) {
origin = origin[1];
}

// onCallHandler sniffs the function length to determine which API to present.
// fix the length to prevent api versions from being mismatched.
Expand Down

0 comments on commit 0aaedc4

Please sign in to comment.