Vizra.ai |

Documentation

๐Ÿ›ก๏ธ

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

Store API keys in environment variables, never in code ๐Ÿ”‘
Implement input validation and sanitization ๐Ÿงน
Use authorization checks for agents and tools ๐ŸŽซ
Apply rate limiting to prevent abuse ๐Ÿšฆ
Encrypt sensitive data at rest ๐Ÿ”’
Use HTTPS for all communications ๐Ÿ”
Implement audit logging ๐Ÿ“
Regularly update dependencies ๐Ÿ”„
Follow data retention policies ๐Ÿ—“๏ธ
Test for security vulnerabilities ๐Ÿ”
๐Ÿ’ก

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.