Skip to content

Security

Jean-Marc Strauven edited this page Aug 6, 2025 · 2 revisions

Security & PII Protection

Protecting sensitive data in traces is crucial for production deployments. ChronoTrace provides comprehensive PII scrubbing and security features to ensure compliance and data protection.


πŸ” Overview

When recording traces in production, you may capture sensitive data such as:

  • Passwords and tokens in request payloads
  • Email addresses and phone numbers in database queries
  • Credit card numbers in payment processing flows
  • API keys and secrets in HTTP headers
  • Personal information in cache keys and values

ChronoTrace automatically detects and masks this sensitive data while preserving the structure needed for debugging.


πŸ›‘οΈ Default PII Scrubbing

Automatic Field Detection

ChronoTrace automatically scrubs fields with these names (case-insensitive):

// Default scrubbed fields
'scrub' => [
    'password',
    'token',
    'secret',
    'key',
    'email',
    'phone',
    'ssn',
    'credit_card',
    'cvv',
    'api_key',
    'auth_token',
    'bearer_token',
],

Before and After Examples

Database Query Scrubbing

Before scrubbing:

INSERT INTO users (name, email, password) VALUES (?, ?, ?)
['John Doe', 'john@example.com', 'MySecretPassword123']

After scrubbing:

INSERT INTO users (name, email, password) VALUES (?, ?, ?)
['John Doe', '[REDACTED]', '[REDACTED]']

HTTP Request Scrubbing

Before scrubbing:

{
    "user": {
        "name": "John Doe",
        "email": "john@example.com",
        "password": "MySecretPassword123"
    },
    "payment": {
        "credit_card": "4532-1234-5678-9012",
        "cvv": "123"
    }
}

After scrubbing:

{
    "user": {
        "name": "John Doe",
        "email": "[REDACTED]",
        "password": "[REDACTED]"
    },
    "payment": {
        "credit_card": "[REDACTED]",
        "cvv": "[REDACTED]"
    }
}

πŸŽ›οΈ Custom PII Configuration

Adding Custom Fields

Extend the default scrubbing to include your application-specific fields:

// config/chronotrace.php
'scrub' => [
    // Default fields
    'password',
    'token',
    'secret',
    'key',
    'email',
    
    // Your custom fields
    'api_token',
    'auth_key',
    'private_key',
    'bank_account',
    'routing_number',
    'social_security',
    'date_of_birth',
    'drivers_license',
    'passport_number',
    
    // Application-specific
    'stripe_key',
    'paypal_token',
    'oauth_secret',
    'encryption_key',
],

Regular Expression Patterns

For more sophisticated detection, use regex patterns:

// config/chronotrace.php
'custom_scrubbers' => [
    // Credit card numbers (any format)
    '/\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b/' => '****-****-****-****',
    
    // Social Security Numbers
    '/\b\d{3}-\d{2}-\d{4}\b/' => '***-**-****',
    
    // Phone numbers
    '/\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/' => '***-***-****',
    
    // Email addresses
    '/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/' => '[EMAIL_REDACTED]',
    
    // API keys (common patterns)
    '/api_key_[a-zA-Z0-9]+/' => 'api_key_[REDACTED]',
    '/sk_live_[a-zA-Z0-9]+/' => 'sk_live_[REDACTED]',
    '/pk_live_[a-zA-Z0-9]+/' => 'pk_live_[REDACTED]',
    
    // Bearer tokens
    '/Bearer\s+[A-Za-z0-9\-._~+\/]+=*/' => 'Bearer [REDACTED]',
    
    // JSON field patterns
    '/"password":\s*"[^"]*"/' => '"password": "[REDACTED]"',
    '/"token":\s*"[^"]*"/' => '"token": "[REDACTED]"',
    '/"secret":\s*"[^"]*"/' => '"secret": "[REDACTED]"',
],

Environment-Specific Scrubbing

Different scrubbing rules for different environments:

// config/chronotrace.php
'scrub' => array_merge([
    'password',
    'token',
    'secret',
], app()->environment('production') ? [
    // More aggressive scrubbing in production
    'email',
    'phone',
    'name',
    'address',
    'ip_address',
] : [
    // Minimal scrubbing in development
]),

🚫 Route and Data Exclusions

Excluding Sensitive Routes

Prevent recording traces for sensitive endpoints:

// config/chronotrace.php
'excluded_routes' => [
    'password/*',
    'api/auth/login',
    'api/auth/register',
    'api/payments/*',
    'admin/sensitive/*',
    'oauth/*',
    'webhook/stripe',
    'webhook/paypal',
],

Excluding by IP Address

Don't record traces from specific IP addresses:

// config/chronotrace.php
'excluded_ips' => [
    '192.168.1.100',    // Admin workstation
    '10.0.0.0/8',       // Internal network
    '172.16.0.0/12',    // Private network
    '127.0.0.1',        // Localhost
],

Excluding by User Role

Exclude traces for privileged users:

// config/chronotrace.php
'excluded_users' => [
    'roles' => ['admin', 'super-admin'],
    'ids' => [1, 2, 3], // Specific user IDs
],

πŸ—ƒοΈ Database Security

Excluding Sensitive Tables

Don't capture queries from sensitive tables:

// config/chronotrace.php
'database' => [
    'excluded_tables' => [
        'password_resets',
        'personal_access_tokens',
        'oauth_access_tokens',
        'oauth_refresh_tokens',
        'sessions',
        'cache',
        'failed_jobs',
        
        // Your sensitive tables
        'user_secrets',
        'payment_methods',
        'audit_logs',
        'encryption_keys',
    ],
],

Query Parameter Scrubbing

Scrub sensitive data in SQL query bindings:

// config/chronotrace.php
'database' => [
    'scrub_bindings' => true,
    'scrub_patterns' => [
        // Credit card patterns in bindings
        '/\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}/',
        // Email patterns
        '/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/',
    ],
],

🌐 HTTP Request Security

Header Scrubbing

Automatically scrub sensitive HTTP headers:

// config/chronotrace.php
'http' => [
    'scrub_headers' => [
        'Authorization',
        'X-API-Key',
        'X-Auth-Token',
        'Cookie',
        'Set-Cookie',
        'X-Stripe-Signature',
        'X-Hub-Signature',
    ],
    
    'scrub_request_body' => true,
    'scrub_response_body' => true,
    'max_body_size' => 64 * 1024, // Don't capture large payloads
],

URL Parameter Scrubbing

Clean sensitive data from URLs:

// config/chronotrace.php
'http' => [
    'scrub_url_params' => [
        'api_key',
        'token',
        'access_token',
        'password',
        'secret',
    ],
],

Example:

Before: https://api.example.com/users?api_key=abc123&user_id=456
After:  https://api.example.com/users?api_key=[REDACTED]&user_id=456

πŸ’Ύ Cache Security

Cache Key Scrubbing

Protect sensitive data in cache keys:

// config/chronotrace.php
'cache' => [
    'scrub_keys' => true,
    'scrub_values' => true,
    'excluded_keys' => [
        'session:*',
        'user:*:secrets',
        'payment:*',
        'oauth:*',
    ],
],

Value Size Limits

Prevent capturing large cache values:

// config/chronotrace.php
'cache' => [
    'max_value_size' => 1024,  // 1KB limit
    'include_values' => false, // Don't store values at all
],

πŸ”§ Advanced Security Features

Custom Scrubber Classes

Create custom scrubbing logic:

// app/Services/CustomScrubber.php
class CustomScrubber implements ScrubbingContract
{
    public function scrub(array $data): array
    {
        return $this->scrubRecursive($data);
    }
    
    private function scrubRecursive(array $data): array
    {
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                $data[$key] = $this->scrubRecursive($value);
            } elseif ($this->isSensitive($key, $value)) {
                $data[$key] = $this->maskValue($value);
            }
        }
        
        return $data;
    }
    
    private function isSensitive(string $key, $value): bool
    {
        // Custom logic to detect sensitive data
        if (str_contains(strtolower($key), 'credit_card')) {
            return true;
        }
        
        if (is_string($value) && preg_match('/\d{4}-\d{4}-\d{4}-\d{4}/', $value)) {
            return true;
        }
        
        return false;
    }
    
    private function maskValue($value): string
    {
        if (is_string($value) && strlen($value) > 4) {
            return substr($value, 0, 2) . str_repeat('*', strlen($value) - 4) . substr($value, -2);
        }
        
        return '[REDACTED]';
    }
}

Register your custom scrubber:

// config/chronotrace.php
'custom_scrubbers' => [
    'payment_data' => App\Services\CustomScrubber::class,
],

Context-Aware Scrubbing

Different scrubbing rules based on request context:

// config/chronotrace.php
'contextual_scrubbing' => [
    'routes' => [
        'api/payments/*' => [
            'scrub' => ['credit_card', 'cvv', 'bank_account'],
            'exclude_completely' => true, // Don't record at all
        ],
        'api/auth/*' => [
            'scrub' => ['password', 'token', 'secret'],
        ],
    ],
    
    'user_roles' => [
        'admin' => [
            'scrub_less' => true, // Admins can see more data
        ],
        'customer' => [
            'scrub_aggressively' => true,
        ],
    ],
],

🏭 Production Security Checklist

Essential Configuration

# .env - Production security settings
CHRONOTRACE_MODE=record_on_error
CHRONOTRACE_SCRUB_PII=true
CHRONOTRACE_ASYNC_STORAGE=true
CHRONOTRACE_RETENTION_DAYS=7

# Minimal event capture
CHRONOTRACE_CAPTURE_CACHE=false
CHRONOTRACE_CAPTURE_EVENTS=false

Verification Commands

# Test scrubbing is working
php artisan chronotrace:test-internal --test-scrubbing

# Verify sensitive routes are excluded
php artisan chronotrace:diagnose --security

# Check for accidentally captured PII
php artisan chronotrace:list --scan-pii

Regular Security Audits

# Monthly security check
php artisan chronotrace:audit --check-pii --check-routes --check-retention

# Generate security report
php artisan chronotrace:security-report --output=/secure/location/

πŸ“‹ Compliance Considerations

GDPR Compliance

  • Data Minimization: Only capture necessary events
  • Purpose Limitation: Use traces only for debugging/monitoring
  • Storage Limitation: Set short retention periods
  • Right to Erasure: Implement data deletion procedures
// GDPR-compliant configuration
'gdpr' => [
    'retention_days' => 30,
    'auto_purge' => true,
    'data_subject_rights' => true,
    'anonymize_after_days' => 7,
],

HIPAA Compliance

For healthcare applications:

// HIPAA-compliant settings
'hipaa' => [
    'encrypt_storage' => true,
    'access_logging' => true,
    'scrub_aggressively' => true,
    'excluded_fields' => [
        'ssn', 'medical_record_number', 'patient_id',
        'diagnosis', 'treatment', 'prescription',
    ],
],

PCI DSS Compliance

For payment processing:

// PCI DSS-compliant settings
'pci_dss' => [
    'exclude_payment_routes' => true,
    'scrub_card_data' => true,
    'encrypt_traces' => true,
    'restricted_access' => true,
],

🚨 Security Incident Response

Accidental PII Exposure

If sensitive data is accidentally captured:

# Immediately purge specific traces
php artisan chronotrace:purge --trace-id=sensitive-trace-id --force

# Purge all traces from a time period
php artisan chronotrace:purge --since="2024-08-06 10:00" --before="2024-08-06 11:00"

# Enable aggressive scrubbing going forward
php artisan chronotrace:config --scrub-aggressive

Security Audit Trail

Enable audit logging for compliance:

// config/chronotrace.php
'audit' => [
    'log_access' => true,
    'log_purges' => true,
    'log_configuration_changes' => true,
    'audit_file' => storage_path('logs/chronotrace-audit.log'),
],

πŸ“š Related Documentation


Remember: Security is an ongoing process. Regularly review your ChronoTrace configuration and audit captured traces to ensure compliance with your organization's security policies.

Clone this wiki locally