From 4618a520147e9a8106a471f43161c417debfba4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivar=20Conradi=20=C3=98sthus?= Date: Wed, 13 Dec 2023 16:12:17 +0100 Subject: [PATCH] fix: optimize cores headers (#5629) This commit enhances two aspects of CORS: - Always support CORS preflight requests. - Do not add additional secuity headers for prefligh calls. --- src/lib/app.ts | 5 +---- src/lib/middleware/conditional-middleware.ts | 1 - src/lib/middleware/cors-origin-middleware.ts | 6 +++++- src/lib/middleware/secure-headers.ts | 8 ++++---- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/lib/app.ts b/src/lib/app.ts index bcfd7aaa0b..d9001411b7 100644 --- a/src/lib/app.ts +++ b/src/lib/app.ts @@ -102,10 +102,7 @@ export default async function getApp( // so this must be handled before the API token middleware. app.options( `${baseUriPath}/api/frontend*`, - conditionalMiddleware( - () => config.flagResolver.isEnabled('embedProxy'), - corsOriginMiddleware(services, config), - ), + corsOriginMiddleware(services, config), ); app.use(baseUriPath, patMiddleware(config, services)); diff --git a/src/lib/middleware/conditional-middleware.ts b/src/lib/middleware/conditional-middleware.ts index 3a5eb4a249..c548618c20 100644 --- a/src/lib/middleware/conditional-middleware.ts +++ b/src/lib/middleware/conditional-middleware.ts @@ -7,7 +7,6 @@ export const conditionalMiddleware = ( const router = Router(); router.use((req, res, next) => { - res.setHeader('Vary', 'Origin'); if (condition()) { middleware(req, res, next); } else { diff --git a/src/lib/middleware/cors-origin-middleware.ts b/src/lib/middleware/cors-origin-middleware.ts index 6645c93e8b..4804b00e5e 100644 --- a/src/lib/middleware/cors-origin-middleware.ts +++ b/src/lib/middleware/cors-origin-middleware.ts @@ -19,7 +19,7 @@ export const corsOriginMiddleware = ( { proxyService }: Pick, config: IUnleashConfig, ): RequestHandler => { - return cors(async (req, callback) => { + const corsFunc = cors(async (req, callback) => { try { const { frontendApiOrigins = [] } = await proxyService.getFrontendSettings(); @@ -33,4 +33,8 @@ export const corsOriginMiddleware = ( callback(error); } }); + return (req, res, next) => { + res.setHeader('Vary', 'Origin'); + corsFunc(req, res, next); + }; }; diff --git a/src/lib/middleware/secure-headers.ts b/src/lib/middleware/secure-headers.ts index b061c0daff..9d863ac14d 100644 --- a/src/lib/middleware/secure-headers.ts +++ b/src/lib/middleware/secure-headers.ts @@ -116,11 +116,11 @@ const secureHeaders: (config: IUnleashConfig) => RequestHandler = (config) => { }); return (req, res, next) => { - const stripHeadersOnAPI = - config.flagResolver.isEnabled('stripHeadersOnAPI'); - if ( + if (req.method === 'OPTIONS') { + return next(); + } else if ( req.path.startsWith(`${config.server.baseUriPath}/api/`) && - stripHeadersOnAPI + config.flagResolver.isEnabled('stripHeadersOnAPI') ) { apiHelmet(req, res, next); } else {