Skip to content

Commit

Permalink
fix: Secure cookies in staging/test/prod
Browse files Browse the repository at this point in the history
  • Loading branch information
alexdigdir committed Jan 31, 2025
1 parent b7a02ea commit 9248694
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 8 deletions.
1 change: 1 addition & 0 deletions compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
7 changes: 7 additions & 0 deletions packages/bff/src/graphql/fastifyHeaders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
10 changes: 2 additions & 8 deletions packages/bff/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,10 @@ const { version, port, host, oidc_url, hostname, client_id, client_secret, redis

const startServer = async (): Promise<void> => {
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();
Expand All @@ -46,16 +42,14 @@ const startServer = async (): Promise<void> => {
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,
Expand Down

0 comments on commit 9248694

Please sign in to comment.