From b3a95378f165959d9eca1803ba50b6e6d6651f4d Mon Sep 17 00:00:00 2001 From: Avnyr Date: Fri, 16 May 2025 18:10:42 +0200 Subject: [PATCH] feat: enhance CORS configuration for development and production environments - Updated backend CORS setup to differentiate between development (open origins) and production (restricted origins). - Implemented support for additional allowed origins via environment variables. - Adjusted `WebSocketGateway` CORS settings to align with the new configuration. - Updated `PROJECT_STATUS.md` to reflect progress on CORS-related security tasks. --- backend/src/main.ts | 41 ++++++++++++++++--- .../modules/websockets/websockets.gateway.ts | 15 ++++--- docs/PROJECT_STATUS.md | 8 ++-- 3 files changed, 49 insertions(+), 15 deletions(-) diff --git a/backend/src/main.ts b/backend/src/main.ts index d28a006..63acd30 100644 --- a/backend/src/main.ts +++ b/backend/src/main.ts @@ -16,12 +16,41 @@ async function bootstrap() { }), ); - // Configuration CORS - app.enableCors({ - origin: configService.get('CORS_ORIGIN', 'http://localhost:3000'), - methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', - credentials: true, - }); + // Configuration CORS selon l'environnement + const environment = configService.get('NODE_ENV', 'development'); + const frontendUrl = configService.get('FRONTEND_URL', 'http://localhost:3001'); + + if (environment === 'development') { + // En développement, on autorise toutes les origines avec credentials + app.enableCors({ + origin: true, + methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS', + credentials: true, + }); + console.log('CORS configured for development environment (all origins allowed)'); + } else { + // En production, on restreint les origines autorisées + const allowedOrigins = [frontendUrl]; + // Ajouter d'autres origines si nécessaire (ex: sous-domaines, CDN, etc.) + if (configService.get('ADDITIONAL_CORS_ORIGINS')) { + allowedOrigins.push(...configService.get('ADDITIONAL_CORS_ORIGINS').split(',')); + } + + app.enableCors({ + origin: (origin, callback) => { + // Permettre les requêtes sans origine (comme les appels d'API mobile) + if (!origin || allowedOrigins.includes(origin)) { + callback(null, true); + } else { + callback(new Error(`Origin ${origin} not allowed by CORS`)); + } + }, + methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS', + credentials: true, + maxAge: 86400, // 24 heures de mise en cache des résultats preflight + }); + console.log(`CORS configured for production environment with allowed origins: ${allowedOrigins.join(', ')}`); + } // Préfixe global pour les routes API app.setGlobalPrefix(configService.get('API_PREFIX', 'api')); diff --git a/backend/src/modules/websockets/websockets.gateway.ts b/backend/src/modules/websockets/websockets.gateway.ts index 01cdcf2..85e2e1a 100644 --- a/backend/src/modules/websockets/websockets.gateway.ts +++ b/backend/src/modules/websockets/websockets.gateway.ts @@ -24,15 +24,20 @@ import { Server, Socket } from 'socket.io'; */ @WebSocketGateway({ cors: { - origin: process.env.FRONTEND_URL || 'http://localhost:3001', + origin: process.env.NODE_ENV === 'development' + ? true + : [ + process.env.FRONTEND_URL || 'http://localhost:3001', + ...(process.env.ADDITIONAL_CORS_ORIGINS ? process.env.ADDITIONAL_CORS_ORIGINS.split(',') : []) + ], credentials: true, }, }) export class WebSocketsGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect { - + @WebSocketServer() server: Server; - + private logger = new Logger('WebSocketsGateway'); private connectedClients = new Map(); // socketId -> userId @@ -48,7 +53,7 @@ export class WebSocketsGateway */ handleConnection(client: Socket, ...args: any[]) { const userId = client.handshake.query.userId as string; - + if (userId) { this.connectedClients.set(client.id, userId); client.join(`user:${userId}`); @@ -149,4 +154,4 @@ export class WebSocketsGateway this.server.to(`project:${projectId}`).emit('notification:new', data); this.logger.log(`Emitted notification:new for project ${projectId}`); } -} \ No newline at end of file +} diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index c7d80ca..2daf7b0 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -93,7 +93,7 @@ Nous avons élaboré un plan de bataille complet pour l'implémentation du backe ##### Sécurité et Conformité RGPD - [ ] Implémenter la validation des entrées avec class-validator -- [ ] Configurer CORS pour sécuriser les API +- [x] Configurer CORS pour sécuriser les API - [ ] Mettre en place la protection contre les attaques CSRF - [x] Implémenter les fonctionnalités d'export de données utilisateur (RGPD) dans le backend - [ ] Implémenter l'interface frontend pour l'export de données utilisateur @@ -217,7 +217,7 @@ Nous avons élaboré un plan de bataille complet pour l'implémentation du backe | Backend - Tests Unitaires | 100% | | Backend - Tests e2e | 20% | | Backend - Documentation API | 0% | -| Backend - Sécurité et RGPD | 50% | +| Backend - Sécurité et RGPD | 67% | | Frontend - Structure de Base | 100% | | Frontend - Pages et Composants | 100% | | Frontend - Authentification | 100% | @@ -235,7 +235,7 @@ Basé sur l'état d'avancement actuel et les tâches restantes, l'estimation du - **Backend**: ~2 semaines - Tests e2e: 3-4 jours - Documentation API avec Swagger: 3-4 jours - - Sécurité (validation des entrées, CORS, CSRF): 2-3 jours + - Sécurité (validation des entrées, CSRF): 1-2 jours - Finalisation des fonctionnalités RGPD: 1-2 jours - **Frontend**: ~3 semaines @@ -282,7 +282,7 @@ Cependant, plusieurs aspects importants restent à finaliser: 2. **Tests e2e et documentation**: Les tests end-to-end et la documentation API avec Swagger sont nécessaires pour assurer la qualité et la maintenabilité du projet. -3. **Sécurité**: Des améliorations de sécurité comme la validation des entrées, la configuration CORS et la protection CSRF sont encore à implémenter. +3. **Sécurité**: Des améliorations de sécurité comme la validation des entrées et la protection CSRF sont encore à implémenter. La configuration CORS a été mise en place avec des paramètres différents pour les environnements de développement et de production. 4. **Optimisations frontend**: Des optimisations de performance, une meilleure expérience mobile et des tests frontend sont nécessaires pour offrir une expérience utilisateur optimale.