Skip to content
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
10 changes: 10 additions & 0 deletions backend/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>/src'],
testMatch: ['**/*.test.ts'],
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
},
};
29 changes: 29 additions & 0 deletions backend/jest.setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@

// Set environment variables for testing
process.env.NODE_ENV = 'test';
process.env.JWT_SECRET = 'test-secret-at-least-32-chars-long-123456';
process.env.DATABASE_URL = 'postgresql://user:pass@localhost:5432/testdb';
process.env.REDIS_URL = 'redis://localhost:6379';
process.env.LUNES_RPC_URL = 'https://rpc.lunes.io';
process.env.CONTRACT_ADDRESS = '0x1234567890123456789012345678901234567890';
process.env.PRIVATE_KEY = '0x1234567890123456789012345678901234567890123456789012345678901234';

// Mock ioredis
jest.mock('ioredis', () => {
return class Redis {
constructor() {}
async get() { return null; }
async set() { return 'OK'; }
async del() { return 1; }
async exists() { return 0; }
on() {}
duplicate() { return this; }
};
});

// Mock console to reduce noise
global.console = {
...console,
// log: jest.fn(),
// error: jest.fn(),
};
105 changes: 24 additions & 81 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
"dependencies": {
"@fastify/cors": "^8.4.0",
"@fastify/helmet": "^11.1.1",
"@fastify/jwt": "^10.0.0",
"@fastify/jwt": "^8.0.1",
"@fastify/multipart": "^8.0.0",
"@fastify/rate-limit": "^9.0.1",
"@fastify/swagger": "^8.12.0",
Expand Down
18 changes: 6 additions & 12 deletions backend/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class App {
this.setupErrorHandling();
}

private async initialize(): Promise<void> {
public async initialize(): Promise<void> {
await this.setupMiddlewares();
await this.setupRoutes();
}
Expand All @@ -64,17 +64,11 @@ class App {
},
});

// Rate Limiting - DESABILITADO PARA DESENVOLVIMENTO
// await this.server.register(rateLimit, {
// max: envConfig.RATE_LIMIT_MAX_REQUESTS,
// timeWindow: envConfig.RATE_LIMIT_WINDOW_MS,
// errorResponseBuilder: (request, context) => ({
// code: 429,
// error: 'Rate Limit Exceeded',
// message: `Muitas tentativas. Tente novamente em ${Math.round(context.ttl / 1000)} segundos.`,
// expiresIn: context.ttl,
// }),
// });
// Rate Limiting
await this.server.register(rateLimit, {
max: envConfig.RATE_LIMIT_MAX_REQUESTS,
timeWindow: envConfig.RATE_LIMIT_WINDOW_MS,
});

// Swagger Documentation
if (envConfig.ENABLE_SWAGGER) {
Expand Down
2 changes: 1 addition & 1 deletion backend/src/shared/middleware/error.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export const errorHandler = (server: FastifyInstance) => {
const errorResponse: any = {
success: false,
error: {
code: error.code || 'INTERNAL_SERVER_ERROR',
code: error.code || (statusCode === 429 ? 'RATE_LIMIT_EXCEEDED' : 'INTERNAL_SERVER_ERROR'),
message: getErrorMessage(error, statusCode),
timestamp: new Date().toISOString(),
path: url,
Expand Down
47 changes: 47 additions & 0 deletions backend/src/tests/rate_limit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { envConfig } from '../config/env.config';
import { app } from '../app';

describe('Rate Limiting', () => {
beforeAll(async () => {
// Configure rate limit for testing
// We override the values directly on the singleton
(envConfig as any).RATE_LIMIT_MAX_REQUESTS = 2;
(envConfig as any).RATE_LIMIT_WINDOW_MS = 1000;

// Initialize the app (registers plugins)
await app.initialize();
});

afterAll(async () => {
await app.stop();
});

it('should enforce rate limits', async () => {
// Request 1: OK
const response1 = await app.server.inject({
method: 'GET',
url: '/health',
});
expect(response1.statusCode).toBe(200);

// Request 2: OK
const response2 = await app.server.inject({
method: 'GET',
url: '/health',
});
expect(response2.statusCode).toBe(200);

// Request 3: Rate Limited
const response3 = await app.server.inject({
method: 'GET',
url: '/health',
});
expect(response3.statusCode).toBe(429);

const body = JSON.parse(response3.payload);
expect(body.success).toBe(false);
expect(body.error).toBeDefined();
expect(body.error.code).toBe('RATE_LIMIT_EXCEEDED');
expect(body.error.message).toContain('Rate limit exceeded');
});
});
Loading