Security Patterns¶
Security best practices and patterns for Nova AI development.
Security Principles¶
- Defense in Depth - Multiple layers of security
- Least Privilege - Minimal required permissions
- Input Validation - Validate all external input
- Secure Defaults - Safe configuration by default
- Fail Securely - Graceful degradation
Common Vulnerabilities¶
1. SQL Injection¶
Bad:
Good:
2. XSS (Cross-Site Scripting)¶
Bad:
Good:
3. Hardcoded Secrets¶
Bad:
Good:
4. Path Traversal¶
Bad:
Good:
from pathlib import Path
filepath = (Path("/data") / user_provided_path).resolve()
if not str(filepath).startswith("/data/"):
raise ValueError("Invalid path")
5. Command Injection¶
Bad:
Good:
Security Checklist¶
Code Review Security Gates¶
Blocking Issues:
- No SQL injection vulnerabilities
- No XSS vulnerabilities
- No hardcoded secrets or credentials
- No path traversal vulnerabilities
- No command injection vulnerabilities
- All user input validated
- All sensitive data encrypted
- Proper error handling (no info disclosure)
Input Validation¶
from pydantic import BaseModel, validator
class UserInput(BaseModel):
email: str
password: str
@validator('email')
def validate_email(cls, v):
if not re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', v):
raise ValueError('Invalid email')
return v
@validator('password')
def validate_password(cls, v):
if len(v) < 12:
raise ValueError('Password too short (min 12 chars)')
return v
Secret Management¶
# Good: Environment variables
import os
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
# Better: Secret manager (AWS Secrets Manager, etc.)
import boto3
client = boto3.client('secretsmanager')
secret = client.get_secret_value(SecretId='anthropic-api-key')
Security Tools¶
1. Bandit (Security Linter)¶
2. Safety (Dependency Scanner)¶
3. mypy (Type Checking)¶
Best Practices¶
- Never commit secrets - Use .gitignore
- Validate all input - Use Pydantic models
- Use parameterized queries - Prevent SQL injection
- Escape HTML output - Prevent XSS
- Use subprocess module - Prevent command injection
- Validate file paths - Prevent path traversal
- Log security events - Audit trail
- Rotate credentials - Regular updates
- Use HTTPS - Always encrypt in transit
- Principle of least privilege - Minimal permissions