Security Best Practices
Essential security practices for production agents
Security Best Practices
Follow these security best practices to protect your SwiftClaw agents and data.
Authentication & Authorization
1. Use Strong Authentication
# Generate secure API keys
swiftclaw keys create my-agent --length 64
# Enable MFA for sensitive operations
swiftclaw security mfa enable my-agent2. Implement RBAC
{
"roles": {
"admin": ["read", "write", "delete", "manage"],
"developer": ["read", "write"],
"viewer": ["read"]
}
}3. Rotate Credentials Regularly
# Set automatic rotation
swiftclaw security rotation my-agent --interval 90dSecret Management
1. Never Hardcode Secrets
# Bad
api_key = "sk-abc123..."
# Good
api_key = os.getenv("OPENAI_API_KEY")
# Best
api_key = await agent.secrets.get("api-key")2. Use Secret Store
# Store secrets securely
swiftclaw secrets set my-agent api-key --value sk-...3. Enable Secret Scanning
# Prevent secret leaks
swiftclaw security scan my-agent --enableNetwork Security
1. Use HTTPS Only
{
"security": {
"enforceHttps": true,
"hsts": {
"enabled": true,
"maxAge": 31536000
}
}
}2. Configure IP Whitelist
{
"security": {
"ipWhitelist": {
"enabled": true,
"addresses": ["203.0.113.0/24"]
}
}
}3. Enable Rate Limiting
{
"security": {
"rateLimit": {
"enabled": true,
"requests": 100,
"window": "1m"
}
}
}Input Validation
1. Validate All Inputs
from pydantic import BaseModel, validator
class MessageInput(BaseModel):
content: str
user_id: str
@validator('content')
def validate_content(cls, v):
if len(v) > 10000:
raise ValueError('Content too long')
return v
@agent.on_message
async def handle_message(message: MessageInput):
# Input validated automatically
return await agent.generate(message.content)2. Sanitize User Input
import bleach
def sanitize_input(text: str) -> str:
# Remove HTML tags
clean = bleach.clean(text, strip=True)
# Remove special characters
clean = re.sub(r'[^\w\s-]', '', clean)
return clean
@agent.on_message
async def handle_message(message):
clean_message = sanitize_input(message.content)
return await agent.generate(clean_message)3. Implement Content Filtering
@agent.middleware
async def content_filter(message):
# Check for malicious content
if contains_malicious_content(message.content):
raise SecurityError("Malicious content detected")
# Check for PII
if contains_pii(message.content):
message.content = redact_pii(message.content)Data Protection
1. Encrypt Sensitive Data
from cryptography.fernet import Fernet
# Generate encryption key
key = Fernet.generate_key()
cipher = Fernet(key)
# Encrypt data
encrypted = cipher.encrypt(sensitive_data.encode())
# Decrypt data
decrypted = cipher.decrypt(encrypted).decode()2. Implement Data Retention
{
"dataRetention": {
"logs": "30d",
"memory": "90d",
"analytics": "1y"
}
}3. Enable Data Anonymization
def anonymize_data(data: dict) -> dict:
# Remove PII
data.pop('email', None)
data.pop('phone', None)
# Hash identifiers
data['user_id'] = hash_id(data['user_id'])
return dataAccess Control
1. Principle of Least Privilege
# Grant minimal permissions
swiftclaw access grant user@example.com \
--agent my-agent \
--permission read2. Implement Audit Logging
# Enable audit logging
swiftclaw audit enable my-agent
# View audit logs
swiftclaw audit logs my-agent --period 30d3. Monitor Access Patterns
# Set up alerts for unusual access
swiftclaw alerts create \
--agent my-agent \
--metric unusual-access \
--action notifyDependency Security
1. Keep Dependencies Updated
# Check for vulnerabilities
npm audit
# Update dependencies
npm update
# Fix vulnerabilities
npm audit fix2. Use Dependency Scanning
# .github/workflows/security.yml
name: Security Scan
on: [push, pull_request]
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run Snyk
uses: snyk/actions/node@master
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}3. Pin Dependency Versions
{
"dependencies": {
"express": "4.18.2",
"openai": "4.28.0"
}
}Monitoring & Alerting
1. Enable Security Monitoring
# Enable security monitoring
swiftclaw security monitor my-agent --enable2. Set Up Security Alerts
# Alert on failed authentication
swiftclaw alerts create \
--agent my-agent \
--metric failed-auth \
--threshold 10 \
--window 5m
# Alert on unusual activity
swiftclaw alerts create \
--agent my-agent \
--metric unusual-activity \
--action notify3. Review Security Logs
# View security events
swiftclaw logs my-agent --filter security
# Export security logs
swiftclaw logs export my-agent \
--filter security \
--period 30dIncident Response
1. Create Incident Response Plan
## Incident Response Plan
### Detection
- Monitor alerts
- Review logs daily
- Track anomalies
### Response
1. Identify incident type
2. Contain the threat
3. Investigate root cause
4. Remediate vulnerability
5. Document incident
### Recovery
- Restore from backup
- Verify system integrity
- Monitor for recurrence2. Enable Automatic Rollback
{
"security": {
"autoRollback": {
"enabled": true,
"triggers": ["security-breach", "data-leak"]
}
}
}3. Maintain Backups
# Enable automatic backups
swiftclaw backup enable my-agent --interval 24h
# Create manual backup
swiftclaw backup create my-agent
# Restore from backup
swiftclaw backup restore my-agent --backup backup-idCompliance
1. GDPR Compliance
# Implement right to deletion
@agent.endpoint("/delete-user-data")
async def delete_user_data(user_id: str):
await agent.memory.delete(user_id=user_id)
await agent.logs.delete(user_id=user_id)
return {"status": "deleted"}
# Implement data export
@agent.endpoint("/export-user-data")
async def export_user_data(user_id: str):
data = await agent.memory.export(user_id=user_id)
return {"data": data}2. SOC 2 Compliance
# Enable compliance logging
swiftclaw compliance enable my-agent --standard soc2
# Generate compliance report
swiftclaw compliance report my-agent --period 90d3. HIPAA Compliance
{
"compliance": {
"hipaa": {
"enabled": true,
"encryption": "aes-256",
"auditLogging": true,
"accessControl": "strict"
}
}
}Security Checklist
- Strong authentication enabled
- API keys rotated regularly
- Secrets stored securely
- HTTPS enforced
- Rate limiting configured
- Input validation implemented
- Data encrypted at rest and in transit
- Audit logging enabled
- Security monitoring active
- Incident response plan documented
- Dependencies updated regularly
- Backups configured
- Compliance requirements met
Security is Ongoing: Regularly review and update security practices as threats evolve.
Next Steps
How is this guide ?
Last updated on