Security hardening guide for CrewAI applications.
Never hardcode API keys in your code:
# ✅ Correct
import os
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
# ❌ Wrong - Never do this!
os.environ["OPENAI_API_KEY"] = "sk-1234567890"
Create .env file (add to .gitignore):
OPENAI_API_KEY=sk-your-key-here
SERPER_API_KEY=your-serper-key
ANTHROPIC_API_KEY=sk-ant-key
Load in Python:
from dotenv import load_dotenv
load_dotenv() # Loads .env automatically
For production, use secrets management:
# AWS Secrets Manager
aws secretsmanager create-secret --name crewai-api-keys
# HashiCorp Vault
vault kv put secret/crewai openai_key=sk-...
from crewai import Agent
from crewai_tools import SerperDevTool, ScrapeWebsiteTool
# Only give agents the tools they need
researcher = Agent(
role="Researcher",
tools=[SerperDevTool()], # Only search
allow_delegation=False
)
writer = Agent(
role="Writer",
tools=[], # No direct tool access
allow_delegation=True # Can ask researcher
)
from crewai import Agent, Task
agent = Agent(
role="Researcher",
tools=[SerperDevTool()],
max_rpm=10 # 10 requests per minute
)
task = Task(
description="Research topic",
agent=agent,
max_rpm=10
)
from crewai import Task
from pydantic import BaseModel, Field
class ResearchOutput(BaseModel):
title: str = Field(..., min_length=5)
bullet_points: list[str]
sources: list[str]
confidence_score: float = Field(..., ge=0, le=1)
task = Task(
description="Research AI trends",
expected_output="Structured findings",
agent=researcher,
output_pydantic=ResearchOutput # Validates output structure
)
def validate_output(output):
if len(output) < 100:
return False
if "ERROR" in output:
return False
return True
task = Task(
description="Write report",
agent=writer,
output_validation=validate_output
)
task = Task(
description="Generate important report",
agent=writer,
human_input=True # Requires human approval
)
def review_callback(output):
print(f"Review this output: {output}")
approved = input("Approve? (y/n): ")
return approved.lower() == 'y'
crew = Crew(
agents=[agent],
tasks=[task],
task_callback=review_callback
)
By default, CrewAI agents cannot execute code. Keep this secure:
# Agents cannot execute Python code by default
agent = Agent(
role="Analyst",
allow_code_execution=False # Keep False for security
)
If you must allow code execution, use sandboxing:
from crewai_tools import CodeInterpreterTool
# Use in isolated environment
agent = Agent(
role="Data Analyst",
tools=[CodeInterpreterTool()],
max_iter=5 # Limit iterations
)
export CREWAI_TELEMETRY_DISABLED="true"
In code:
import os
os.environ["CREWAI_TELEMETRY_DISABLED"] = "true"
def redact_callback(step):
# Redact sensitive information from logs
sensitive = ["API_KEY", "PASSWORD", "SECRET"]
for s in sensitive:
step = step.replace(s, "***REDACTED***")
print(step)
crew = Crew(
agents=[agent],
tasks=[task],
step_callback=redact_callback
)
import os
# Route through proxy
os.environ["HTTP_PROXY"] = "http://proxy.company.com:8080"
os.environ["HTTPS_PROXY"] = "http://proxy.company.com:8080"
For tools that access the web, configure allowlists:
from crewai_tools import ScrapeWebsiteTool
tool = ScrapeWebsiteTool(
allowed_domains=["example.com", "docs.python.org"]
)
For enterprise deployments, CrewAI AMP Suite provides:
| Feature | Description |
|---|---|
| 🔐 Advanced Security | Built-in security and compliance measures |
| 🔍 Audit Logging | Complete audit trail of all agent actions |
| 🎛️ Access Control | Role-based access control (RBAC) |
| 📊 Compliance | SOC 2, GDPR, HIPAA compliance options |
| 🔒 Data Residency | Control where data is stored |