From 98c5329e03d972899a3f3b808d33a1b98c86ba5f Mon Sep 17 00:00:00 2001 From: Marshall Polaris Date: Fri, 20 May 2022 19:34:26 -0700 Subject: [PATCH] Fix up API CORS header processing (#277) * Fix ultra embarrassing bug not restricting CORS origins * Put CORS origin regexps in common * Static types so I don't muck it up again * Fixup CORS regex to be more strict * Fix sloppy imports to actually work --- common/envs/constants.ts | 8 ++++++++ functions/src/api.ts | 17 +++++++++++------ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/common/envs/constants.ts b/common/envs/constants.ts index dc753021..db82f014 100644 --- a/common/envs/constants.ts +++ b/common/envs/constants.ts @@ -1,3 +1,4 @@ +import { escapeRegExp } from 'lodash' import { DEV_CONFIG } from './dev' import { EnvConfig, PROD_CONFIG } from './prod' import { THEOREMONE_CONFIG } from './theoremone' @@ -28,3 +29,10 @@ export const DOMAIN = ENV_CONFIG.domain export const FIREBASE_CONFIG = ENV_CONFIG.firebaseConfig export const PROJECT_ID = ENV_CONFIG.firebaseConfig.projectId export const IS_PRIVATE_MANIFOLD = ENV_CONFIG.visibility === 'PRIVATE' + +// Manifold's domain or any subdomains thereof +export const CORS_ORIGIN_MANIFOLD = new RegExp( + '^https?://(?:[a-zA-Z0-9\\-]+\\.)*' + escapeRegExp(ENV_CONFIG.domain) + '$' +) +// Any localhost server on any port +export const CORS_ORIGIN_LOCALHOST = /^http:\/\/localhost:\d+$/ diff --git a/functions/src/api.ts b/functions/src/api.ts index aee95532..fa3a9aa6 100644 --- a/functions/src/api.ts +++ b/functions/src/api.ts @@ -2,7 +2,11 @@ import * as admin from 'firebase-admin' import * as functions from 'firebase-functions' import * as Cors from 'cors' -import { User, PrivateUser } from 'common/user' +import { User, PrivateUser } from '../../common/user' +import { + CORS_ORIGIN_MANIFOLD, + CORS_ORIGIN_LOCALHOST, +} from '../../common/envs/constants' type Request = functions.https.Request type Response = functions.Response @@ -90,10 +94,11 @@ export const lookupUser = async (creds: Credentials): Promise => { } } -export const CORS_ORIGIN_MANIFOLD = /^https?:\/\/.+\.manifold\.markets$/ -export const CORS_ORIGIN_LOCALHOST = /^http:\/\/localhost:\d+$/ - -export const applyCors = (req: any, res: any, params: object) => { +export const applyCors = ( + req: Request, + res: Response, + params: Cors.CorsOptions +) => { return new Promise((resolve, reject) => { Cors(params)(req, res, (result) => { if (result instanceof Error) { @@ -107,7 +112,7 @@ export const applyCors = (req: any, res: any, params: object) => { export const newEndpoint = (methods: [string], fn: Handler) => functions.runWith({ minInstances: 1 }).https.onRequest(async (req, res) => { await applyCors(req, res, { - origins: [CORS_ORIGIN_MANIFOLD, CORS_ORIGIN_LOCALHOST], + origin: [CORS_ORIGIN_MANIFOLD, CORS_ORIGIN_LOCALHOST], methods: methods, }) try {