# Configuration key

Secrets Phantom keeps at rest are encrypted with the configuration key:
model provider API keys, bug bounty tokens, session accounts, issue
tracker tokens, webhook secrets, SMTP passwords and Splunk tokens,
passive provider keys and the upstream proxy password. The key is a
Fernet key, read from `PHANTOM_CONFIG_KEY` or, without it, from the key
file next to the database (the `keys` volume in Docker Compose) (created once, readable by its owner only). Back it up with the
database: without it those secrets cannot be read.

## Rotate the key

Rotate it when it may have been exposed, or on a schedule.

1. Make a new key:

   ```
   python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
   ```

2. Put the new key in `PHANTOM_CONFIG_KEY` and the old one in
   `PHANTOM_CONFIG_KEY_PREVIOUS` (several old keys go comma separated),
   then restart. From now on new secrets are encrypted with the new key,
   and old ones still decrypt with the old.

3. Re-encrypt what is stored:

   ```
   python -m scripts.rotate_config_key --check
   python -m scripts.rotate_config_key
   ```

   `--check` lists what would be re-encrypted and writes nothing. The run
   re-encrypts every stored secret with the new key in one transaction.
   If any secret cannot be decrypted with the keys given, it names them
   and writes nothing. With Docker Compose, run it in the backend
   container:
   `docker compose exec backend python -m scripts.rotate_config_key`.

4. Remove `PHANTOM_CONFIG_KEY_PREVIOUS` and restart. Keep the old key
   only as long as backups taken before the rotation may need restoring.

Code: `backend/app/core/config_key.py`, `backend/scripts/rotate_config_key.py`.
