Skip to content

Commit

Permalink
fix(apollo-server-lambda): allow regex support for Access-Control-All…
Browse files Browse the repository at this point in the history
…ow-Origin (apollographql#4470)

fix(apollo-server-cloud-functions): allow regex support for Access-Control-Allow-Origin (apollographql#4470)
  • Loading branch information
prescottprue committed Apr 1, 2021
1 parent 1bb051f commit d3080f0
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
17 changes: 14 additions & 3 deletions packages/apollo-server-cloud-functions/src/ApolloServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { graphqlCloudFunction } from './googleCloudApollo';

export interface CreateHandlerOptions {
cors?: {
origin?: boolean | string | string[];
origin?: boolean | string | (string | RegExp)[];
methods?: string | string[];
allowedHeaders?: string | string[];
exposedHeaders?: string | string[];
Expand Down Expand Up @@ -82,13 +82,24 @@ export class ApolloServer extends ApolloServerBase {
return;
}

if (cors) {
if (cors && cors.origin) {
const requestOrigin = req.get('origin') || '';
if (typeof cors.origin === 'string') {
res.set('Access-Control-Allow-Origin', cors.origin);
} else if (
typeof cors.origin === 'boolean' ||
(Array.isArray(cors.origin) &&
cors.origin.includes(req.get('origin') || ''))
// Check settings array for strings matching origin
(cors.origin.includes(requestOrigin) ||
// Check settings array for Regex matching origin
cors.origin.some((setting) =>
setting instanceof RegExp && setting.test(requestOrigin)
)
)
) ||
// Check origin for matching Regex
(cors.origin instanceof RegExp &&
cors.origin.test(requestOrigin))
) {
res.set('Access-Control-Allow-Origin', req.get('origin'));
}
Expand Down
13 changes: 10 additions & 3 deletions packages/apollo-server-lambda/src/ApolloServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { Readable, Writable } from 'stream';

export interface CreateHandlerOptions {
cors?: {
origin?: boolean | string | string[];
origin?: boolean | string | (string | RegExp)[];
methods?: string | string[];
allowedHeaders?: string | string[];
exposedHeaders?: string | string[];
Expand Down Expand Up @@ -171,8 +171,15 @@ export class ApolloServer extends ApolloServerBase {
requestOrigin &&
(typeof cors.origin === 'boolean' ||
(Array.isArray(cors.origin) &&
requestOrigin &&
cors.origin.includes(requestOrigin)))
// Check settings array for strings matching origin
(cors.origin.includes(requestOrigin) ||
// Check settings array for Regex matching origin
cors.origin.some((setting) =>
setting instanceof RegExp &&
setting.test(requestOrigin)
)
)
))
) {
requestCorsHeaders.set(
'access-control-allow-origin',
Expand Down

0 comments on commit d3080f0

Please sign in to comment.