Security Best Practices
Security Best Practices for AI Agents
Security is critical when deploying AI agents to production. This guide covers essential practices to keep your agents, data, and users safe.
The Security Mindset
Principle: Assume breach. Design systems that remain secure even if one component is compromised.
Key Principles:
- Least Privilege - Minimum permissions needed
- Defense in Depth - Multiple security layers
- Zero Trust - Verify everything, trust nothing
- Fail Secure - Errors should deny access, not grant it
Authentication & Authorization
API Keys
Do’s ✅
# Store in environment variablesimport osapi_key = os.getenv("API_KEY")
# Use Auteryn secrets managementagent.set_secret("API_KEY", "your-key")key = agent.get_secret("API_KEY")Don’ts ❌
# NEVER hardcode keysapi_key = "sk_live_abc123..." # ❌ WRONG
# NEVER commit to git# config.pyAPI_KEY = "sk_live_abc123..." # ❌ WRONGOAuth Tokens
Best Practices:
- Use OAuth over API keys when available
- Request minimum scopes needed
- Refresh tokens before expiry
- Revoke unused tokens
User Authentication
For user-facing agents:
# Verify user identityif not user.is_authenticated(): return "Please log in first"
# Check permissionsif not user.has_permission("view_data"): return "Access denied"Data Protection
Sensitive Data Handling
PII (Personally Identifiable Information):
# ❌ Bad: Logging PIIlogger.info(f"User email: {user.email}")
# ✅ Good: Redact PIIlogger.info(f"User: {user.id}")
# ✅ Good: Hash PIIimport hashlibhashed = hashlib.sha256(user.email.encode()).hexdigest()logger.info(f"User hash: {hashed[:8]}")Credit Card Data:
Data Encryption
At Rest:
# Auteryn encrypts all data automatically# But for extra sensitive data:from cryptography.fernet import Fernet
key = agent.get_secret("ENCRYPTION_KEY")cipher = Fernet(key)
# Encryptencrypted = cipher.encrypt(b"sensitive data")
# Decryptdecrypted = cipher.decrypt(encrypted)In Transit:
- Always use HTTPS for APIs
- Verify SSL certificates
- Use TLS 1.3 minimum
Input Validation
Sanitize User Input
SQL Injection Prevention:
# ❌ Bad: String concatenationquery = f"SELECT * FROM users WHERE email = '{user_input}'"
# ✅ Good: Parameterized queriesquery = "SELECT * FROM users WHERE email = %s"cursor.execute(query, (user_input,))XSS Prevention:
# ❌ Bad: Raw HTMLhtml = f"<div>{user_input}</div>"
# ✅ Good: Escape HTMLfrom html import escapehtml = f"<div>{escape(user_input)}</div>"Command Injection Prevention:
# ❌ Bad: Shell injection riskos.system(f"ls {user_input}")
# ✅ Good: Use subprocess with listimport subprocesssubprocess.run(["ls", user_input])Validate All Inputs
def validate_email(email): import re pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' if not re.match(pattern, email): raise ValueError("Invalid email") return email
# Use validationtry: email = validate_email(user_input)except ValueError: return "Please provide a valid email"Access Control
Role-Based Access Control (RBAC)
Define roles and permissions:
roles = { "admin": ["read", "write", "delete", "manage_users"], "editor": ["read", "write"], "viewer": ["read"]}
# Check permissionif "write" not in user.permissions: return "Access denied"Principle of Least Privilege
Bad:
# Agent has admin access to everythingagent.add_integration("github", scope="admin")Good:
# Agent has only needed permissionsagent.add_integration("github", scope="repo:read,issues:write")Secrets Management
Using Auteryn Secrets
# Set secret (encrypted automatically)agent.set_secret("DATABASE_URL", "postgresql://...")
# Get secretdb_url = agent.get_secret("DATABASE_URL")
# List secrets (values hidden)secrets = agent.list_secrets()# ["DATABASE_URL", "API_KEY", "STRIPE_KEY"]
# Delete secretagent.delete_secret("OLD_KEY")Environment Variables
# .env file (never commit to git)DATABASE_URL=postgresql://...API_KEY=sk_live_...STRIPE_KEY=sk_test_...Add .env to .gitignore:
.env.env.local*.key*.pemAudit Logging
What to Log
Do log:
- Authentication attempts
- Permission checks
- Data access
- Configuration changes
- Integration calls
- Errors and exceptions
Don’t log:
- Passwords or API keys
- Credit card numbers
- PII (unless necessary and encrypted)
- Full request/response bodies
Log Format
import logging
logger.info({ "event": "data_access", "user_id": user.id, "resource": "customer_data", "action": "read", "timestamp": "2026-04-02T10:15:23Z", "ip_address": request.ip, "result": "success"})Compliance
GDPR Compliance
User Rights:
- Right to access data
- Right to deletion
- Right to portability
- Right to rectification
Implementation:
# Data exportdata = agent.export_user_data(user_id)
# Data deletionagent.delete_user_data(user_id)
# Anonymizationagent.anonymize_user_data(user_id)Data Retention
Set retention policies:
agent.configure_retention( logs="30d", snapshots="90d", conversations="1y", analytics="2y")Incident Response
Response Plan
- Detect - Monitoring alerts on issue
- Contain - Isolate affected systems
- Investigate - Determine root cause
- Remediate - Fix the issue
- Recover - Restore normal operations
- Review - Post-mortem and improvements
Emergency Contacts
- Security issues: security@auteryn.ai
- Critical bugs: support@auteryn.ai
- 24/7 hotline: +1-555-AGENT-911 (Enterprise)
Security Checklist
Before Deployment
- All secrets in environment variables
- Input validation on all user inputs
- SQL injection prevention
- XSS prevention
- CSRF protection
- Rate limiting configured
- Audit logging enabled
- Error messages don’t leak info
- HTTPS only
- Security headers configured
Ongoing
- Review audit logs weekly
- Rotate secrets quarterly
- Update dependencies monthly
- Security training for team
- Incident response drills
- Penetration testing annually
Resources
Questions?
- Is Auteryn SOC 2 compliant? Yes, SOC 2 Type II certified.
- Where is data stored? US or EU regions (you choose).
- Can I use my own encryption keys? Yes (Enterprise plan).
- Do you support HIPAA? Yes, with BAA (Enterprise plan).
- How do you handle security incidents? 24/7 monitoring, immediate response, transparent communication.