-
Notifications
You must be signed in to change notification settings - Fork 200
Feat/security hardening middleware suite #487
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
1c54c53
b0844df
ab7d384
5ce876d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| # ======================== REQUIRED VARIABLES ======================== | ||
| # Server Configuration (REQUIRED) | ||
| PORT=5000 | ||
| NODE_ENV=development | ||
|
|
||
| # Database (REQUIRED) | ||
| MONGO_URI=mongodb://localhost:27017/github_tracker | ||
|
|
||
| # Security (REQUIRED) | ||
| SESSION_SECRET=your-super-secret-random-key-change-in-production | ||
| CLIENT_URL=http://localhost:5173 | ||
|
|
||
| # ======================== OPTIONAL VARIABLES ======================== | ||
| # Cookie Configuration (Optional - uses localhost if not set) | ||
| COOKIE_DOMAIN=localhost | ||
|
|
||
| # Logging (Optional - defaults to 'info' in production, 'debug' in development) | ||
| LOG_LEVEL=debug |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| const requireAuth = (req, res, next) => { | ||
| if (!req.isAuthenticated()) { | ||
| return res.status(401).json({ | ||
| success: false, | ||
| message: 'Authentication required' | ||
| }); | ||
| } | ||
| next(); | ||
| }; | ||
|
|
||
| module.exports = { requireAuth }; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| const logger = require('../logger'); | ||
|
|
||
| const validateEnv = () => { | ||
| const requiredVars = [ | ||
| 'MONGO_URI', | ||
| 'PORT', | ||
| 'SESSION_SECRET', | ||
| 'CLIENT_URL', | ||
| 'NODE_ENV', | ||
| ]; | ||
|
|
||
| const missingVars = requiredVars.filter(v => !process.env[v]); | ||
|
|
||
| if (missingVars.length > 0) { | ||
| logger.error(`Missing required environment variables: ${missingVars.join(', ')}`); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| logger.info('Environment variables validated ✓'); | ||
| }; | ||
|
|
||
| module.exports = { validateEnv }; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| const logger = require('../logger'); | ||
|
|
||
| const errorHandler = (err, req, res, next) => { | ||
| const status = err.status || err.statusCode || 500; | ||
| const message = process.env.NODE_ENV === 'production' | ||
| ? 'Internal Server Error' | ||
| : err.message; | ||
|
|
||
| logger.error(`[${req.method} ${req.path}] Error: ${err.message}`, err); | ||
|
|
||
| res.status(status).json({ | ||
| success: false, | ||
| message, | ||
| ...(process.env.NODE_ENV !== 'production' && { stack: err.stack }), | ||
| }); | ||
| }; | ||
|
|
||
| const asyncHandler = (fn) => (req, res, next) => { | ||
| Promise.resolve(fn(req, res, next)).catch(next); | ||
| }; | ||
|
|
||
| module.exports = { errorHandler, asyncHandler }; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| const morgan = require('morgan'); | ||
| const logger = require('../logger'); | ||
|
|
||
| const morganStream = { | ||
| write: (message) => logger.info(message.trim()), | ||
| }; | ||
|
|
||
| const httpLogger = morgan( | ||
| ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" - :response-time ms', | ||
| { stream: morganStream } | ||
| ); | ||
|
|
||
| module.exports = httpLogger; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| const helmet = require('helmet'); | ||
|
|
||
| const securityHeaders = helmet({ | ||
| contentSecurityPolicy: { | ||
| directives: { | ||
| defaultSrc: ["'self'"], | ||
| styleSrc: ["'self'", "'nonce-randomvalue'"], | ||
| scriptSrc: ["'self'"], | ||
| imgSrc: ["'self'", 'data:', 'https://api.github.com', 'https://avatars.githubusercontent.com'], | ||
| connectSrc: ["'self'", 'https://api.github.com'], | ||
| fontSrc: ["'self'", 'https://fonts.googleapis.com'], | ||
| }, | ||
| }, | ||
| hsts: { | ||
| maxAge: 31536000, // 1 year | ||
| includeSubDomains: true, | ||
| preload: true, | ||
| }, | ||
| frameguard: { action: 'deny' }, | ||
| noSniff: true, | ||
| referrerPolicy: { policy: 'strict-origin-when-cross-origin' }, | ||
| }); | ||
|
|
||
| module.exports = securityHeaders; |
| Original file line number | Diff line number | Diff line change | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| @@ -1,18 +1,31 @@ | ||||||||||
| const express = require('express'); | ||||||||||
| const mongoose = require('mongoose'); | ||||||||||
| const session = require('express-session'); | ||||||||||
| const MongoStore = require('connect-mongo').default; | ||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧩 Analysis chain🌐 Web query:
💡 Result: For connect-mongo v6.0.0, the CommonJS require pattern is: const session = require('express-session'); const { MongoStore } = require('connect-mongo'); app.use(session({ secret: 'foo', store: MongoStore.create(options) })); This is the documented CJS example for connect-mongo (including v6.x) showing destructuring { MongoStore } from 'connect-mongo' and using MongoStore.create(options) for express-session’s store. [1][2] If you’re specifically asking about the older factory style (require('connect-mongo')(session)), that’s from older versions and does not match the current documented v6 pattern. [3] Note: connect-mongo v6.0.0 also supports an ESM import style (for contrast) like: import session from 'express-session' import MongoStore from 'connect-mongo' app.use(session({ secret: 'foo', store: MongoStore.create(options) })); [1][2] Citations:
Fix connect-mongo v6 CommonJS MongoStore import
🤖 Prompt for AI Agents |
||||||||||
| const passport = require('passport'); | ||||||||||
| const bodyParser = require('body-parser'); | ||||||||||
| const rateLimit = require('express-rate-limit'); | ||||||||||
| require('dotenv').config(); | ||||||||||
| const cors = require('cors'); | ||||||||||
|
|
||||||||||
| // Passport configuration | ||||||||||
| require('./config/passportConfig'); | ||||||||||
|
|
||||||||||
| const logger = require('./logger'); | ||||||||||
| const securityHeaders = require('./middleware/security'); | ||||||||||
| const { validateEnv } = require('./middleware/envValidator'); | ||||||||||
| const httpLogger = require('./middleware/logger'); | ||||||||||
| const { errorHandler } = require('./middleware/errorHandler'); | ||||||||||
| const { requireAuth } = require('./middleware/auth'); | ||||||||||
|
|
||||||||||
| // Validate environment variables | ||||||||||
| validateEnv(); | ||||||||||
|
|
||||||||||
| const app = express(); | ||||||||||
|
|
||||||||||
| app.use(securityHeaders); | ||||||||||
| app.use(httpLogger); | ||||||||||
|
|
||||||||||
| // CORS configuration | ||||||||||
| const allowedOrigins = ['http://localhost:5173', 'https://github-spy.etlify.app']; | ||||||||||
| app.use(cors({ | ||||||||||
|
|
@@ -27,27 +40,94 @@ app.use(cors({ | |||||||||
| })); | ||||||||||
|
|
||||||||||
| // Middleware | ||||||||||
| app.use(bodyParser.json()); | ||||||||||
| app.use(bodyParser.json({ limit: '10mb' })); | ||||||||||
| app.use(bodyParser.urlencoded({ limit: '10mb', extended: true })); | ||||||||||
|
Comment on lines
+43
to
+44
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 10MB body size limit may enable DoS attacks. The request body limit of
Unless there's a specific requirement for large payloads (e.g., data imports), consider:
🔒 Recommended limit for typical APIs // Middleware
-app.use(bodyParser.json({ limit: '10mb' }));
-app.use(bodyParser.urlencoded({ limit: '10mb', extended: true }));
+app.use(bodyParser.json({ limit: '1mb' })); // Adjust based on actual requirements
+app.use(bodyParser.urlencoded({ limit: '1mb', extended: true }));📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||
|
|
||||||||||
| app.use(session({ | ||||||||||
| secret: process.env.SESSION_SECRET, | ||||||||||
| resave: false, | ||||||||||
| saveUninitialized: false, | ||||||||||
| store: MongoStore.create({ | ||||||||||
| mongoUrl: process.env.MONGO_URI, | ||||||||||
| touchAfter: 24 * 3600, | ||||||||||
| }), | ||||||||||
| cookie: { | ||||||||||
| httpOnly: true, | ||||||||||
| secure: process.env.NODE_ENV === 'production', | ||||||||||
| sameSite: 'strict', | ||||||||||
| maxAge: 1000 * 60 * 30, | ||||||||||
| domain: process.env.COOKIE_DOMAIN || undefined, | ||||||||||
| } | ||||||||||
| })); | ||||||||||
|
|
||||||||||
| app.use(passport.initialize()); | ||||||||||
| app.use(passport.session()); | ||||||||||
|
|
||||||||||
| // Rate Limiting | ||||||||||
| const authLimiter = rateLimit({ | ||||||||||
| windowMs: 15 * 60 * 1000, | ||||||||||
| max: 10, | ||||||||||
| standardHeaders: true, | ||||||||||
| legacyHeaders: false, | ||||||||||
| message: { message: 'Too many attempts, please try again after 15 minutes.' }, | ||||||||||
| skipSuccessfulRequests: true, | ||||||||||
| // keyGenerator: (req) => req.ip, // Rate limit by IP address | ||||||||||
| }); | ||||||||||
|
|
||||||||||
| // General API: 100 requests per 15 minutes | ||||||||||
| const generalLimiter = rateLimit({ | ||||||||||
| windowMs: 15 * 60 * 1000, | ||||||||||
| max: 100, | ||||||||||
| standardHeaders: true, | ||||||||||
| legacyHeaders: false, | ||||||||||
| skip: (req) => req.isAuthenticated(), // Skip rate limiting for authenticated users | ||||||||||
| }) | ||||||||||
|
|
||||||||||
| app.use('/api/auth', authLimiter); | ||||||||||
| app.use('/api', generalLimiter); | ||||||||||
|
Comment on lines
+86
to
+87
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
# Test rate limiting behavior on auth endpoints
echo "Testing auth rate limit with 12 failed login attempts..."
for i in {1..12}; do
echo "Request $i:"
curl -X POST http://localhost:5000/api/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"test@example.com","password":"wrong"}' \
-w "\nHTTP Status: %{http_code}\n" \
-s | jq -c '.message' 2>/dev/null || echo "(parse error)"
if [ $i -eq 10 ]; then
echo -e "\n--- Reached authLimiter max (10), next requests should be blocked ---\n"
fi
sleep 1
done
echo -e "\n=== Check which limiter blocked the requests ==="Repository: GitMetricsLab/github_tracker Length of output: 554 Avoid stacking rate limiters on app.use('/api/auth', authLimiter);
app.use('/api', generalLimiter);So unauthenticated auth calls are limited by both The proposed curl/jq verification didn’t show limiter outcomes because 🤖 Prompt for AI Agents |
||||||||||
|
|
||||||||||
| // Health Check | ||||||||||
| app.get('/api/health', (req,res) => { | ||||||||||
| res.status(200).json({ status: 'ok', timestamp: new Date().toISOString() }); | ||||||||||
| }); | ||||||||||
|
|
||||||||||
| // Routes | ||||||||||
| const authRoutes = require('./routes/auth'); | ||||||||||
|
|
||||||||||
| app.use('/api/auth', authRoutes); | ||||||||||
|
|
||||||||||
|
|
||||||||||
| // 404 Handler | ||||||||||
| app.use((req, res) => { | ||||||||||
| res.status(404).json({ success: false, message: 'Route not found' }); | ||||||||||
| }); | ||||||||||
|
|
||||||||||
| // Global Error Handler | ||||||||||
| app.use(errorHandler); | ||||||||||
|
|
||||||||||
| module.exports = app; | ||||||||||
|
|
||||||||||
| // Connect to MongoDB | ||||||||||
| mongoose.connect(process.env.MONGO_URI, {}).then(() => { | ||||||||||
| mongoose.connect(process.env.MONGO_URI, { | ||||||||||
| maxPoolSize: 10, | ||||||||||
| minPoolSize: 5, | ||||||||||
| waitQueueTimeoutMS: 10000, | ||||||||||
| }).then(() => { | ||||||||||
| logger.info('Connected to MongoDB'); | ||||||||||
|
|
||||||||||
| const PORT = process.env.PORT || 5000; | ||||||||||
| app.listen(PORT, () => { | ||||||||||
| logger.info(`Server running on port ${PORT}`); | ||||||||||
| app.listen(process.env.PORT, () => { | ||||||||||
| logger.info(`Server running on port ${process.env.PORT}`); | ||||||||||
| logger.info(`✓ Environment: ${process.env.NODE_ENV}`); | ||||||||||
| }); | ||||||||||
| }).catch((err) => { | ||||||||||
| logger.error('MongoDB connection error', err); | ||||||||||
| process.exit(1); | ||||||||||
| }); | ||||||||||
|
|
||||||||||
| // Graceful shutdown | ||||||||||
| process.on('SIGTERM', () => { | ||||||||||
| logger.info('SIGTERM received, shutting down gracefully'); | ||||||||||
| mongoose.connection.close(false, () => { | ||||||||||
| logger.info('MongoDB connection closed'); | ||||||||||
| process.exit(0); | ||||||||||
| }) | ||||||||||
| }) | ||||||||||
|
Comment on lines
+127
to
+133
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win Graceful shutdown should also close the HTTP server. The SIGTERM handler closes the MongoDB connection but doesn't close the Express server. This means new HTTP requests may still be accepted during shutdown, which could lead to:
🔄 Recommended graceful shutdown sequence+let server;
+
// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI, {
maxPoolSize: 10,
minPoolSize: 5,
waitQueueTimeoutMS: 10000,
}).then(() => {
logger.info('Connected to MongoDB');
- app.listen(process.env.PORT, () => {
+ server = app.listen(process.env.PORT, () => {
logger.info(`Server running on port ${process.env.PORT}`);
logger.info(`✓ Environment: ${process.env.NODE_ENV}`);
});
}).catch((err) => {
logger.error('MongoDB connection error', err);
process.exit(1);
});
// Graceful shutdown
process.on('SIGTERM', () => {
logger.info('SIGTERM received, shutting down gracefully');
- mongoose.connection.close(false, () => {
- logger.info('MongoDB connection closed');
- process.exit(0);
- })
+ server.close(() => {
+ logger.info('HTTP server closed');
+ mongoose.connection.close(false, () => {
+ logger.info('MongoDB connection closed');
+ process.exit(0);
+ });
+ });
})🤖 Prompt for AI Agents |
||||||||||
Uh oh!
There was an error while loading. Please reload this page.