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 all 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
53 changes: 49 additions & 4 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,44 @@
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);
app.enableCors();

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: (origin, callback) => {
if (corsOriginList.includes(origin) || corsOriginList[0] === '*') {
callback(null, true);
} else {
callback(new ForbiddenException('Origin not allowed'));
}
},
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')
.setDescription('The Middleware service')
.setVersion('1.0')
.addApiKey(
{ type: 'apiKey', name: 'Authorization', in: 'header' },
Expand All @@ -18,8 +47,24 @@ async function bootstrap() {
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api/swagger-docs', app, document);
await app.listen(process.env.PORT || 4000, () => {
console.log(`Server middleware on port - ${process.env.PORT}`);

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();