From 2b5bc585a323201772d73fc4b825fd7c10c03e42 Mon Sep 17 00:00:00 2001 From: Oliver Eyton-Williams Date: Thu, 21 Sep 2023 15:40:19 +0200 Subject: [PATCH] feat(api): sync api and api-server CORS headers (#51608) --- api/src/plugins/cors.ts | 11 +++++++---- api/src/server.test.ts | 7 ++++--- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/api/src/plugins/cors.ts b/api/src/plugins/cors.ts index 3fe8fc08d92..f58b5455dd2 100644 --- a/api/src/plugins/cors.ts +++ b/api/src/plugins/cors.ts @@ -3,8 +3,6 @@ import { FastifyPluginCallback } from 'fastify'; import fp from 'fastify-plugin'; import { HOME_LOCATION } from '../utils/env'; -// import { FREECODECAMP_NODE_ENV } from '../utils/env'; - const allowedOrigins = [ 'https://www.freecodecamp.dev', 'https://www.freecodecamp.org', @@ -34,9 +32,14 @@ const cors: FastifyPluginCallback = (fastify, _options, done) => { void reply .header( 'Access-Control-Allow-Headers', - 'Origin, X-Requested-With, Content-Type, Accept' + 'Origin, X-Requested-With, Content-Type, Accept, Csrf-Token' ) - .header('Access-Control-Allow-Credentials', true); + .header('Access-Control-Allow-Credentials', true) + // These 4 are the only methods we use + .header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE') + // Vary: Origin to prevent cache poisoning + // TODO: do we need Vary: Accept-Encoding? + .header('Vary', 'Origin, Accept-Encoding'); }); done(); diff --git a/api/src/server.test.ts b/api/src/server.test.ts index b7c81a68692..d004f468a5e 100644 --- a/api/src/server.test.ts +++ b/api/src/server.test.ts @@ -89,12 +89,13 @@ describe('server', () => { }); }); - test('should have Access-Control-Allow-(Headers+Credentials) headers', async () => { + test('should have CORS headers', async () => { const res = await superRequest('/', { method: 'GET' }); expect(res.headers).toMatchObject({ 'access-control-allow-headers': - 'Origin, X-Requested-With, Content-Type, Accept', - 'access-control-allow-credentials': 'true' + 'Origin, X-Requested-With, Content-Type, Accept, Csrf-Token', + 'access-control-allow-credentials': 'true', + 'access-control-allow-methods': 'GET, PUT, POST, DELETE' }); }); });