diff --git a/backend/src/__tests__/security.test.ts b/backend/src/__tests__/security.test.ts new file mode 100644 index 00000000..f537d05f --- /dev/null +++ b/backend/src/__tests__/security.test.ts @@ -0,0 +1,108 @@ +import { sanitizeInput, detectSuspiciousPatterns } from '../middleware/sanitizer'; +import { Request, Response, NextFunction } from 'express'; + +describe('Security Middleware', () => { + describe('detectSuspiciousPatterns', () => { + let req: Partial; + let res: Partial; + let next: NextFunction; + let jsonMock: jest.Mock; + + beforeEach(() => { + jsonMock = jest.fn(); + req = { + body: {}, + query: {}, + params: {} + }; + res = { + status: jest.fn(() => ({ json: jsonMock })), + }; + next = jest.fn(); + }); + + it('should detect XSS attempts with script tags', () => { + req.body = { + name: '' + }; + + detectSuspiciousPatterns(req as Request, res as Response, next); + + expect(res.status).toHaveBeenCalledWith(403); + expect(jsonMock).toHaveBeenCalled(); + }); + + it('should detect SQL injection attempts', () => { + req.body = { + id: "1' OR '1'='1" + }; + + detectSuspiciousPatterns(req as Request, res as Response, next); + + expect(res.status).toHaveBeenCalledWith(403); + }); + + it('should detect NoSQL injection attempts', () => { + req.body = { + $gt: 0 + }; + + detectSuspiciousPatterns(req as Request, res as Response, next); + + expect(res.status).toHaveBeenCalledWith(403); + }); + + it('should let normal requests pass', () => { + req.body = { + name: 'John Doe', + email: 'john@example.com' + }; + + detectSuspiciousPatterns(req as Request, res as Response, next); + + expect(next).toHaveBeenCalled(); + }); + }); + + describe('sanitizeInput', () => { + let req: Partial; + let res: Partial; + let next: NextFunction; + + beforeEach(() => { + req = { + body: {}, + query: {}, + params: {} + }; + res = {}; + next = jest.fn(); + }); + + it('should strip HTML tags', () => { + req.body = { + name: 'John Doe', + bio: 'Hello' + }; + + sanitizeInput(req as Request, res as Response, next); + + expect(req.body.name).not.toContain(''); + expect(req.body.bio).not.toContain('