security: harden production configuration and routes
Run Tests on Branches / Detect Changes (push) Successful in 12s
Run Tests on Branches / Frontend Tests (push) Successful in 2m12s
Run Tests on Branches / Frontend Mobile Tests (push) Has been skipped
Run Tests on Branches / Parapharmacy API Tests (push) Successful in 2m2s
Run Tests on Branches / PIP Platform Tests (push) Has been skipped
Run Tests on Branches / Backend Tests (push) Successful in 2m8s
Run Tests on Branches / Detect Changes (push) Successful in 12s
Run Tests on Branches / Frontend Tests (push) Successful in 2m12s
Run Tests on Branches / Frontend Mobile Tests (push) Has been skipped
Run Tests on Branches / Parapharmacy API Tests (push) Successful in 2m2s
Run Tests on Branches / PIP Platform Tests (push) Has been skipped
Run Tests on Branches / Backend Tests (push) Successful in 2m8s
This commit is contained in:
@@ -8,6 +8,10 @@ MONGODB_URI=mongodb://localhost:27017/parapharmacy
|
||||
# CORS
|
||||
CORS_ORIGIN=http://localhost:3000
|
||||
|
||||
# Internal credentials (generate unique random values outside local tests)
|
||||
INGEST_API_KEY=dev-ingest-key-change-me
|
||||
ADMIN_API_KEY=dev-admin-key-change-me
|
||||
|
||||
# Rate Limiting
|
||||
RATE_LIMIT_WINDOW_MS=60000
|
||||
RATE_LIMIT_MAX=100
|
||||
|
||||
@@ -30,8 +30,8 @@ ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium
|
||||
# Copy package files
|
||||
COPY apps/parapharmacy-api/package*.json ./
|
||||
|
||||
# Install dependencies (production only)
|
||||
RUN npm install --omit=dev
|
||||
# Install dependencies from the committed lockfile (production only)
|
||||
RUN npm ci --omit=dev
|
||||
|
||||
# Copy source code
|
||||
COPY apps/parapharmacy-api/ .
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { jest } from '@jest/globals'
|
||||
|
||||
process.env.NODE_ENV = 'test'
|
||||
process.env.INGEST_API_KEY = 'ingest-test-key'
|
||||
process.env.ADMIN_API_KEY = 'admin-test-key'
|
||||
|
||||
jest.unstable_mockModule('../src/models/Product.js', () => ({
|
||||
default: {
|
||||
search: jest.fn(async () => ({ results: [], total: 0, page: 1, pages: 0 })),
|
||||
distinct: jest.fn(async () => []),
|
||||
find: jest.fn(() => ({ sort: () => ({ skip: () => ({ limit: () => ({ lean: async () => [] }) }) }) })),
|
||||
countDocuments: jest.fn(async () => 0),
|
||||
},
|
||||
}))
|
||||
|
||||
jest.unstable_mockModule('../src/scraper.js', () => ({
|
||||
scrapeAll: jest.fn(async () => ({ total: 0 })),
|
||||
}))
|
||||
|
||||
const { default: supertest } = await import('supertest')
|
||||
const { default: app } = await import('../src/server.js')
|
||||
|
||||
describe('parapharmacy security', () => {
|
||||
test('keeps public product search available without credentials', async () => {
|
||||
const res = await supertest(app).get('/api/products/search?q=cream')
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
|
||||
test.each(['/api/products', '/api/products/bulk', '/api/scrape'])(
|
||||
'rejects unauthenticated mutation route %s',
|
||||
async (path) => {
|
||||
const res = await supertest(app).post(path).send({})
|
||||
expect(res.status).toBe(401)
|
||||
},
|
||||
)
|
||||
|
||||
test('accepts a valid ingest key for product creation', async () => {
|
||||
const res = await supertest(app)
|
||||
.post('/api/products')
|
||||
.set('Authorization', 'Bearer ingest-test-key')
|
||||
.send({})
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
test('requires a separate admin key for product deletion', async () => {
|
||||
const res = await supertest(app)
|
||||
.delete('/api/products/507f1f77bcf86cd799439011')
|
||||
.set('Authorization', 'Bearer ingest-test-key')
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
|
||||
test('does not expose Swagger in production', async () => {
|
||||
const original = process.env.NODE_ENV
|
||||
process.env.NODE_ENV = 'production'
|
||||
const res = await supertest(app).get('/api/docs')
|
||||
process.env.NODE_ENV = original
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,28 @@
|
||||
import crypto from 'crypto';
|
||||
|
||||
function readPresentedKey(req) {
|
||||
const authorization = req.get('authorization');
|
||||
if (authorization?.startsWith('Bearer ')) return authorization.slice(7);
|
||||
return req.get('x-service-key');
|
||||
}
|
||||
|
||||
export function requireServiceKey(environmentVariable) {
|
||||
return (req, res, next) => {
|
||||
const expected = process.env[environmentVariable];
|
||||
const supplied = readPresentedKey(req);
|
||||
|
||||
if (!expected) {
|
||||
return res.status(503).json({ error: 'Service authentication is not configured' });
|
||||
}
|
||||
|
||||
if (!supplied) return res.status(401).json({ error: 'Authentication required' });
|
||||
|
||||
const suppliedBuffer = Buffer.from(supplied);
|
||||
const expectedBuffer = Buffer.from(expected);
|
||||
const valid = suppliedBuffer.length === expectedBuffer.length
|
||||
&& crypto.timingSafeEqual(suppliedBuffer, expectedBuffer);
|
||||
|
||||
if (!valid) return res.status(403).json({ error: 'Invalid service credentials' });
|
||||
return next();
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Router } from 'express';
|
||||
import Product from '../models/Product.js';
|
||||
import { requireServiceKey } from '../middleware/service-auth.js';
|
||||
|
||||
const router = Router();
|
||||
|
||||
@@ -208,7 +209,7 @@ router.get('/:id', async (req, res) => {
|
||||
* 201:
|
||||
* description: Product created/updated
|
||||
*/
|
||||
router.post('/', async (req, res) => {
|
||||
router.post('/', requireServiceKey('INGEST_API_KEY'), async (req, res) => {
|
||||
try {
|
||||
const {
|
||||
name,
|
||||
@@ -277,13 +278,16 @@ router.post('/', async (req, res) => {
|
||||
* 200:
|
||||
* description: Upsert results
|
||||
*/
|
||||
router.post('/bulk', async (req, res) => {
|
||||
router.post('/bulk', requireServiceKey('INGEST_API_KEY'), async (req, res) => {
|
||||
try {
|
||||
const { products } = req.body;
|
||||
|
||||
if (!Array.isArray(products)) {
|
||||
return res.status(400).json({ error: 'products must be an array' });
|
||||
}
|
||||
if (products.length > 100) {
|
||||
return res.status(413).json({ error: 'products exceeds the maximum batch size of 100' });
|
||||
}
|
||||
|
||||
const results = {
|
||||
created: 0,
|
||||
@@ -337,7 +341,7 @@ router.post('/bulk', async (req, res) => {
|
||||
* 404:
|
||||
* description: Product not found
|
||||
*/
|
||||
router.put('/:id', async (req, res) => {
|
||||
router.put('/:id', requireServiceKey('ADMIN_API_KEY'), async (req, res) => {
|
||||
try {
|
||||
const product = await Product.findByIdAndUpdate(
|
||||
req.params.id,
|
||||
@@ -374,7 +378,7 @@ router.put('/:id', async (req, res) => {
|
||||
* 404:
|
||||
* description: Product not found
|
||||
*/
|
||||
router.delete('/:id', async (req, res) => {
|
||||
router.delete('/:id', requireServiceKey('ADMIN_API_KEY'), async (req, res) => {
|
||||
try {
|
||||
const product = await Product.findByIdAndDelete(req.params.id);
|
||||
|
||||
|
||||
@@ -1,12 +1,23 @@
|
||||
import { Router } from 'express';
|
||||
import { scrapeAll } from '../scraper.js';
|
||||
import rateLimit from 'express-rate-limit';
|
||||
import { requireServiceKey } from '../middleware/service-auth.js';
|
||||
|
||||
const router = Router();
|
||||
const scrapeLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000,
|
||||
max: 5,
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
});
|
||||
|
||||
// Trigger scraping
|
||||
router.post('/scrape', async (req, res) => {
|
||||
router.post('/scrape', scrapeLimiter, requireServiceKey('INGEST_API_KEY'), async (req, res) => {
|
||||
try {
|
||||
const { queries = ['crema hidratante'], sources = ['promofarma'] } = req.body;
|
||||
if (!Array.isArray(queries) || !Array.isArray(sources) || queries.length > 20 || sources.length > 10) {
|
||||
return res.status(400).json({ error: 'queries and sources must be bounded arrays' });
|
||||
}
|
||||
|
||||
console.log('[Scraper] Starting scrape...');
|
||||
console.log(`[Scraper] Queries: ${queries.join(', ')}`);
|
||||
@@ -19,7 +30,7 @@ router.post('/scrape', async (req, res) => {
|
||||
res.json(result);
|
||||
} catch (error) {
|
||||
console.error('[Scraper] Error:', error.message);
|
||||
res.status(500).json({ error: 'Scraping failed', message: error.message });
|
||||
res.status(500).json({ error: 'Scraping failed' });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ const swaggerSpec = swaggerJsdoc(swaggerOptions);
|
||||
|
||||
// Middleware
|
||||
app.use(cors(config.cors));
|
||||
app.use(express.json({ limit: '10mb' }));
|
||||
app.use(express.json({ limit: '1mb' }));
|
||||
app.use(morgan('combined'));
|
||||
|
||||
// Rate limiting
|
||||
@@ -66,11 +66,13 @@ const limiter = rateLimit({
|
||||
app.use(limiter);
|
||||
|
||||
// Swagger UI
|
||||
app.use('/api/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec, {
|
||||
explorer: true,
|
||||
customCss: '.swagger-ui .topbar { display: none }',
|
||||
customSiteTitle: 'FarmaFinder Parapharmacy API',
|
||||
}));
|
||||
if (!['production', 'test'].includes(process.env.NODE_ENV)) {
|
||||
app.use('/api/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec, {
|
||||
explorer: true,
|
||||
customCss: '.swagger-ui .topbar { display: none }',
|
||||
customSiteTitle: 'FarmaFinder Parapharmacy API',
|
||||
}));
|
||||
}
|
||||
|
||||
// Routes
|
||||
app.use('/api/products', productsRouter);
|
||||
@@ -131,6 +133,6 @@ process.on('SIGINT', async () => {
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
start();
|
||||
if (process.env.NODE_ENV !== 'test') start();
|
||||
|
||||
export default app;
|
||||
|
||||
Reference in New Issue
Block a user