From 92486940993a34cb05a6d573612c0a93d5a9428a Mon Sep 17 00:00:00 2001 From: Alexander Midteide Date: Fri, 31 Jan 2025 10:36:09 +0100 Subject: [PATCH] fix: Secure cookies in staging/test/prod --- compose.yml | 1 + packages/bff/src/graphql/fastifyHeaders.ts | 7 +++++++ packages/bff/src/server.ts | 10 ++-------- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/compose.yml b/compose.yml index 338410c05..0f4b1a47c 100644 --- a/compose.yml +++ b/compose.yml @@ -111,6 +111,7 @@ services: REDIS_CONNECTION_STRING: redis://:mysecretpassword@redis:6379/0 PORT: 80 NODE_ENV: production + COOKIE_SECURE: false APPLICATIONINSIGHTS_CONNECTION_STRING: ${APPLICATIONINSIGHTS_CONNECTION_STRING} APPLICATIONINSIGHTS_ENABLED: ${APPLICATIONINSIGHTS_ENABLED} labels: diff --git a/packages/bff/src/graphql/fastifyHeaders.ts b/packages/bff/src/graphql/fastifyHeaders.ts index 1c01e3204..cd80f85c4 100644 --- a/packages/bff/src/graphql/fastifyHeaders.ts +++ b/packages/bff/src/graphql/fastifyHeaders.ts @@ -22,6 +22,13 @@ const plugin: FastifyPluginAsync = async (fastify) => { 'X-XSS-Protection': '1; mode=block', }); }); + // Middleware to set secure cookies based on X-Forwarded-Proto header + fastify.addHook('onRequest', (request, reply, done) => { + if (request.headers['x-forwarded-proto'] === 'https') { + request.session.cookie.secure = true; + } + done(); + }); } catch (e) { logger.error(e, 'Error setting headers'); request.tokenIsValid = false; diff --git a/packages/bff/src/server.ts b/packages/bff/src/server.ts index efef7e949..254286a13 100644 --- a/packages/bff/src/server.ts +++ b/packages/bff/src/server.ts @@ -21,14 +21,10 @@ const { version, port, host, oidc_url, hostname, client_id, client_secret, redis const startServer = async (): Promise => { const { secret, cookie: cookieConfig, enableGraphiql } = config; - const server = Fastify({ ignoreTrailingSlash: true, ignoreDuplicateSlashes: true, - // The application gateway will terminate https and forward request as http - // This ensures that the proxy aka application gateway is trusted - // Setting cookie to secure will make it expect https requests without this - trustProxy: cookieConfig.secure, + trustProxy: true, }); const { dataSource } = await connectToDB(); @@ -46,16 +42,14 @@ const startServer = async (): Promise => { server.register(cookie); // Session setup - const cookieSessionConfig: FastifySessionOptions = { secret, cookie: { secure: cookieConfig.secure, - httpOnly: cookieConfig.httpOnly, + httpOnly: true, maxAge: cookieConfig.maxAge, }, }; - if (redisConnectionString) { const store = new RedisStore({ client: redisClient,