# Security Architecture

This document describes the security architecture of Crypto Trader.

## Security Layers

```
Application Layer
    ├──► API Key Encryption
    ├──► Permission Management
    └──► Audit Logging
            │
            ▼
Storage Layer
    ├──► Encrypted Storage
    └──► Secure Key Management
```

## API Key Encryption

### Encryption Process

```
Plain API Key
    │
    ▼
Fernet Encryption
    │
    ▼
Encrypted Key (Stored in Database)
```

### Key Management

- **Encryption Key**: Stored securely (environment variable or keyring)
- **Key Generation**: Automatic on first use
- **Key Rotation**: Manual rotation process

## Permission Management

### Permission Levels

- **Read-Only**: Data collection, backtesting only
- **Trading Enabled**: Full trading capabilities

### Permission Enforcement

```
API Request
    │
    ▼
Permission Check
    │
    ├──► Read-Only Request
    │         │
    │         └──► Allow (read operations)
    │
    └──► Trading Request
            │
            ├──► Trading Enabled?
            │         │
            │         ├──► Yes: Allow
            │         └──► No: Reject
```

## Secure Storage

### Keyring Integration

- **Linux**: Secret Service (GNOME Keyring)
- **macOS**: Keychain
- **Windows**: Windows Credential Manager

### Fallback Storage

If keyring unavailable:
- Environment variable (development only)
- Encrypted file with user permission

## Audit Logging

All security events are logged:

- API key changes
- Permission changes
- Trading operations
- Configuration changes
- Error events

### Audit Log Format

```python
{
    "timestamp": "2025-12-13T19:00:00Z",
    "event_type": "API_KEY_CHANGED",
    "user_id": "system",
    "details": {
        "exchange": "coinbase",
        "action": "updated"
    }
}
```

## Data Privacy

- **Local Storage**: All data stored locally
- **No Telemetry**: No data sent externally
- **Encryption**: Sensitive data encrypted at rest
- **Access Control**: File system permissions

## Best Practices

1. **Use Read-Only Keys**: When possible, use read-only API keys
2. **IP Whitelisting**: Enable IP whitelisting on exchange accounts
3. **Regular Rotation**: Rotate API keys periodically
4. **Secure Environment**: Keep encryption keys secure
5. **Audit Review**: Regularly review audit logs

## Threat Model

### Threats Addressed

- **API Key Theft**: Encryption at rest
- **Unauthorized Trading**: Permission checks
- **Data Breach**: Local storage, encryption
- **Man-in-the-Middle**: HTTPS for API calls
- **Key Logging**: Secure keyring storage

### Security Boundaries

- **Application Boundary**: Application code
- **Storage Boundary**: Encrypted database
- **Network Boundary**: Secure API connections
- **System Boundary**: File system permissions

