Skip to content
Draft
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
4 changes: 4 additions & 0 deletions .jules/sentinel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
## 2026-01-21 - Fastify Rate Limiting & Dependency Conflict
**Vulnerability:** Rate limiting was completely disabled (commented out) in production code, exposing the API to DoS and brute-force attacks. Additionally, a major version mismatch in `@fastify/jwt` (v10 with Fastify v4) prevented the server from starting if dependencies were updated.
**Learning:** Security features commented out "for development" often make their way to production. Framework plugin version compatibility (Fastify v4 vs v5 ecosystem) can silently break applications or prevent security updates if not pinned correctly. The global error handler in Fastify can mask or transform expected error responses from security plugins like `rate-limit`.
**Prevention:** Use environment variables (e.g. `ENABLE_RATE_LIMIT=false`) instead of commenting out code. Strictly verify peer dependencies when upgrading packages. Ensure security tests verify the *actual* response structure, as global handlers may intercept plugin errors.
17 changes: 17 additions & 0 deletions backend/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"rules": {
"@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/no-unused-vars": "warn",
"no-console": "warn"
},
"env": {
"node": true,
"jest": true
}
}
9 changes: 9 additions & 0 deletions backend/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
setupFiles: ['<rootDir>/jest.setup.js'],
testMatch: ['**/__tests__/**/*.test.ts'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
},
};
41 changes: 41 additions & 0 deletions backend/jest.setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
process.env.NODE_ENV = 'test';
process.env.PORT = '3001';
process.env.DATABASE_URL = 'postgresql://test:test@localhost:5432/test';
process.env.JWT_SECRET = 'test-secret-at-least-32-chars-long-should-be-here';
process.env.LUNES_RPC_URL = 'http://localhost:9933';
process.env.CONTRACT_ADDRESS = '0x123';
process.env.PRIVATE_KEY = '0xabc';
process.env.AWS_ACCESS_KEY_ID = 'test';
process.env.AWS_SECRET_ACCESS_KEY = 'test';
process.env.AWS_BUCKET_NAME = 'test';
process.env.AWS_REGION = 'us-east-1';

// Mock Redis to prevent connection errors
jest.mock('ioredis', () => {
return jest.fn().mockImplementation(() => {
return {
get: jest.fn(),
set: jest.fn(),
del: jest.fn(),
on: jest.fn(),
quit: jest.fn(),
};
});
});

// Mock logger to avoid noise
jest.mock('./src/shared/logger', () => ({
logger: {
info: jest.fn(),
error: jest.fn(),
warn: jest.fn(),
debug: jest.fn(),
},
Logger: {
info: jest.fn(),
error: jest.fn(),
warn: jest.fn(),
debug: jest.fn(),
auth: jest.fn(),
}
}));
79 changes: 14 additions & 65 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
50 changes: 50 additions & 0 deletions backend/src/__tests__/security/rate_limit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { app } from '../../app';
import { FastifyInstance } from 'fastify';

describe('Security: Rate Limiting', () => {
let server: FastifyInstance;

beforeAll(async () => {
// Initialize the app (register middlewares and routes)
await app.initialize();
server = app.server;
});

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

it('should limit requests when exceeding the threshold', async () => {
const limit = 100; // Default limit in env.config.ts
const extraRequests = 10;
const totalRequests = limit + extraRequests;
const url = '/api/v1/auth/nonce/0x1234567890123456789012345678901234567890';

// We expect the first 'limit' requests to succeed (200)
// And the subsequent requests to fail (429) if rate limiting is enabled.

// Rate limiting is ENABLED, so we expect to hit 429 eventually.

let rateLimitTriggered = false;

for (let i = 0; i < totalRequests; i++) {
const response = await server.inject({
method: 'GET',
url,
});

if (response.statusCode === 429) {
rateLimitTriggered = true;
// Verify response structure - expecting Global Error Handler format
const body = JSON.parse(response.payload);
expect(body.success).toBe(false);
expect(body.error.code).toBe(429);
expect(body.error.message).toMatch(/Muitas tentativas/);
break;
}
}

// Assert that rate limit WAS triggered
expect(rateLimitTriggered).toBe(true);
});
});
25 changes: 13 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,18 @@ 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,
errorResponseBuilder: (request, context) => ({
code: 429,
error: 'Rate Limit Exceeded',
message: `Muitas tentativas. Tente novamente em ${Math.round(context.ttl / 1000)} segundos.`,
statusCode: 429,
expiresIn: context.ttl,
}),
});

// Swagger Documentation
if (envConfig.ENABLE_SWAGGER) {
Expand Down
Loading