Skip to content

Security Patterns

Security best practices and patterns for Nova AI development.

Security Principles

  1. Defense in Depth - Multiple layers of security
  2. Least Privilege - Minimal required permissions
  3. Input Validation - Validate all external input
  4. Secure Defaults - Safe configuration by default
  5. Fail Securely - Graceful degradation

Common Vulnerabilities

1. SQL Injection

Bad:

query = f"SELECT * FROM users WHERE email = '{email}'"  # Vulnerable

Good:

query = "SELECT * FROM users WHERE email = ?"
cursor.execute(query, (email,))  # Parameterized

2. XSS (Cross-Site Scripting)

Bad:

html = f"<div>{user_input}</div>"  # Vulnerable

Good:

from markupsafe import escape
html = f"<div>{escape(user_input)}</div>"  # Escaped

3. Hardcoded Secrets

Bad:

API_KEY = "sk-1234567890abcdef"  # Hardcoded secret

Good:

import os
API_KEY = os.getenv("ANTHROPIC_API_KEY")  # Environment variable

4. Path Traversal

Bad:

filepath = f"/data/{user_provided_path}"  # Vulnerable

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:

os.system(f"git clone {repo_url}")  # Vulnerable

Good:

import subprocess
subprocess.run(["git", "clone", repo_url], check=True)  # Safe

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)

pip install bandit
bandit -r src/

2. Safety (Dependency Scanner)

pip install safety
safety check

3. mypy (Type Checking)

pip install mypy
mypy src/

Best Practices

  1. Never commit secrets - Use .gitignore
  2. Validate all input - Use Pydantic models
  3. Use parameterized queries - Prevent SQL injection
  4. Escape HTML output - Prevent XSS
  5. Use subprocess module - Prevent command injection
  6. Validate file paths - Prevent path traversal
  7. Log security events - Audit trail
  8. Rotate credentials - Regular updates
  9. Use HTTPS - Always encrypt in transit
  10. Principle of least privilege - Minimal permissions

Next Steps

Testing Guide Development Guide