# AegisTrade AI — Threat Model & Security Architecture

## 1. STRIDE Threat Analysis

| Threat Category | Potential Attack / Failure Vector | AegisTrade AI Mitigation |
| :--- | :--- | :--- |
| **Spoofing** | Unauthorized user placing live trades or triggering kill switch resets. | JWT token authentication, bcrypt password hashing, role-based authorization (`admin`, `operator`, `viewer`), API key signature validation. |
| **Tampering** | Man-in-the-middle tampering with market data or exchange orders. | TLS 1.3 enforced for REST and WebSockets; HMAC-SHA256 signature verification on every Bybit V5 authenticated request. |
| **Repudiation** | Operator claims an order was not placed or parameters were changed. | Append-only `AUDIT_LOGS` table with timestamps, IP address, user ID, and diffs on all state changes. |
| **Information Disclosure** | Bybit API keys leaked via logs, stack traces, UI screenshots, or Git. | Environment variable storage, strict regex redaction in JSON logging, `.gitignore` locks, demo/live credential segregation. |
| **Denial of Service** | Exchange disconnect or market data feed freeze causing unmanaged positions. | Real-time WebSocket heartbeat watchdog. Auto-triggering `STALE_DATA_HALT` if feed lags $>30$ seconds; protective exchange-side Stop Orders placed concurrently with entry. |
| **Elevation of Privilege** | Normal viewer or dev test script triggering live mainnet orders. | Live trading requires `ENABLE_LIVE_TRADING=true`, live subaccount key check, passing risk rules, and explicit authenticated approval token. Live is locked by default. |

---

## 2. Exchange API Key Security Model

1. **Least-Privilege API Keys**:
   - Only `Read` and `Trade` permissions permitted.
   - **Withdrawal permission is strictly barred**. If the Bybit API key capability check detects withdrawal rights, initialization aborts immediately with an error.
2. **Subaccount Isolation**:
   - Live trading must only use a dedicated, isolated Bybit Subaccount with limited allocated capital, never the master exchange account.
3. **Endpoint Validation**:
   - `BYBIT_DEMO` mode forces URL `https://api-demo.bybit.com` and private WebSocket `wss://stream-demo.bybit.com/v5/private`.
   - Live endpoints can never be reached when running under `BYBIT_DEMO` or `PAPER`.

---

## 3. Financial Safety Invariants

- **Kill Switch Persistence**: In the event of backend restart or worker crash, `KILL_SWITCH_ACTIVE=True` is read from SQLite/PostgreSQL upon startup, ensuring trading remains suspended.
- **Fail-Safe Recovery**: If exchange connectivity drops while a position is open, the client flags the position as `UNVERIFIED_PROTECTION` and issues immediate high-priority alerts.
