This document outlines security best practices and policies for the AyurTrace project. Following these guidelines is crucial for maintaining the security and integrity of the supply chain traceability system.
- Security Vulnerabilities
- Authentication & Authorization
- Environment Variables & Secrets
- Database Security
- API Security
- Blockchain Security
- Production Deployment
- Security Checklist
If you discover a security vulnerability, please email [email protected] (or your team's security contact). Do NOT create public GitHub issues for security vulnerabilities.
Please include:
- Description of the vulnerability
- Steps to reproduce
- Potential impact
- Suggested fix (if any)
Response Timeline:
- Acknowledgment within 24 hours
- Initial assessment within 72 hours
- Fix timeline based on severity
Current Implementation:
- JWT-based authentication with role-based access control
- Token expiry: 7 days (configurable)
- Tokens stored in localStorage (client-side)
Security Recommendations:
-
Generate Strong JWT Secrets:
# Generate a 64-byte random secret node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
-
Token Storage:
- Consider using httpOnly cookies instead of localStorage for better XSS protection
- Implement refresh token mechanism for long-lived sessions
- Clear tokens on logout
-
Password Requirements:
- Minimum 8 characters
- Must include: uppercase, lowercase, number, special character
- Passwords hashed using bcryptjs
Roles:
farmer- Create and manage herb batchesmanufacturer- Process batches, add quality testsconsumer- Verify products, view supply chainadmin- Full system accessgov_admin- Government oversight and monitoring
Implementation:
// Protect routes with role authorization
router.get('/admin/dashboard',
protect,
authorize('admin', 'gov_admin'),
getDashboard
);Never commit these to version control:
JWT_SECRET= # Generate using crypto.randomBytes
MONGODB_URI= # Contains database credentials
GPS_API_KEY= # External service API keys-
Development:
- Use
.envfile (already in.gitignore) - Copy
.env.exampleto.envand fill in values - Never share
.envfile
- Use
-
Production:
- Use environment-specific secrets management:
- AWS: AWS Secrets Manager, AWS Systems Manager Parameter Store
- Azure: Azure Key Vault
- GCP: Google Secret Manager
- Kubernetes: Kubernetes Secrets
- Rotate secrets regularly (every 90 days recommended)
- Use different secrets for each environment
- Use environment-specific secrets management:
-
Docker Deployment:
# Use Docker secrets (don't put secrets in docker-compose.yml) docker secret create jwt_secret jwt_secret.txt # Or use env_file with restricted permissions chmod 600 .env.production
Current Setup:
- Connection string in environment variables
- Mongoose ODM for query sanitization
Hardening Recommendations:
-
Enable Authentication:
// Use authentication in production MONGODB_URI=mongodb://username:password@host:27017/ayurtrace?authSource=admin
-
Enable SSL/TLS:
MONGODB_URI=mongodb://username:password@host:27017/ayurtrace?ssl=true
-
Network Security:
- Use VPC/Private network
- Whitelist IP addresses
- Use MongoDB Atlas for managed security
-
Data Encryption:
- Enable encryption at rest
- Use TLS for data in transit
- Consider field-level encryption for sensitive data
-
Regular Backups:
# Automated daily backups mongodump --uri="mongodb://localhost:27017/ayurtrace" --archive=backup.gz --gzip
- Helmet.js - Security headers
- Rate Limiting - 200 requests per 15 minutes
- CORS - Configured allowed origins
- Input Sanitization - NoSQL injection prevention
- XSS Protection - Input/output sanitization
- HPP - HTTP Parameter Pollution prevention
-
API Rate Limiting (Tiered):
// Stricter limits for sensitive endpoints const authLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 5 // 5 login attempts per 15 minutes }); app.use('/api/auth/login', authLimiter);
-
Request Size Limits:
// Already implemented - 10MB limit app.use(express.json({ limit: '10mb' }));
-
HTTPS Only:
// Force HTTPS in production if (process.env.NODE_ENV === 'production') { app.use((req, res, next) => { if (req.header('x-forwarded-proto') !== 'https') { res.redirect(`https://${req.header('host')}${req.url}`); } else { next(); } }); }
-
API Versioning:
// Implement versioning for backward compatibility app.use('/api/v1/auth', authRoutes);
Network Security:
-
Certificate Management:
- Use Fabric CA for certificate issuance
- Rotate certificates before expiry
- Revoke compromised certificates immediately
-
Chaincode Security:
- Input validation in smart contracts
- Access control within chaincode
- Regular security audits
-
Private Data:
// Use private data collections for sensitive info const collection = "farmersPrivateDetails";
- All environment variables configured securely
- Strong JWT secret generated (64+ bytes)
- MongoDB authentication enabled
- SSL/TLS certificates installed
- CORS configured for production domains only
- Rate limiting tuned for production traffic
- Error messages don't expose sensitive info
- Logging configured (no sensitive data in logs)
- Security headers configured (Helmet.js)
- Regular backup strategy implemented
- Monitoring and alerting configured
- DDoS protection enabled (Cloudflare, AWS Shield, etc.)
-
Firewall Rules:
# Only allow necessary ports - Port 80/443: HTTP/HTTPS (public) - Port 3001: API (internal/load balancer only) - Port 27017: MongoDB (internal only) - Port 22: SSH (restricted IPs only) -
Regular Updates:
# Keep dependencies updated npm audit npm audit fix # Update Docker images regularly docker pull node:18-alpine
-
Container Security:
- Run containers as non-root user (already implemented in Dockerfile)
- Use minimal base images (alpine)
- Scan images for vulnerabilities
docker scan ayurtrace-backend:latest
- Environment variables properly configured
- Input validation on all endpoints
- Authentication and authorization implemented
- Security headers configured
- Rate limiting implemented
- Dependencies updated (no known vulnerabilities)
- Unit tests for security functions
- Integration tests for auth flows
- Security audit completed
- Penetration testing performed
- Load testing completed
- SSL certificates obtained and configured
- Backup and recovery tested
- Monitoring dashboards configured
- Incident response plan documented
- All checklist items above completed
- Production secrets rotated
- Monitoring alerts configured
- Regular security scans scheduled
- Compliance requirements met (GDPR, etc.)
- Review access logs for suspicious activity
- Check for failed authentication attempts
- Monitor rate limiting triggers
- Run
npm auditand update dependencies - Review and rotate API keys if needed
- Check backup integrity
- Rotate JWT secrets
- Rotate database credentials
- Security assessment review
- Update SSL certificates if needed
- Comprehensive security audit
- Penetration testing
- Disaster recovery drill
- Security policy review
- OWASP Top 10
- Node.js Security Best Practices
- Express.js Security Best Practices
- MongoDB Security Checklist
- Hyperledger Fabric Security
For security concerns, contact:
- Email: [email protected]
- Bug Bounty: [Link to bug bounty program if applicable]
Last Updated: October 2, 2025
Version: 1.0