Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PS-703 : Added CORS and helmet to middle ware for security #16

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "middleware_micorservice",
"name": "middleware_microservice",
"version": "0.0.1",
"description": "",
"author": "",
Expand Down Expand Up @@ -34,7 +34,9 @@
"cache-manager-memory-store": "^1.1.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"helmet": "^8.0.0",
"nest-winston": "^1.9.6",
"passport-jwt": "^4.0.1",
"reflect-metadata": "^0.1.14",
Expand Down
56 changes: 56 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,35 @@
import { NestFactory } from '@nestjs/core';
import helmet from 'helmet';
import { AppModule } from './app.module';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import * as dotenv from 'dotenv';
import { ConfigService } from '@nestjs/config';
import { ForbiddenException } from '@nestjs/common';

async function bootstrap() {
dotenv.config(); // Load environment variables from .env file
const app = await NestFactory.create(AppModule);

const configService = app.get(ConfigService);

const corsOriginList = configService
.get<string>('CORS_ORIGIN_LIST')
?.split(',');

if (!corsOriginList || corsOriginList.length === 0) {
throw new Error('CORS_ORIGIN_LIST is not defined or empty');
}

if (corsOriginList[0] !== '*' && !validateCorsOriginList(corsOriginList)) {
throw new Error('Invalid CORS_ORIGIN_LIST');
}
Comment on lines +23 to +25
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Potential issue with empty corsOriginList.

If CORS_ORIGIN_LIST is undefined or empty, accessing corsOriginList[0] could lead to an error.

Add a check to handle cases where corsOriginList is undefined or empty.

Apply this diff:

+  if (!corsOriginList || corsOriginList.length === 0) {
+    throw new Error('CORS_ORIGIN_LIST is not defined or empty');
+  }

   if (corsOriginList[0] !== '*' && !validateCorsOriginList(corsOriginList)) {
     throw new Error('Invalid CORS_ORIGIN_LIST');
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (corsOriginList[0] !== '*' && !validateCorsOriginList(corsOriginList)) {
throw new Error('Invalid CORS_ORIGIN_LIST');
}
if (!corsOriginList || corsOriginList.length === 0) {
throw new Error('CORS_ORIGIN_LIST is not defined or empty');
}
if (corsOriginList[0] !== '*' && !validateCorsOriginList(corsOriginList)) {
throw new Error('Invalid CORS_ORIGIN_LIST');
}


const corsOptions = {
origin: corsOriginList, // Array of allowed origins
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', // Specify allowed methods
credentials: true, // Allow credentials (cookies, authorization headers)
};

const config = new DocumentBuilder()
.setTitle('Middleware APIs')
.setDescription('The Middlware service')
Expand All @@ -17,8 +41,40 @@ async function bootstrap() {
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api/swagger-docs', app, document);

app.use((req, res, next) => {
const origin = req.headers.origin;

if (corsOriginList.includes(origin) || corsOriginList[0] === '*') {
res.setHeader('Access-Control-Allow-Origin', origin);
} else {
throw new ForbiddenException('Origin not allowed');
}
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.header(
'Access-Control-Allow-Methods',
'GET,HEAD,PUT,PATCH,POST,DELETE',
);
next();
});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Remove redundant custom CORS middleware.

The custom CORS middleware implementation conflicts with the app.enableCors(corsOptions) call on line 61. This redundancy can lead to unexpected behavior and was previously pointed out in a past review comment.

Consider removing the custom middleware and relying solely on app.enableCors(corsOptions) for CORS handling. If custom logic is needed, it should be incorporated into the corsOptions object.

Apply this diff to remove the custom middleware:

-  app.use((req, res, next) => {
-    const origin = req.headers.origin;
-
-    if (corsOriginList.includes(origin) || corsOriginList[0] === '*') {
-      res.setHeader('Access-Control-Allow-Origin', origin);
-    } else {
-      throw new ForbiddenException('Origin not allowed');
-    }
-    res.setHeader('Access-Control-Allow-Credentials', 'true');
-    res.header(
-      'Access-Control-Allow-Methods',
-      'GET,HEAD,PUT,PATCH,POST,DELETE',
-    );
-    next();
-  });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
app.use((req, res, next) => {
const origin = req.headers.origin;
if (corsOriginList.includes(origin) || corsOriginList[0] === '*') {
res.setHeader('Access-Control-Allow-Origin', origin);
} else {
throw new ForbiddenException('Origin not allowed');
}
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.header(
'Access-Control-Allow-Methods',
'GET,HEAD,PUT,PATCH,POST,DELETE',
);
next();
});


app.enableCors(corsOptions);
app.use(helmet());

await app.listen(4000, () => {
console.log(`Server middleware on port - 4000`);
});
}

function validateCorsOriginList(corsOriginList: string[]): boolean {
return corsOriginList.every((origin) => {
try {
new URL(origin);
return true;
} catch (error) {
return false;
}
});
}

bootstrap();