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:
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, test } from '@jest/globals'
|
||||
import { validateProductionEnv } from '../src/config/required-env.js'
|
||||
|
||||
describe('validateProductionEnv', () => {
|
||||
test('rejects a missing production session secret', () => {
|
||||
expect(() => validateProductionEnv({
|
||||
NODE_ENV: 'production',
|
||||
CORS_ORIGIN: 'https://app.example.com',
|
||||
PG_URL: 'postgres://app:password@db/app',
|
||||
})).toThrow(/SESSION_SECRET/i)
|
||||
})
|
||||
|
||||
test('rejects placeholder production configuration', () => {
|
||||
expect(() => validateProductionEnv({
|
||||
NODE_ENV: 'production',
|
||||
SESSION_SECRET: 'farma-clic-secret-key-change-in-production',
|
||||
CORS_ORIGIN: 'http://localhost:3000',
|
||||
PG_URL: 'postgres://app:password@db/app',
|
||||
})).toThrow(/placeholder|production/i)
|
||||
})
|
||||
|
||||
test('accepts complete non-placeholder production configuration', () => {
|
||||
expect(() => validateProductionEnv({
|
||||
NODE_ENV: 'production',
|
||||
SESSION_SECRET: 'a-test-only-long-session-secret',
|
||||
CORS_ORIGIN: 'https://app.example.com',
|
||||
PG_URL: 'postgres://app:password@db/app',
|
||||
})).not.toThrow()
|
||||
})
|
||||
})
|
||||
@@ -26,6 +26,9 @@ import multer from 'multer';
|
||||
import { searchMedicines, getMedicineDetails, searchOTC } from './cima-service.js';
|
||||
import { runFarmaciaWebhookImport, DEFAULT_FARMACIAS_WEBHOOK, importPharmaciesFromRows } from './farmacias-webhook-import.js';
|
||||
import { fetchPharmaciesExternal } from '../API/index.js';
|
||||
import { validateProductionEnv } from './src/config/required-env.js';
|
||||
|
||||
validateProductionEnv();
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
@@ -81,11 +84,11 @@ if (PG_URL) {
|
||||
}
|
||||
|
||||
const sessionConfig = {
|
||||
secret: process.env.SESSION_SECRET || 'farma-clic-secret-key-change-in-production',
|
||||
secret: process.env.SESSION_SECRET || (process.env.NODE_ENV === 'test' ? 'test-only-session-secret' : undefined),
|
||||
resave: false,
|
||||
saveUninitialized: false,
|
||||
cookie: {
|
||||
secure: process.env.COOKIE_SECURE === 'true',
|
||||
secure: process.env.NODE_ENV === 'production' || process.env.COOKIE_SECURE === 'true',
|
||||
sameSite: 'lax',
|
||||
httpOnly: true,
|
||||
maxAge: 24 * 60 * 60 * 1000 // 24 hours
|
||||
@@ -2648,4 +2651,3 @@ if (process.env.NODE_ENV !== 'test') {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
const PLACEHOLDERS = new Set([
|
||||
'',
|
||||
'change-me-in-production',
|
||||
'farma-clic-secret-key-change-in-production',
|
||||
'replace-me',
|
||||
'dev-ingest-key-change-me',
|
||||
])
|
||||
|
||||
export function validateProductionEnv(env = process.env) {
|
||||
if (env.NODE_ENV !== 'production') return
|
||||
|
||||
const required = [
|
||||
['SESSION_SECRET', env.SESSION_SECRET],
|
||||
['CORS_ORIGIN', env.CORS_ORIGIN],
|
||||
]
|
||||
|
||||
for (const [name, value] of required) {
|
||||
if (!value || PLACEHOLDERS.has(value)) {
|
||||
throw new Error(`${name} must be set to a non-placeholder value in production`)
|
||||
}
|
||||
}
|
||||
|
||||
if (env.CORS_ORIGIN.includes('localhost') || env.CORS_ORIGIN.includes('127.0.0.1')) {
|
||||
throw new Error('CORS_ORIGIN must not point to localhost in production')
|
||||
}
|
||||
|
||||
if (!env.PG_URL && (!env.PG_PASSWORD || PLACEHOLDERS.has(env.PG_PASSWORD))) {
|
||||
throw new Error('PG_URL or PG_PASSWORD must be set to a non-placeholder value in production')
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,14 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_tokens off;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://backend:3001;
|
||||
proxy_set_header Host $host;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
APP_NAME=PIP - Pharmacy Integration Platform
|
||||
APP_VERSION=0.1.0
|
||||
DEBUG=false
|
||||
NODE_ENV=development
|
||||
|
||||
DATABASE_URL=postgresql+asyncpg://pip:pip-secret@localhost:5432/pip
|
||||
DATABASE_POOL_SIZE=20
|
||||
|
||||
@@ -7,14 +7,14 @@ services:
|
||||
ports:
|
||||
- "8000:8000"
|
||||
environment:
|
||||
DATABASE_URL: postgresql+asyncpg://pip:${PG_PASSWORD:-pip-secret}@postgres:5432/pip
|
||||
DATABASE_URL: postgresql+asyncpg://pip:${PG_PASSWORD:?PG_PASSWORD must be set}@postgres:5432/pip
|
||||
REDIS_URL: redis://redis:6379/0
|
||||
RABBITMQ_URL: amqp://pip:${RABBITMQ_PASSWORD:-pip-secret}@rabbitmq:5672/pip
|
||||
JWT_SECRET_KEY: ${JWT_SECRET_KEY:-change-me-in-production}
|
||||
RABBITMQ_URL: amqp://pip:${RABBITMQ_PASSWORD:?RABBITMQ_PASSWORD must be set}@rabbitmq:5672/pip
|
||||
JWT_SECRET_KEY: ${JWT_SECRET_KEY:?JWT_SECRET_KEY must be set}
|
||||
NODE_ENV: production
|
||||
LOG_LEVEL: INFO
|
||||
LOG_JSON_FORMAT: "true"
|
||||
CORS_ORIGINS: '["*"]'
|
||||
CORS_ORIGINS: ${CORS_ORIGINS:?CORS_ORIGINS must be set}
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: http://host.docker.internal:4317
|
||||
OTEL_TRACES_ENABLED: "true"
|
||||
depends_on:
|
||||
@@ -45,9 +45,7 @@ services:
|
||||
environment:
|
||||
POSTGRES_DB: pip
|
||||
POSTGRES_USER: pip
|
||||
POSTGRES_PASSWORD: ${PG_PASSWORD:-pip-secret}
|
||||
ports:
|
||||
- "5432:5432"
|
||||
POSTGRES_PASSWORD: ${PG_PASSWORD:?PG_PASSWORD must be set}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
@@ -73,8 +71,6 @@ services:
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "6380:6379"
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
healthcheck:
|
||||
@@ -94,11 +90,8 @@ services:
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
RABBITMQ_DEFAULT_USER: pip
|
||||
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD:-pip-secret}
|
||||
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD:?RABBITMQ_PASSWORD must be set}
|
||||
RABBITMQ_DEFAULT_VHOST: pip
|
||||
ports:
|
||||
- "5672:5672"
|
||||
- "15672:15672"
|
||||
volumes:
|
||||
- rabbitmq_data:/var/lib/rabbitmq
|
||||
healthcheck:
|
||||
@@ -111,4 +104,4 @@ services:
|
||||
volumes:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
rabbitmq_data:
|
||||
rabbitmq_data:
|
||||
|
||||
@@ -7,14 +7,14 @@ services:
|
||||
ports:
|
||||
- "8000:8000"
|
||||
environment:
|
||||
DATABASE_URL: postgresql+asyncpg://pip:${PG_PASSWORD:-pip-secret}@postgres:5432/pip
|
||||
DATABASE_URL: postgresql+asyncpg://pip:${PG_PASSWORD:?PG_PASSWORD must be set}@postgres:5432/pip
|
||||
REDIS_URL: redis://redis:6379/0
|
||||
RABBITMQ_URL: amqp://pip:${RABBITMQ_PASSWORD:-pip-secret}@rabbitmq:5672/pip
|
||||
JWT_SECRET_KEY: ${JWT_SECRET_KEY:-change-me-in-production}
|
||||
RABBITMQ_URL: amqp://pip:${RABBITMQ_PASSWORD:?RABBITMQ_PASSWORD must be set}@rabbitmq:5672/pip
|
||||
JWT_SECRET_KEY: ${JWT_SECRET_KEY:?JWT_SECRET_KEY must be set}
|
||||
NODE_ENV: production
|
||||
LOG_LEVEL: INFO
|
||||
LOG_JSON_FORMAT: "true"
|
||||
CORS_ORIGINS: '["*"]'
|
||||
CORS_ORIGINS: ${CORS_ORIGINS:?CORS_ORIGINS must be set}
|
||||
# Re-routed to the shared Grafana Alloy collector on srv84-macos.
|
||||
# host.docker.internal resolves to the Docker host gateway from
|
||||
# inside the container — works because this stack runs on the same
|
||||
@@ -53,9 +53,7 @@ services:
|
||||
environment:
|
||||
POSTGRES_DB: pip
|
||||
POSTGRES_USER: pip
|
||||
POSTGRES_PASSWORD: ${PG_PASSWORD:-pip-secret}
|
||||
ports:
|
||||
- "5432:5432"
|
||||
POSTGRES_PASSWORD: ${PG_PASSWORD:?PG_PASSWORD must be set}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
@@ -81,8 +79,6 @@ services:
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "6380:6379"
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
healthcheck:
|
||||
@@ -102,11 +98,8 @@ services:
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
RABBITMQ_DEFAULT_USER: pip
|
||||
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD:-pip-secret}
|
||||
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD:?RABBITMQ_PASSWORD must be set}
|
||||
RABBITMQ_DEFAULT_VHOST: pip
|
||||
ports:
|
||||
- "5672:5672"
|
||||
- "15672:15672"
|
||||
volumes:
|
||||
- rabbitmq_data:/var/lib/rabbitmq
|
||||
healthcheck:
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from pydantic import model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
@@ -12,6 +13,7 @@ class Settings(BaseSettings):
|
||||
APP_NAME: str = "PIP - Pharmacy Integration Platform"
|
||||
APP_VERSION: str = "0.1.0"
|
||||
DEBUG: bool = False
|
||||
NODE_ENV: str = "development"
|
||||
|
||||
DATABASE_URL: str = "postgresql+asyncpg://pip:pip@localhost:5432/pip"
|
||||
DATABASE_POOL_SIZE: int = 20
|
||||
@@ -50,6 +52,23 @@ class Settings(BaseSettings):
|
||||
|
||||
HEALTH_CHECK_CACHE_TTL: int = 10
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_production_security(self):
|
||||
if self.NODE_ENV.lower() != "production":
|
||||
return self
|
||||
|
||||
if self.JWT_SECRET_KEY == "change-me-in-production":
|
||||
raise ValueError("JWT_SECRET_KEY must be changed in production")
|
||||
|
||||
default_credentials = ("pip:pip@", "pip-secret")
|
||||
if any(value in self.DATABASE_URL or value in self.RABBITMQ_URL for value in default_credentials):
|
||||
raise ValueError("default database or broker credentials are not allowed in production")
|
||||
|
||||
if self.CORS_ALLOW_CREDENTIALS and "*" in self.CORS_ORIGINS:
|
||||
raise ValueError("wildcard CORS_ORIGINS are not allowed with credentials in production")
|
||||
|
||||
return self
|
||||
|
||||
@property
|
||||
def DATABASE_URL_SYNC(self) -> str:
|
||||
return self.DATABASE_URL.replace("+asyncpg", "+psycopg2", 1)
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import pytest
|
||||
|
||||
from src.infrastructure.config.settings import Settings
|
||||
|
||||
|
||||
def test_production_rejects_placeholder_jwt_secret():
|
||||
with pytest.raises(ValueError, match="JWT_SECRET_KEY"):
|
||||
Settings(
|
||||
NODE_ENV="production",
|
||||
JWT_SECRET_KEY="change-me-in-production",
|
||||
_env_file=None,
|
||||
)
|
||||
|
||||
|
||||
def test_production_rejects_default_database_and_broker_credentials():
|
||||
with pytest.raises(ValueError, match="credentials"):
|
||||
Settings(
|
||||
NODE_ENV="production",
|
||||
JWT_SECRET_KEY="a-real-test-secret",
|
||||
DATABASE_URL="postgresql+asyncpg://pip:pip@localhost:5432/pip",
|
||||
RABBITMQ_URL="amqp://pip:pip@localhost:5672/pip",
|
||||
_env_file=None,
|
||||
)
|
||||
|
||||
|
||||
def test_production_rejects_wildcard_credentialed_cors():
|
||||
with pytest.raises(ValueError, match="CORS"):
|
||||
Settings(
|
||||
NODE_ENV="production",
|
||||
JWT_SECRET_KEY="a-real-test-secret",
|
||||
DATABASE_URL="postgresql+asyncpg://pip:real-password@db:5432/pip",
|
||||
RABBITMQ_URL="amqp://pip:real-password@rabbitmq:5672/pip",
|
||||
CORS_ORIGINS=["*"],
|
||||
CORS_ALLOW_CREDENTIALS=True,
|
||||
_env_file=None,
|
||||
)
|
||||
|
||||
|
||||
def test_development_keeps_local_defaults_usable():
|
||||
settings = Settings(_env_file=None)
|
||||
assert settings.NODE_ENV == "development"
|
||||
Reference in New Issue
Block a user