Security Guide

Security Guide

πŸ›‘οΈ Security Overview

SAM Framework implements a defense-in-depth security approach with multiple layers of protection for handling sensitive blockchain operations and AI interactions.

Key Management

Encrypted Storage

Fernet encryption with OS keyring integration

Transaction Safety

Validation Layer

Pre-execution checks and slippage protection

Privacy First

No Data Collection

Local operation with minimal external dependencies

Secure Memory

Persistent Storage

Encrypted conversation context and session data

πŸ” Key Security Features

1. Encrypted Private Key Storage

SAM uses military-grade encryption for all sensitive data:

Fernet Encryption Implementation

# sam/utils/crypto.py
from cryptography.fernet import Fernet

def encrypt_private_key(private_key: str, fernet_key: str) -> str:
    f = Fernet(fernet_key)
    encrypted = f.encrypt(private_key.encode())
    return encrypted.decode()

def decrypt_private_key(encrypted_key: str, fernet_key: str) -> str:
    f = Fernet(fernet_key)
    decrypted = f.decrypt(encrypted_key.encode())
    return decrypted.decode()

Security Properties:

  • AES 128 encryption in CBC mode
  • HMAC-SHA256 for authentication
  • Tamper-evident: Detects if data was modified
  • Cryptographically secure key generation

2. Transaction Validation & Safety

Comprehensive pre-execution checks prevent unauthorized or dangerous transactions:

# sam/utils/transaction_validator.py
async def validate_pump_buy(args: Dict[str, Any]) -> bool:
    """Validate Pump.fun buy transaction parameters."""

    # Amount validation
    if args.get('amount', 0) <= 0:
        raise ValueError("Amount must be positive")

    # Slippage limits
    slippage = args.get('slippage', 5)
    if slippage < 1 or slippage > 50:
        raise ValueError("Slippage must be between 1% and 50%")

    # Maximum transaction limits
    max_sol = float(os.getenv('MAX_TRANSACTION_SOL', '1000'))
    if args['amount'] > max_sol:
        raise ValueError(f"Transaction exceeds maximum SOL limit: {max_sol}")

    return True

Validation Layers:

  • Amount validation: Positive values only
  • Slippage protection: Configurable limits (1-50%)
  • Transaction limits: Maximum SOL per transaction
  • Address validation: Solana address format checking

3. Rate Limiting & Abuse Prevention

Built-in protection against excessive API usage:

# sam/utils/rate_limiter.py
class RateLimiter:
    def __init__(self, requests_per_minute: int = 60):
        self.requests_per_minute = requests_per_minute
        self.requests = []

    async def check_limit(self, key: str) -> bool:
        """Check if request is within rate limits."""
        now = time.time()
        # Remove old requests
        self.requests = [req for req in self.requests if now - req < 60]

        if len(self.requests) >= self.requests_per_minute:
            return False

        self.requests.append(now)
        return True

Rate Limiting Features:

  • Per-operation limits: Different limits for different operations
  • Automatic cleanup: Old requests automatically removed
  • Configurable thresholds: Adjustable limits via environment variables
  • Graceful degradation: Clear error messages when limits exceeded

4. Memory & Session Security

Secure conversation context management:

# sam/core/memory.py
class MemoryManager:
    async def save_session(self, session_id: str, messages: List[Dict]):
        """Securely store conversation context."""

        # Sanitize sensitive data before storage
        sanitized_messages = []
        for msg in messages:
            if msg.get('role') == 'tool' and 'private_key' in str(msg.get('content', '')):
                # Remove sensitive data from context
                msg = msg.copy()
                msg['content'] = '[SENSITIVE_DATA_REMOVED]'
            sanitized_messages.append(msg)

        # Store sanitized context
        await self._store_messages(session_id, sanitized_messages)

Memory Security:

  • Data sanitization: Sensitive information removed before storage
  • Session isolation: Independent contexts per session
  • Automatic cleanup: Old sessions can be cleared
  • SQLite encryption: Database can be encrypted at rest

🚨 Security Best Practices

Key Management

Recommended Key Management

# βœ… Good: Use secure import
uv run sam key import

# ❌ Bad: Store in environment
SAM_WALLET_PRIVATE_KEY=your_private_key_here

# ❌ Bad: Store in .env file
echo "SAM_WALLET_PRIVATE_KEY=your_key" >> .env

Key Rotation

# Regularly rotate your Fernet encryption key
uv run sam key generate
# Update SAM_FERNET_KEY in your .env file
# Re-import your private key with the new encryption key

Transaction Safety

Slippage Protection

# Set reasonable slippage limits
export DEFAULT_SLIPPAGE=5  # 5% for volatile tokens
export MAX_TRANSACTION_SOL=10.0  # Maximum 10 SOL per transaction

Testing Strategy

# Always test with small amounts first
"buy 0.001 SOL worth of TEST_TOKEN"

# Verify transaction details before large trades
"get swap quote for 1 SOL to USDC"

Environment Security

Production Configuration

# Use production settings
export RATE_LIMITING_ENABLED=true
export LOG_LEVEL=WARNING
export MAX_TRANSACTION_SOL=5.0

Secure Environment Variables

# Use secure file permissions
chmod 600 .env

# Never commit sensitive files
echo ".env" >> .gitignore
echo ".sam/" >> .gitignore

πŸ” Security Auditing

Regular Security Checks

# Run security health check
uv run sam health

# Validate configuration security
uv run sam setup

# Check for exposed sensitive data
grep -r "private_key\|api_key" . --exclude-dir=.git

Security Monitoring

Log Analysis

# Monitor for suspicious activity
tail -f sam.log | grep -E "(ERROR|WARNING|private_key)"

# Check rate limiting effectiveness
grep "rate_limit" sam.log

Key Usage Monitoring

# Verify key access patterns
uv run sam health  # Check key retrieval status

# Monitor for unusual transaction patterns
# Review transaction history for anomalies

🚫 Security Risks & Mitigations

Common Vulnerabilities

| Risk | Mitigation | |------|------------| | Private Key Exposure | Encrypted storage + OS keyring | | API Key Leakage | Environment variables + secure storage | | Transaction Manipulation | Pre-validation + slippage protection | | Rate Limit Bypass | Multi-layer rate limiting | | Memory Dumping | Sensitive data sanitization | | Log Exposure | No sensitive data in logs |

Incident Response

If Private Key is Compromised

  1. Immediate Action: Stop using the compromised key
  2. Transfer Assets: Move funds to a new wallet
  3. Key Rotation: Generate new key pair
  4. Update Storage: Re-import new key securely
  5. Audit: Review transaction history for unauthorized activity

If API Key is Exposed

  1. Revoke Key: Immediately revoke the exposed OpenAI API key
  2. Generate New Key: Create new API key
  3. Update Configuration: Update environment variables
  4. Monitor Usage: Watch for unauthorized API usage

πŸ”’ Advanced Security Features

Transaction Signing Security

# sam/integrations/solana/solana_tools.py
async def _sign_transaction(self, transaction_hex: str) -> str:
    """Secure transaction signing with validation."""

    # Validate transaction before signing
    if not self._validate_transaction_format(transaction_hex):
        raise ValueError("Invalid transaction format")

    # Sign with keypair
    signed_tx = self.keypair.sign_message(transaction_hex)

    # Clear sensitive data from memory
    del transaction_hex

    return signed_tx

API Security

OpenAI API Protection

  • Token Limits: Monitor and limit API usage
  • Request Validation: Validate all API requests
  • Error Handling: Secure error messages without data leakage
  • Rate Limiting: Protect against API abuse

External API Security

  • HTTPS Only: All external API calls use HTTPS
  • Certificate Validation: SSL certificate verification
  • Timeout Protection: Request timeouts prevent hanging
  • Retry Logic: Secure retry with exponential backoff

πŸ“‹ Security Checklist

πŸ”’ Security Verification

  • β€’ Private key imported via sam key import
  • β€’ Fernet encryption key properly configured
  • β€’ Rate limiting enabled in production
  • β€’ Transaction limits configured
  • β€’ No sensitive data in logs
  • β€’ .env file not committed to version control
  • β€’ Regular security audits performed
  • β€’ Latest security updates applied

Security is not a featureβ€”it's a fundamental requirement. SAM Framework is designed with security-first principles to protect your assets and data.