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 2 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
49 changes: 48 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,31 @@
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 { InternalServerErrorException } from '@nestjs/common';

async function bootstrap() {
dotenv.config(); // Load environment variables from .env file
const app = await NestFactory.create(AppModule);
const app = await NestFactory.create(AppModule, { cors: true });
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Redundant CORS configuration detected.

You have enabled CORS by setting { cors: true } in NestFactory.create, and later you enable CORS again using app.enableCors(corsOptions);. This redundancy might cause unexpected behavior.

Consider removing the { cors: true } option when creating the app, since you are configuring CORS with custom options later.

Apply this diff:

-  const app = await NestFactory.create(AppModule, { cors: true });
+  const app = await NestFactory.create(AppModule);
📝 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
const app = await NestFactory.create(AppModule, { cors: true });
const app = await NestFactory.create(AppModule);


const configService = app.get(ConfigService);

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

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 +37,35 @@ 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 InternalServerErrorException('Invalid CORS_ORIGIN');
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improper error handling for invalid CORS origins.

Throwing an InternalServerErrorException when the origin is invalid may not be appropriate and could expose internal details.

Instead of throwing an exception, you can simply not set the Access-Control-Allow-Origin header, or respond with a 403 Forbidden status.

Apply this diff:

     if (corsOriginList.includes(origin) || corsOriginList[0] === '*') {
       res.setHeader('Access-Control-Allow-Origin', origin);
     } else {
-      throw new InternalServerErrorException('Invalid CORS_ORIGIN');
+      res.status(403).send('Forbidden');
+      return;
     }

However, removing the custom middleware as suggested earlier would eliminate this issue.

📝 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.includes(origin) || corsOriginList[0] === '*') {
res.setHeader('Access-Control-Allow-Origin', origin);
} else {
throw new InternalServerErrorException('Invalid CORS_ORIGIN');
}
if (corsOriginList.includes(origin) || corsOriginList[0] === '*') {
res.setHeader('Access-Control-Allow-Origin', origin);
} else {
res.status(403).send('Forbidden');
return;
}

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

Redundant and conflicting CORS middleware.

You have manually implemented a middleware to handle CORS, but you also enable CORS using app.enableCors(corsOptions); at line 57. This redundancy can cause conflicts and unexpected behaviors.

Consider removing the custom middleware and rely on app.enableCors(corsOptions); for CORS handling.

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 InternalServerErrorException('Invalid CORS_ORIGIN');
-    }
-    res.setHeader('Access-Control-Allow-Credentials', 'true');
-    res.header(
-      'Access-Control-Allow-Methods',
-      'GET,HEAD,PUT,PATCH,POST,DELETE',
-    );
-    next();
-  });

If you need custom logic, you can adjust the corsOptions passed to app.enableCors().

📝 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 InternalServerErrorException('Invalid CORS_ORIGIN');
}
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) => {
return origin.includes('http://') || origin.includes('https://');
});
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve CORS origin validation.

The current validation only checks if the origins include http:// or https://, which might not sufficiently validate the URLs.

Consider using the URL constructor to validate each origin.

Apply this diff:

function validateCorsOriginList(corsOriginList: string[]): boolean {
-  return corsOriginList.every((origin) => {
-    return origin.includes('http://') || origin.includes('https://');
-  });
+  return corsOriginList.every((origin) => {
+    try {
+      new URL(origin);
+      return true;
+    } catch (error) {
+      return false;
+    }
+  });
}

This approach ensures that each origin is a valid URL.

📝 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
function validateCorsOriginList(corsOriginList: string[]): boolean {
return corsOriginList.every((origin) => {
return origin.includes('http://') || origin.includes('https://');
});
}
function validateCorsOriginList(corsOriginList: string[]): boolean {
return corsOriginList.every((origin) => {
try {
new URL(origin);
return true;
} catch (error) {
return false;
}
});
}


bootstrap();