Security Hardening Guide
Overview
This document outlines the security hardening measures implemented in NIJA to protect the trading bot, user data, and API credentials.
Automated Security Scanning
CodeQL Analysis
NIJA uses GitHub’s CodeQL to perform automated security scanning of the codebase.
Workflow: .github/workflows/codeql.yml
Features:
- ✅ Scans Python and JavaScript code
- ✅ Runs on every push to main/develop branches
- ✅ Runs on all pull requests
- ✅ Weekly scheduled scans (Mondays at 6am UTC)
- ✅ Detects security vulnerabilities, coding errors, and code smells
View Results:
- Navigate to:
Security > Code scanning alerts in GitHub
- Review and address any high/critical severity findings
Dependency Vulnerability Scanning
Workflow: .github/workflows/security-scan.yml
Tools Used:
- Safety - Python dependency vulnerability scanner
- Bandit - Python security linting
- TruffleHog - Secret scanning in git history
Scanning Schedule:
- On every push to main/develop
- On all pull requests
- Weekly scheduled scans (Sundays at 2am UTC)
Security Best Practices Checklist
✅ API Key Security
Required Environment Variables:
COINBASE_API_KEY=your_key_here
COINBASE_API_SECRET=your_secret_here
COINBASE_PEM_CONTENT=your_pem_content_here
Example:
from pydantic import BaseModel, validator
class WebhookSignal(BaseModel):
symbol: str
action: str
price: float
@validator('action')
def validate_action(cls, v):
if v not in ['buy', 'sell']:
raise ValueError('Invalid action')
return v
✅ Network Security
✅ Error Handling
Example:
import logging
logger = logging.getLogger(__name__)
try:
response = api_call()
except Exception as e:
# DON'T: logger.error(f"API failed: {api_key}")
# DO: logger.error(f"API call failed: {type(e).__name__}")
✅ Access Control
✅ Code Security
✅ Trading Security
Example:
from bot.risk_manager import RiskManager
risk_manager = RiskManager(
max_position_size_pct=5.0,
max_daily_loss_pct=5.0,
max_drawdown_pct=12.0
)
# Validate trade before execution
if not risk_manager.validate_trade(size, price):
logger.warning("Trade rejected by risk manager")
return
Security Monitoring
Real-Time Alerts
Configure alerts for:
- Failed authentication attempts
- Unusual API activity
- Large withdrawals or transfers
- Circuit breaker triggers
- Error rate spikes
Security Logs
Monitor these log files:
logs/security.log - Authentication and authorization events
logs/api.log - API call history
logs/trades.log - Trade execution audit trail
logs/errors.log - Application errors
Log Retention:
- Keep logs for minimum 90 days
- Archive important logs for compliance
- Implement log rotation to prevent disk fill
Incident Response
Security Incident Steps
- Immediate Actions:
- Stop the trading bot:
./stop_bot.sh
- Disable API keys in broker account
- Assess the scope of the incident
- Investigation:
- Review security logs
- Check recent trade history
- Identify compromised credentials
- Document timeline of events
- Remediation:
- Rotate all API keys and secrets
- Update
.env file with new credentials
- Patch identified vulnerabilities
- Review and update security policies
- Recovery:
- Test bot with new credentials
- Restart trading in paper mode first
- Monitor closely for 24-48 hours
- Document lessons learned
- Security Issues: Create issue in GitHub with
security label
- Trading Issues: Check
RECOVERY_GUIDE.md
- API Issues: Refer to broker support documentation
Security Updates
Dependency Updates
Monthly Security Updates:
# Check for outdated packages
pip list --outdated
# Update specific vulnerable packages
pip install --upgrade package-name
# Update requirements.txt
pip freeze > requirements.txt
Security Patch Process
- Monitor GitHub Security Advisories
- Review Dependabot alerts weekly
- Test patches in development environment
- Deploy to production with monitoring
Compliance Considerations
Data Protection
- Encryption at rest: User credentials encrypted with Fernet
- Encryption in transit: HTTPS for all API calls
- Data minimization: Only store necessary trading data
- Right to deletion: Provide mechanism to delete user data
Audit Trail
- All trades logged with timestamp and user ID
- API key usage tracked
- Authentication events recorded
- Position changes documented
Regulatory Compliance
- Comply with broker terms of service
- Follow financial regulation requirements
- Maintain records as required by law
- Implement KYC/AML as needed
Security Review Schedule
- Daily: Review security scan results
- Weekly: Check Dependabot alerts
- Monthly: Update dependencies
- Quarterly: Rotate API keys
- Annually: Full security audit
Additional Resources
Questions or Issues?
If you discover a security vulnerability:
- DO NOT open a public issue
- Email security contact privately
- Provide detailed information
- Allow time for patch before disclosure
For general security questions, refer to SECURITY.md.