Security Best Practices
Build invincible AI agents with these powerful security techniques! Think of security as your agent's superpower - protecting data, preventing misuse, and earning user trust.
API Key Management
Your first line of defense! ๐ Let's keep those keys safe and sound.
๐ Secure Storage
Think of API keys like your house keys - you wouldn't leave them lying around! Keep them in environment variables where they belong:
# Your secret keys - keep these safe! ๐คซ
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
# .env.example (committed) - share this template with your team
OPENAI_API_KEY=your-openai-api-key-here
ANTHROPIC_API_KEY=your-anthropic-api-key-here
๐ Key Rotation
Keep your keys fresh! Regular rotation is like changing your passwords - it keeps the bad guys guessing:
class ApiKeyRotationCommand extends Command
{
protected $signature = 'vizra:rotate-keys';
public function handle(): void
{
// Fetch new keys from secure vault
$newKeys = $this->fetchFromVault();
// Update configuration
config(['services.openai.key' => $newKeys['openai']]);
// Clear caches
cache()->forget('llm_connections');
$this->info('๐ API keys rotated successfully!');
}
}
๐ Encryption at Rest
Even when stored, your keys should be encrypted. It's like putting them in a safe within a safe!
use Illuminate\Support\Facades\Crypt;
// Store encrypted API keys in database
$team->update([
'openai_key' => Crypt::encryptString($apiKey),
]);
// Decrypt when needed
$apiKey = Crypt::decryptString($team->openai_key);
Input Validation & Sanitization
Your shield against prompt injection! ๐ก๏ธ Let's make those inputs squeaky clean.
๐ค Agent Input Validation
Protect your agents from sneaky prompt injections. Think of this as teaching your agent to spot trouble before it starts!
class SecureAgent extends BaseLlmAgent
{
protected function beforeAsk(string $message): string
{
// Remove potential injection attempts
$message = strip_tags($message);
// Validate length
if (strlen($message) > 5000) {
throw new ValidationException('Whoa there! That\'s a bit too long ๐');
}
// Check for malicious patterns
if ($this->containsMaliciousPatterns($message)) {
throw new SecurityException('Nice try! ๐ซ We caught that sneaky input.');
}
return $message;
}
private function containsMaliciousPatterns(string $input): bool
{
$patterns = [
'/\bignore\s+previous\s+instructions?\b/i',
'/\bsystem\s+prompt\b/i',
'/\b(reveal|show|display)\s+.*\s+instructions?\b/i',
];
foreach ($patterns as $pattern) {
if (preg_match($pattern, $input)) {
return true;
}
}
return false;
}
}
๐ง Tool Parameter Validation
Tools need protection too! Make sure they only accept the good stuff:
class DatabaseQueryTool extends BaseTool
{
protected function validate(array $parameters): void
{
// Whitelist allowed operations
$allowedOperations = ['select', 'count'];
if (!in_array($parameters['operation'], $allowedOperations)) {
throw new SecurityException('That operation is off-limits! ๐ท');
}
// Prevent SQL injection
if (preg_match('/[;\'"]/', $parameters['table'])) {
throw new SecurityException('No SQL injection here! ๐โ');
}
}
}
Authorization & Access Control
Who gets the keys to the kingdom? ๐ Let's set up some VIP access!
๐ฎ Agent-Level Authorization
Some agents are special! Make sure only the right people can use your most powerful agents:
class AdminAgent extends BaseLlmAgent
{
protected function authorize(): bool
{
return $this->user && $this->user->hasRole('admin');
}
protected function beforeAsk(string $message): string
{
if (!$this->authorize()) {
throw new UnauthorizedException(
'Halt! ๐ Admin powers required for this agent!'
);
}
return $message;
}
}
๐ฏ Tool-Level Permissions
Fine-grained control! Each tool can have its own bouncer at the door:
class SensitiveDataTool extends BaseTool
{
protected bool $requiresAuth = true;
protected function authorize(): bool
{
// Check specific permissions
return $this->user->can('view-sensitive-data');
}
public function execute(array $parameters): ToolResult
{
// Additional runtime checks
if (!$this->user->belongsToTeam($parameters['team_id'])) {
return ToolResult::error('No peeking at other teams\' data! ๐');
}
// Tool logic...
}
}
Rate Limiting
Slow down there, speedy! โฑ๏ธ Let's keep things fair for everyone.
๐ฆ Agent Rate Limiting
Prevent your agents from being overwhelmed! It's like having a polite doorman who says "one at a time, please!"
class RateLimitedAgent extends BaseLlmAgent
{
protected function beforeAsk(string $message): string
{
$key = "agent_limit:{$this->name}:{$this->user?->id}";
if (!RateLimiter::attempt($key, 10, function() {}, 60)) {
throw new TooManyRequestsException(
'Whoa there! ๐ค Take a breather and try again in a minute.'
);
}
return $message;
}
}
๐ฐ Tool Rate Limiting
Some tools are precious resources! Set limits to keep costs under control:
class ExpensiveApiTool extends BaseTool
{
protected $rateLimit = [
'maxAttempts' => 5,
'decayMinutes' => 60,
'key' => 'user', // Rate limit per user
];
}
Data Privacy
Keep secrets secret! ๐คซ Protect your users' personal information like a digital vault.
๐ต๏ธ PII Protection
Automatically redact sensitive info before it reaches the LLM. Your users will thank you!
class PrivacyAwareAgent extends BaseLlmAgent
{
protected function beforeAsk(string $message): string
{
// Redact sensitive information
$message = $this->redactPII($message);
return $message;
}
private function redactPII(string $text): string
{
// Redact SSN
$text = preg_replace('/\b\d{3}-\d{2}-\d{4}\b/', '[SSN REDACTED]', $text);
// Redact credit card numbers
$text = preg_replace('/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/', '[CC REDACTED]', $text);
// Redact email addresses
$text = preg_replace('/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/', '[EMAIL REDACTED]', $text);
return $text;
}
}
๐๏ธ Data Retention
Don't be a data hoarder! Clean up old sessions automatically:
// Automatic cleanup of old sessions
class CleanupOldSessions extends Command
{
protected $signature = 'vizra:cleanup-sessions {--days=30}';
public function handle(): void
{
$days = $this->option('days');
AgentSession::where('created_at', '<', now()->subDays($days))
->each(function ($session) {
// Delete messages
$session->messages()->delete();
// Delete session
$session->delete();
});
$this->info("๐งน Cleaned up sessions older than {$days} days!");
}
}
Secure Communication
Encrypt all the things! ๐ Keep your data safe in transit.
๐ HTTPS Enforcement
Make sure all communication is encrypted. No eavesdropping allowed!
// Force HTTPS in production
class ForceHttps
{
public function handle($request, Closure $next)
{
if (!$request->secure() && app()->environment('production')) {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
๐ญ API Response Filtering
Don't reveal your secrets! Filter out internal data before sending responses:
class SecureAgentResponse
{
public static function filter(AgentResponse $response): AgentResponse
{
// Remove internal data from responses
$response->metadata = array_filter($response->metadata, function($key) {
return !str_starts_with($key, '_internal_');
}, ARRAY_FILTER_USE_KEY);
// Remove sensitive tool results
foreach ($response->toolCalls as &$toolCall) {
if (isset($toolCall['result']['sensitive'])) {
unset($toolCall['result']['sensitive']);
}
}
return $response;
}
}
Audit Logging
Keep receipts for everything! ๐งพ Track who did what and when.
Create a paper trail for security audits and compliance. Your future self will thank you!
class AuditableAgent extends BaseLlmAgent
{
protected function afterResponse(AgentResponse $response): void
{
AuditLog::create([
'user_id' => $this->user?->id,
'agent' => $this->name,
'action' => 'agent_query',
'ip_address' => request()->ip(),
'user_agent' => request()->userAgent(),
'metadata' => [
'session_id' => $this->session?->id,
'tools_used' => array_column($response->toolCalls, 'name'),
'token_usage' => $response->usage,
],
]);
}
}
Security Checklist
Your security superhero checklist! ๐ฆธ Check these off to sleep soundly at night.
โจ Essential Security Measures
Pro Security Tip
Always assume user input is trying to break your system! ๐ฅท Implement defense in depth with multiple layers of security. Regular security audits and penetration testing aren't just recommended - they're your secret weapons for production applications.