test: enhance security middleware and token management tests

- Added comprehensive test coverage for TokenManager encryption and validation methods
- Implemented detailed test scenarios for security middleware functions
- Updated test cases to handle edge cases and improve input validation
- Refactored test mocks to provide more robust and realistic testing environment
- Improved error handling and input validation in security-related components
This commit is contained in:
jango-blockchained
2025-02-03 18:44:38 +01:00
parent 4e89e5458c
commit d17d881e7b
12 changed files with 658 additions and 428 deletions

View File

@@ -3,6 +3,7 @@ import { Request, Response, NextFunction } from 'express';
import rateLimit from 'express-rate-limit';
import helmet from 'helmet';
import { HelmetOptions } from 'helmet';
import jwt from 'jsonwebtoken';
// Security configuration
const RATE_LIMIT_WINDOW = 15 * 60 * 1000; // 15 minutes
@@ -42,83 +43,112 @@ const helmetConfig: HelmetOptions = {
// Security headers middleware
export const securityHeaders = helmet(helmetConfig);
// Token validation and encryption
const ALGORITHM = 'aes-256-gcm';
const IV_LENGTH = 16;
const AUTH_TAG_LENGTH = 16;
export class TokenManager {
private static readonly algorithm = 'aes-256-gcm';
private static readonly keyLength = 32;
private static readonly ivLength = 16;
private static readonly saltLength = 64;
private static readonly tagLength = 16;
private static readonly iterations = 100000;
private static readonly digest = 'sha512';
private static deriveKey(password: string, salt: Buffer): Buffer {
return crypto.pbkdf2Sync(
password,
salt,
this.iterations,
this.keyLength,
this.digest
);
}
public static encryptToken(token: string, encryptionKey: string): string {
const iv = crypto.randomBytes(this.ivLength);
const salt = crypto.randomBytes(this.saltLength);
const key = this.deriveKey(encryptionKey, salt);
const cipher = crypto.createCipheriv(this.algorithm, key, iv, {
authTagLength: this.tagLength
});
const encrypted = Buffer.concat([
cipher.update(token, 'utf8'),
cipher.final()
]);
const tag = cipher.getAuthTag();
return Buffer.concat([salt, iv, tag, encrypted]).toString('base64');
}
public static decryptToken(encryptedToken: string, encryptionKey: string): string {
const buffer = Buffer.from(encryptedToken, 'base64');
const salt = buffer.subarray(0, this.saltLength);
const iv = buffer.subarray(this.saltLength, this.saltLength + this.ivLength);
const tag = buffer.subarray(
this.saltLength + this.ivLength,
this.saltLength + this.ivLength + this.tagLength
);
const encrypted = buffer.subarray(this.saltLength + this.ivLength + this.tagLength);
const key = this.deriveKey(encryptionKey, salt);
const decipher = crypto.createDecipheriv(this.algorithm, key, iv, {
authTagLength: this.tagLength
});
decipher.setAuthTag(tag);
return decipher.update(encrypted) + decipher.final('utf8');
}
public static validateToken(token: string): boolean {
if (!token) return false;
/**
* Encrypts a token using AES-256-GCM
*/
static encryptToken(token: string, key: string): string {
if (!token || typeof token !== 'string') {
throw new Error('Invalid token');
}
if (!key || typeof key !== 'string' || key.length < 32) {
throw new Error('Invalid encryption key');
}
try {
// Check token format
if (!/^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/.test(token)) {
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv(ALGORITHM, key.slice(0, 32), iv);
const encrypted = Buffer.concat([
cipher.update(token, 'utf8'),
cipher.final()
]);
const tag = cipher.getAuthTag();
// Format: algorithm:iv:tag:encrypted
return `${ALGORITHM}:${iv.toString('base64')}:${tag.toString('base64')}:${encrypted.toString('base64')}`;
} catch (error) {
throw new Error('Failed to encrypt token');
}
}
/**
* Decrypts a token using AES-256-GCM
*/
static decryptToken(encryptedToken: string, key: string): string {
if (!encryptedToken || typeof encryptedToken !== 'string') {
throw new Error('Invalid encrypted token');
}
if (!key || typeof key !== 'string' || key.length < 32) {
throw new Error('Invalid encryption key');
}
try {
const [algorithm, ivBase64, tagBase64, encryptedBase64] = encryptedToken.split(':');
if (algorithm !== ALGORITHM || !ivBase64 || !tagBase64 || !encryptedBase64) {
throw new Error('Invalid encrypted token format');
}
const iv = Buffer.from(ivBase64, 'base64');
const tag = Buffer.from(tagBase64, 'base64');
const encrypted = Buffer.from(encryptedBase64, 'base64');
const decipher = crypto.createDecipheriv(ALGORITHM, key.slice(0, 32), iv);
decipher.setAuthTag(tag);
return Buffer.concat([
decipher.update(encrypted),
decipher.final()
]).toString('utf8');
} catch (error) {
if (error instanceof Error && error.message === 'Invalid encrypted token format') {
throw error;
}
throw new Error('Invalid encrypted token');
}
}
/**
* Validates a JWT token
*/
static validateToken(token: string): boolean {
if (!token || typeof token !== 'string') {
return false;
}
try {
const decoded = jwt.decode(token);
if (!decoded || typeof decoded !== 'object') {
return false;
}
// Decode token parts
const [headerEncoded, payloadEncoded] = token.split('.');
const header = JSON.parse(Buffer.from(headerEncoded, 'base64').toString());
const payload = JSON.parse(Buffer.from(payloadEncoded, 'base64').toString());
// Check token expiry
if (payload.exp && Date.now() >= payload.exp * 1000) {
// Check for expiration
if (!decoded.exp) {
return false;
}
// Additional checks can be added here
return true;
const now = Math.floor(Date.now() / 1000);
if (decoded.exp <= now) {
return false;
}
// Verify signature using the secret from environment variable
const secret = process.env.JWT_SECRET;
if (!secret) {
return false;
}
try {
jwt.verify(token, secret);
return true;
} catch {
return false;
}
} catch {
return false;
}

View File

@@ -0,0 +1,109 @@
import { Request, Response, NextFunction } from 'express';
import { validateRequest, sanitizeInput } from '../../src/security/middleware';
type MockRequest = {
headers: {
'content-type'?: string;
authorization?: string;
};
body?: any;
is: jest.MockInstance<string | false | null, [type: string | string[]]>;
};
type MockResponse = {
status: jest.MockInstance<MockResponse, [code: number]>;
json: jest.MockInstance<MockResponse, [body: any]>;
setHeader: jest.MockInstance<MockResponse, [name: string, value: string]>;
};
describe('Security Middleware', () => {
let mockRequest: MockRequest;
let mockResponse: MockResponse;
let nextFunction: jest.Mock;
beforeEach(() => {
mockRequest = {
headers: {},
body: {},
is: jest.fn<string | false | null, [string | string[]]>().mockReturnValue('json')
};
mockResponse = {
status: jest.fn<MockResponse, [number]>().mockReturnThis(),
json: jest.fn<MockResponse, [any]>().mockReturnThis(),
setHeader: jest.fn<MockResponse, [string, string]>().mockReturnThis()
};
nextFunction = jest.fn();
});
describe('validateRequest', () => {
it('should pass valid requests', () => {
mockRequest.headers.authorization = 'Bearer valid-token';
validateRequest(mockRequest as unknown as Request, mockResponse as unknown as Response, nextFunction);
expect(nextFunction).toHaveBeenCalled();
});
it('should reject requests without authorization header', () => {
validateRequest(mockRequest as unknown as Request, mockResponse as unknown as Response, nextFunction);
expect(mockResponse.status).toHaveBeenCalledWith(401);
expect(mockResponse.json).toHaveBeenCalledWith(expect.objectContaining({
error: expect.stringContaining('authorization')
}));
});
it('should reject requests with invalid authorization format', () => {
mockRequest.headers.authorization = 'invalid-format';
validateRequest(mockRequest as unknown as Request, mockResponse as unknown as Response, nextFunction);
expect(mockResponse.status).toHaveBeenCalledWith(401);
expect(mockResponse.json).toHaveBeenCalledWith(expect.objectContaining({
error: expect.stringContaining('Bearer')
}));
});
});
describe('sanitizeInput', () => {
it('should pass requests without body', () => {
delete mockRequest.body;
sanitizeInput(mockRequest as unknown as Request, mockResponse as unknown as Response, nextFunction);
expect(nextFunction).toHaveBeenCalled();
});
it('should sanitize HTML in request body', () => {
mockRequest.body = {
text: '<script>alert("xss")</script>Hello',
nested: {
html: '<img src="x" onerror="alert(1)">World'
}
};
sanitizeInput(mockRequest as unknown as Request, mockResponse as unknown as Response, nextFunction);
expect(mockRequest.body.text).toBe('Hello');
expect(mockRequest.body.nested.html).toBe('World');
expect(nextFunction).toHaveBeenCalled();
});
it('should handle non-object bodies', () => {
mockRequest.body = '<p>text</p>';
sanitizeInput(mockRequest as unknown as Request, mockResponse as unknown as Response, nextFunction);
expect(mockRequest.body).toBe('text');
expect(nextFunction).toHaveBeenCalled();
});
it('should preserve non-string values', () => {
mockRequest.body = {
number: 42,
boolean: true,
null: null,
array: [1, 2, 3]
};
sanitizeInput(mockRequest as unknown as Request, mockResponse as unknown as Response, nextFunction);
expect(mockRequest.body).toEqual({
number: 42,
boolean: true,
null: null,
array: [1, 2, 3]
});
expect(nextFunction).toHaveBeenCalled();
});
});
});