# Per-Provider API Key Management - Testing Guide

## Quick Test Procedure

### 1. Clear Old API Keys (if testing fresh)
```bash
rm -f ~/.downloads/.finnhub/api-key.txt 2>/dev/null
rm -f ~/.downloads/.finnhub/apiKey_*.txt 2>/dev/null
```

### 2. Test PHP Backend Directly

#### Get key for Twelve Data (should be empty initially)
```bash
curl "http://localhost/~rbutare/downloads/api/finnhub-key.php?action=get&provider=twelve"
# Expected: {"key":"","cached":false}
```

#### Set Twelve Data key
```bash
curl -X POST "http://localhost/~rbutare/downloads/api/finnhub-key.php?action=set&provider=twelve" \
  -H "Content-Type: application/json" \
  -d '{"key":"1fc95863eb26405aa1c0925bb7ab7b96"}'
# Expected: {"success":true}
```

#### Verify key was saved
```bash
curl "http://localhost/~rbutare/downloads/api/finnhub-key.php?action=get&provider=twelve"
# Expected: {"key":"1234567890abcdef","cached":false}
```

#### Set Finnhub key (different key)
```bash
curl -X POST "http://localhost/~rbutare/downloads/api/finnhub-key.php?action=set&provider=finnhub" \
  -H "Content-Type: application/json" \
  -d '{"key":"abcdef1234567890"}'
# Expected: {"success":true}
```

#### Verify both keys exist independently
```bash
curl "http://localhost/~rbutare/downloads/api/finnhub-key.php?action=get&provider=finnhub"
# Expected: {"key":"abcdef1234567890","cached":false}
```

#### Delete Finnhub key
```bash
curl "http://localhost/~rbutare/downloads/api/finnhub-key.php?action=delete&provider=finnhub"
# Expected: {"success":true}
```

#### Verify Finnhub key is gone, Twelve Data key remains
```bash
curl "http://localhost/~rbutare/downloads/api/finnhub-key.php?action=get&provider=finnhub"
# Expected: {"key":"","cached":false}

curl "http://localhost/~rbutare/downloads/api/finnhub-key.php?action=get&provider=twelve"
# Expected: {"key":"1234567890abcdef","cached":false}
```

### 3. Test Browser Dashboard

#### Open dashboard
```bash
open "http://localhost/~rbutare/downloads/dash.html"
```

#### First Load
- Should load with Twelve Data as default provider
- If no key found, should prompt for API key
- Enter a test key: `abc123def456xyz789ab`
- Should show success message and save to server

#### Check File Storage
```bash
cat ~/.downloads/.finnhub/apiKey_twelve.txt
# Should contain: abc123def456xyz789ab

ls -la ~/.downloads/.finnhub/
# Should show files with 0600 permissions: -rw------- 
```

#### Open Preferences
- Should show "Twelve Data" and "Finnhub" sections
- Twelve Data field should show masked key (first 4 + dots + last 4)
- Finnhub field should be empty

#### Switch to Finnhub Provider
- Click "Finnhub" in API Provider dropdown
- Dashboard should clear data (no key for Finnhub yet)
- Should show API overlay prompting for key
- Enter Finnhub test key: `xyz789ab456def123`

#### Verify Both Keys Stored
```bash
cat ~/.downloads/.finnhub/apiKey_twelve.txt
# Should show Twelve Data key

cat ~/.downloads/.finnhub/apiKey_finnhub.txt  
# Should show Finnhub key
```

#### Switch Back to Twelve Data
- Click "Twelve Data" in API Provider dropdown
- Dashboard should load with previous Twelve Data key
- Watchlist data should refresh (if Twelve Data key is valid)

#### Open Preferences Again
- Twelve Data field should show masked key from step 1
- Finnhub field should show masked key from step 2

#### Test Key Updates
- Click "Set" button for Finnhub
- Prompt for new key: `new_finnhub_key123456`
- Preferences should update to show new masked key
- File `~/.downloads/.finnhub/apiKey_finnhub.txt` should contain new key

### 4. Test Persistence

#### Refresh Browser
```bash
# F5 or refresh in browser
```

- Twelve Data provider should load
- Should load Twelve Data key from server
- Preferences should show both provider keys (if both have been set)

#### Switch Providers
- Switch to Finnhub
- Should load Finnhub key automatically
- Switch back to Twelve Data
- Should load Twelve Data key automatically

### 5. Test Error Handling

#### Invalid Key (too short)
- Try to set a key with < 10 characters
- Should see error: "API key has invalid length" or similar
- Key should not be saved

#### Invalid Key (too long)
- Try to set a key with > 500 characters
- Should see error about invalid length
- Key should not be saved

#### Missing API Key
- Delete all keys: `rm -f ~/.downloads/.finnhub/apiKey_*.txt`
- Refresh browser
- Should prompt for key or show empty state
- Should show API overlay

## Browser Console Debugging

### Enable Debug Logging
Open browser console and:
```javascript
// Check current provider and key
console.log('API_PROVIDER:', API_PROVIDER);
console.log('API_KEY:', API_KEY);

// Check preferences
console.log('Twelve Data key:', getProviderKey('twelve'));
console.log('Finnhub key:', getProviderKey('finnhub'));

// Manually test server retrieval
serverKeyGet('twelve').then(k => console.log('Server key (twelve):', k));
serverKeyGet('finnhub').then(k => console.log('Server key (finnhub):', k));
```

### Test Provider Switching
```javascript
// Switch to Finnhub
switchApiProvider('finnhub');

// Check if key loaded
console.log('New API_KEY:', API_KEY);
console.log('New API_PROVIDER:', API_PROVIDER);

// Switch back
switchApiProvider('twelve');
```

### Verify Preferences Storage
```javascript
// Save a test key
setProviderKey('twelve', 'test_key_123456789');

// Verify it's in prefs
console.log(prefs.apiKey_twelve);

// Save preferences
savePref();

// Reload preferences and check
loadPrefs();
console.log(prefs.apiKey_twelve);
```

## Expected File Structure

After testing, you should have:
```
~/.downloads/.finnhub/
├── apiKey_twelve.txt      # Twelve Data key (0600 perms)
└── apiKey_finnhub.txt     # Finnhub key (0600 perms)
```

With contents like:
```
apiKey_twelve.txt:  abc123def456xyz789ab
apiKey_finnhub.txt: xyz789ab456def123new
```

## Known Issues & Workarounds

### Issue: Key not persisting after browser refresh
**Solution:** Check that server endpoint is accessible:
```bash
curl -I "http://localhost/~rbutare/downloads/api/finnhub-key.php?action=get&provider=twelve"
# Should return: HTTP/1.1 200 OK
```

### Issue: File permissions wrong
**Solution:** PHP should auto-set 0600 permissions, but manually fix if needed:
```bash
chmod 600 ~/.downloads/.finnhub/apiKey_*.txt
chmod 700 ~/.downloads/.finnhub
```

### Issue: "Failed to retrieve API key from server"
**Solution:** Check browser console for network error, verify:
1. Apache is running: `apache status`
2. Path is correct: `apache files` (find `.downloads/api/finnhub-key.php`)
3. API key file exists and is readable: `ls -la ~/.downloads/.finnhub/`

### Issue: Preferences not updating after key change
**Solution:** Call `updateKeyDisplay()` in browser console:
```javascript
updateKeyDisplay();
```

## Success Criteria

✅ All tests pass when:
1. Two API keys can be stored independently
2. Keys persist across browser refreshes
3. Switching providers loads the correct provider-specific key
4. Preferences UI shows masked keys for both providers
5. API calls use the correct key based on active provider
6. File permissions are restricted (0600 for keys, 0700 for directory)
7. Invalid keys are rejected with helpful error messages
8. Keys can be updated via preferences UI
9. Keys can be deleted from server
