|
| 1 | +# API Key Encryption Migration |
| 2 | + |
| 3 | +This guide explains how to encrypt all API keys in your database using AES-256-GCM encryption. |
| 4 | + |
| 5 | +## Overview |
| 6 | + |
| 7 | +The application now encrypts all API keys (both user-added provider keys and application-generated API keys) before storing them in the database. This provides an additional layer of security in case your database is compromised. |
| 8 | + |
| 9 | +### What Gets Encrypted? |
| 10 | + |
| 11 | +1. **User Provider Keys** (`user_keys` table): NanoGPT, OpenAI, Anthropic, and HuggingFace API keys that users add in their account settings |
| 12 | +2. **Application API Keys** (`api_keys` table): Developer API keys generated for programmatic access (format: `nc_...`) |
| 13 | + |
| 14 | +### Encryption Details |
| 15 | + |
| 16 | +- **Algorithm**: AES-256-GCM (industry standard, widely supported, hardware accelerated) |
| 17 | +- **Key Derivation**: scrypt with N=16384, r=8, p=1 (~64MB memory) |
| 18 | +- **Key Source**: `ENCRYPTION_KEY` environment variable |
| 19 | +- **Format**: VERSION | SALT | IV | ENCRYPTED_DATA | AUTH_TAG (base64-encoded) |
| 20 | + |
| 21 | +## Prerequisites |
| 22 | + |
| 23 | +1. **Backup your database** - This is critical! |
| 24 | + ```bash |
| 25 | + cp data/nanochat.db data/nanochat.db.backup |
| 26 | + ``` |
| 27 | + |
| 28 | +2. **Generate an encryption key** (if you haven't already): |
| 29 | + ```bash |
| 30 | + openssl rand -base64 32 |
| 31 | + ``` |
| 32 | + |
| 33 | +3. **Set the ENCRYPTION_KEY environment variable** in your `.env` file: |
| 34 | + ```bash |
| 35 | + ENCRYPTION_KEY=your-generated-key-here |
| 36 | + ``` |
| 37 | + |
| 38 | + ⚠️ **IMPORTANT**: Keep this key safe and never change it, or all encrypted API keys will be permanently lost! |
| 39 | + |
| 40 | +## Migration Steps |
| 41 | + |
| 42 | +### Option 1: Run the Migration Script (Recommended) |
| 43 | + |
| 44 | +The migration script will encrypt all existing API keys in your database: |
| 45 | + |
| 46 | +1. **Ensure the application is NOT being used** (stop the server) |
| 47 | +2. **Set the ENCRYPTION_KEY** environment variable |
| 48 | +3. **Run the migration script**: |
| 49 | + ```bash |
| 50 | + bun run scripts/migrate-encrypt-api-keys.ts |
| 51 | + ``` |
| 52 | + |
| 53 | +The script will: |
| 54 | +- Show you all keys it's about to encrypt |
| 55 | +- Wait 5 seconds (press Ctrl+C to cancel) |
| 56 | +- Encrypt all unencrypted keys |
| 57 | +- Skip keys that are already encrypted |
| 58 | +- Show a summary when complete |
| 59 | + |
| 60 | +### Option 2: Let New Keys Be Encrypted (No Migration) |
| 61 | + |
| 62 | +If you prefer not to encrypt existing keys: |
| 63 | +- New keys will automatically be encrypted when added |
| 64 | +- Existing unencrypted keys will continue to work (the app detects and handles both) |
| 65 | +- You can run the migration script later if desired |
| 66 | + |
| 67 | +### Option 3: Skip Encryption Entirely (Graceful Degradation) |
| 68 | + |
| 69 | +The application supports running without encryption for compatibility: |
| 70 | + |
| 71 | +- **Without `ENCRYPTION_KEY` set**: API keys are stored in plain text (like before) |
| 72 | +- A warning is logged on startup: `⚠️ ENCRYPTION_KEY not set. API keys will be stored in plain text.` |
| 73 | +- The application continues to work normally |
| 74 | +- You can enable encryption later by setting `ENCRYPTION_KEY` and running the migration script |
| 75 | + |
| 76 | +## Verification |
| 77 | + |
| 78 | +After migration, you can verify encryption worked by checking the database: |
| 79 | + |
| 80 | +```bash |
| 81 | +# For SQLite |
| 82 | +sqlite3 data/nanochat.db "SELECT key FROM user_keys LIMIT 5;" |
| 83 | +sqlite3 data/nanochat.db "SELECT key FROM api_keys LIMIT 5;" |
| 84 | +``` |
| 85 | + |
| 86 | +Encrypted keys will be long base64 strings (150+ characters), while unencrypted keys are shorter. |
| 87 | + |
| 88 | +## How It Works |
| 89 | + |
| 90 | +### Key Storage Flow |
| 91 | + |
| 92 | +1. **When a user adds an API key**: |
| 93 | + - The key is received via the API |
| 94 | + - Immediately encrypted using `encryptApiKey()` |
| 95 | + - Stored in the database in encrypted form |
| 96 | + |
| 97 | +2. **When an API key is needed**: |
| 98 | + - Retrieved from database (encrypted) |
| 99 | + - Decrypted using `decryptApiKey()` |
| 100 | + - Used for API calls |
| 101 | + - Never returned to the client (masked instead) |
| 102 | + |
| 103 | +3. **For legacy unencrypted keys**: |
| 104 | + - The `isEncrypted()` helper detects encryption |
| 105 | + - Unencrypted keys are used as-is |
| 106 | + - This allows gradual migration |
| 107 | + |
| 108 | +### Security Considerations |
| 109 | + |
| 110 | +✅ **What encryption protects against**: |
| 111 | +- Database dumps/file exposure |
| 112 | +- SQL injection attacks that expose the database |
| 113 | +- Backup database access |
| 114 | + |
| 115 | +❌ **What encryption does NOT protect against**: |
| 116 | +- Application server compromise (the key is in memory during use) |
| 117 | +- Environment variable exposure on the server |
| 118 | +- Process debugging/memory dumps |
| 119 | + |
| 120 | +### Best Practices |
| 121 | + |
| 122 | +1. **Never commit the ENCRYPTION_KEY to version control** |
| 123 | +2. **Rotate the encryption key** (requires special handling - not yet implemented) |
| 124 | +3. **Use strong environment variable security** in production |
| 125 | +4. **Keep backups** before any migration |
| 126 | +5. **Document the key location** for disaster recovery |
| 127 | + |
| 128 | +## Troubleshooting |
| 129 | + |
| 130 | +### "ENCRYPTION_KEY environment variable is not set" |
| 131 | + |
| 132 | +**Solution**: Add the ENCRYPTION_KEY to your `.env` file: |
| 133 | +```bash |
| 134 | +ENCRYPTION_KEY=$(openssl rand -base64 32) |
| 135 | +``` |
| 136 | + |
| 137 | +### "ENCRYPTION_KEY must be at least 32 characters" |
| 138 | + |
| 139 | +**Solution**: Generate a longer key: |
| 140 | +```bash |
| 141 | +openssl rand -base64 32 |
| 142 | +``` |
| 143 | + |
| 144 | +### Keys stopped working after migration |
| 145 | + |
| 146 | +**Solution**: This likely means the ENCRYPTION_KEY used during migration is different from the one the application is using. Either: |
| 147 | +- Restore from backup and migrate again with the correct key |
| 148 | +- Ensure the same ENCRYPTION_KEY is set in all environments |
| 149 | + |
| 150 | +## Rollback |
| 151 | + |
| 152 | +If you need to rollback: |
| 153 | + |
| 154 | +1. Stop the application |
| 155 | +2. Restore your database backup: |
| 156 | + ```bash |
| 157 | + cp data/nanochat.db.backup data/nanochat.db |
| 158 | + ``` |
| 159 | +3. Remove or comment out the `ENCRYPTION_KEY` from your `.env` file |
| 160 | +4. Restart the application |
| 161 | + |
| 162 | +Note: This will revert to storing API keys in plain text. |
0 commit comments