Metadata-Version: 2.4
Name: apikeyvault
Version: 1.10.1
Summary: Encrypted API key vault for AI and cloud services, with a CLI and a desktop window
Home-page: https://github.com/beatboxio/apivault
Author: Jason Smith
Author-email: beatboxio@gmail.com
License: MIT
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.25.0
Requires-Dist: cryptography>=41.0.0
Requires-Dist: keyring>=24.0.0
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: license
Dynamic: license-file
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# APIVault

An encrypted vault for your AI and cloud API keys, with a CLI, a desktop
window, live validation that tells you *why* a key failed, and shell
integration. Keys live in one place, scripts read them without prompts, and
nothing is ever stored in plain text.

Created by Jason Smith, built in collaboration with Claude Code. MIT licensed.

## Features

- 🔐 **Encrypted vault**: keys live in `~/.config/apivault/keys.enc`, unlocked by a random key in your OS keyring (macOS Keychain, Windows Credential Manager, Linux Secret Service). No password to type, nothing in plain text.
- 🪟 **Desktop window** (`apivault gui`) and a CLI for adding, editing, validating, and deleting keys.
- ✅ **Honest validation**: every key is checked with its service, and **Show error** tells you why one failed (bad key, expired, blocked region, network down).
- 🤖 **Eleven services**: OpenAI, Anthropic, AssemblyAI, Google Cloud, Deepgram, LALAL.AI, Google service accounts, xAI Grok, ElevenLabs, Sakana AI, AWS. Plus alternate slots for any of them and custom secrets for anything else.
- 📦 **Export and merge**: password-protected export files and a union merge with per-key conflict choices, for keeping several machines in sync.
- 🔍 **Three tiers with source tracking**: environment variables override a project `.env`, which overrides the vault, and every key shows where it came from.
- 🐚 **Shell integration**: `eval "$(apivault shell-init)"` exports everything into a new terminal.
- 🎭 **Key masking**: only the first and last four characters are ever displayed.

## Table of Contents

- [Installation](#installation)
- [Quick Start](#quick-start)
- [Usage in Python Projects](#usage-in-python-projects)
- [Shell Integration](#shell-integration)
- [Migrating Existing Keys](#migrating-existing-keys)
- [Storage Hierarchy](#storage-hierarchy)
- [CLI Commands](#cli-commands)
- [Security Best Practices](#security-best-practices)

## Installation

```bash
pip install apikeyvault
```

The package on PyPI is `apikeyvault`; the import and the commands are `apivault`:

```python
from apivault import get_openai_key
```

Python 3.8 or newer. Tkinter (for `apivault gui`) ships with the python.org
installers; Homebrew Python needs `brew install python-tk`.

For agents and a copy-paste minimal app see [APIVAULT_QUICKSTART.md](APIVAULT_QUICKSTART.md).

### For Development

```bash
git clone git@github.com:beatboxio/apivault.git ~/apivault
cd ~/apivault
python3 -m venv .venv && source .venv/bin/activate
pip install -e .
python -m unittest discover -s tests -t .
```

## Quick Start

### 1. Interactive Setup (Recommended for First Time)

```bash
# Run the interactive CLI
apivault

# This will:
# - Show current key status
# - Let you add/update keys
# - Validate keys against actual APIs
# - Save to your preferred location
```

### 2. Shell Integration Setup

Add to your `~/.zshrc` or `~/.bashrc`:

```bash
# Auto-load API keys in every new shell
if command -v apivault &> /dev/null; then
    eval "$(apivault shell-init)"
fi
```

Then reload your shell:
```bash
source ~/.zshrc  # or ~/.bashrc
```

## Usage in Python Projects

### Basic Usage

```python
# Import the convenience functions
from apivault import get_openai_key, get_anthropic_key, get_assemblyai_key

# Get API keys
openai_key = get_openai_key()
anthropic_key = get_anthropic_key()
assemblyai_key = get_assemblyai_key()

# Use with your favorite libraries
import openai
openai.api_key = get_openai_key()

# Or with Anthropic
import anthropic
client = anthropic.Client(api_key=get_anthropic_key())
```

### Advanced Usage

```python
from apivault import APIVault, get_vault

# Get the vault instance
vault = get_vault()

# Get a key with its source
key, source = vault.get_key_with_source("OPENAI_API_KEY")
print(f"OpenAI key loaded from: {source}")  # Shows: env, project, or global

# Check all keys status
status = vault.check_keys_status()
for service, (configured, source) in status.items():
    print(f"{service}: {'✓' if configured else '✗'} [{source}]")

# Set a key programmatically
vault.set_key("OPENAI_API_KEY", "sk-...", save_to_global=True)
```

### Direct Key Access

```python
from apivault import get_api_key

# Get any key by name
key = get_api_key("OPENAI_API_KEY")
key2 = get_api_key("ANTHROPIC_API_KEY")
key3 = get_api_key("GOOGLE_CLOUD_API_KEY")
```

### Validation Functions

```python
from apivault import test_openai_key, test_anthropic_key

# Validate keys before use
key = get_openai_key()
if key and test_openai_key(key):
    print("OpenAI key is valid!")
else:
    print("OpenAI key is invalid or not configured")
```

## Migrating Existing Keys

### From Environment Variables

If you already have keys in environment variables, APIVault will automatically find them:

```bash
# Your existing setup
export OPENAI_API_KEY="sk-..."
export ANTHROPIC_API_KEY="sk-ant-..."

# APIVault will automatically use these (highest priority)
python -c "from apivault import get_vault; get_vault().print_status()"
```

### From .env Files

If you have an existing `.env` file in your project:

```bash
# Your existing .env file
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...

# APIVault will automatically load these (project priority)
cd your-project
python -c "from apivault import get_vault; get_vault().print_status()"
```

### From Other Locations

To import keys from another location:

```python
# One-time migration script
from apivault import APIVault
import json

# Create vault instance
vault = APIVault()

# If you have keys in a JSON file
with open('/path/to/your/keys.json') as f:
    keys = json.load(f)
    for key_name, key_value in keys.items():
        vault.set_key(key_name, key_value)

# Save to the global vault (encrypted keys.enc; created on first save)
vault.save_to_global_config()
print("Keys migrated to the global vault")
```

### From quantumpoetry Project

If you have existing keys from the quantumpoetry project:

```bash
# Back up an existing vault first (password-protected, works for plain or encrypted vaults)
apivault export ~/apivault-backup.vault

# Or programmatically migrate
python3 << 'EOF'
import sys
sys.path.insert(0, '/path/to/quantumpoetry')
from utils.api_keys import APIVault as OldVault

# Import the new vault
sys.path.insert(0, '/path/to/apivault')
from apivault import APIVault as NewVault

# Copy keys
old_vault = OldVault()
new_vault = NewVault()

for key_name in ['OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'ASSEMBLYAI_API_KEY', 
                 'GOOGLE_CLOUD_API_KEY', 'GOOGLE_CLOUD_API_KEY_2', 'DEEPGRAM_API_KEY']:
    if old_key := old_vault.get_key(key_name):
        new_vault.set_key(key_name, old_key)
        print(f"Migrated: {key_name}")

new_vault.save_to_global_config()
print("Migration complete!")
EOF
```

## Storage Hierarchy

APIVault uses a three-tier priority system:

### 1. Environment Variables `[env]` - Highest Priority
- Session-only, most secure
- Set with: `export OPENAI_API_KEY=sk-...`
- Perfect for CI/CD and production

### 2. Project .env File `[project]` - Medium Priority
- Project-specific configuration
- Located at: `./.env`
- Add to `.gitignore` for security
- Great for development

### 3. Global Config `[global]` - Lowest Priority
- User-wide configuration
- Located at: `~/.config/apivault/keys.enc` (encrypted, see [Vault Encryption](#vault-encryption))
- Legacy plain `keys.json` files are still read; run `apivault encrypt` to convert
- The directory honors `XDG_CONFIG_HOME` (default `~/.config`)
- Shared across all projects
- 600 permissions (owner read/write only)
- Ideal for personal development machine

## CLI Commands

### Interactive Mode
```bash
apivault
# Opens interactive menu to:
# - Add/update API keys
# - Validate keys
# - Save to different locations
# - View current configuration
```

### Shell Integration
```bash
# Output shell export commands
apivault shell-init

# Use in ~/.zshrc or ~/.bashrc:
eval "$(apivault shell-init)"
```

### Help
```bash
apivault --help
```

### Vault Encryption

The global vault is stored encrypted at `~/.config/apivault/keys.enc`. The
random key that unlocks it lives in your OS keyring (macOS Keychain, Windows
Credential Manager, Linux Secret Service), so scripts read keys with no prompt.
On macOS the first read from a new Python may show a one-time "Always Allow"
dialog.

```bash
apivault encrypt                 # convert a legacy plain keys.json to keys.enc
apivault decrypt                 # convert back to plain JSON (asks to confirm)
apivault export mykeys.vault     # password-protected copy for moving machines
apivault import mykeys.vault     # union merge; asks per conflicting key
apivault import mykeys.vault --prefer incoming    # or: --prefer incumbent
```

Keeping several machines in sync: run `apivault export` on each, import the
files on one machine resolving conflicts per key, export that merged vault, and
import it elsewhere with `--prefer incoming`. Delete the export files afterwards.

What encryption does not do: a process running as you can still read keys
through the API or `apivault get`, which is what lets scripts run without a
prompt. If you want to keep keys out of other tools' reach, do not put
`apivault shell-init` in your shell startup, because that exports every key into
every process environment.

### Desktop GUI

```bash
apivault gui        # from a terminal
apivault-gui        # installed alongside; no console window on Windows
```

A window listing every vault entry with a masked value, its validation status,
and where scripts will read it from. Double-click a row to set or change it;
the Google service account row has a file picker. **Validate** and **Validate
all** check keys against the services on demand (never automatically). **Add
custom…** stores any name and secret string as-is, without validation; read it
in Python with `get_api_key("NAME")` or in the shell with `apivault get NAME`.
**Add alternate…** creates a numbered second slot for any service (OpenAI 2 is
stored as `OPENAI_API_KEY_2`); AWS is one row with three fields. **Make base**
promotes an alternate to the base name, swapping with any existing base.
**Import .env…** merges a project `.env` file into the vault. **Show error**
explains an Invalid, Unreachable, or Missing row.
A banner offers to encrypt a plain vault, and **Export…** / **Import…** use
the same password-protected format and merge rules as the CLI.

Tkinter ships with the python.org installers. Homebrew Python needs
`brew install python-tk`; Debian/Ubuntu need `apt install python3-tk`.

## Supported Services

Eleven services, one row each in the CLI and the window. AWS is a single record
holding three keys.

| Service | Key name(s) | Validation |
|---------|-------------|------------|
| OpenAI | `OPENAI_API_KEY` | Models list |
| Anthropic | `ANTHROPIC_API_KEY` | Models list |
| AssemblyAI | `ASSEMBLYAI_API_KEY` | Transcript endpoint |
| Google Cloud | `GOOGLE_CLOUD_API_KEY` | Free Google endpoint; a key the project has not enabled still counts as recognized |
| Deepgram | `DEEPGRAM_API_KEY` | Projects list |
| LALAL.AI | `LALAL_AI_API_KEY` | License check |
| Google Service Account | `GOOGLE_APPLICATION_CREDENTIALS` (a JSON file path) | File exists and has the service-account fields |
| xAI Grok | `XAI_API_KEY` | Models list; keys start with `xai-` |
| ElevenLabs | `ELEVENLABS_API_KEY` | User endpoint |
| Sakana AI | `SAKANA_API_KEY` | Models list; keys start with `fish_`. The API is blocked from UK/EU addresses (403 page), so validation reports Unreachable there and works over a US VPN |
| AWS | `AWS_ACCESS_KEY_ID` + `AWS_SECRET_ACCESS_KEY` + `AWS_DEFAULT_REGION` (optional) | Signed STS identity call, no boto3 needed |

Every validator asks the service; none accepts a key by its shape alone, and a
service that cannot be reached is reported as Unreachable, not Valid.

**Alternates.** Any service can have more slots: `OPENAI_API_KEY_2`,
`OPENAI_API_KEY_3`, and for AWS all three names get the suffix. Create one with
**Add alternate…** in the window or `apivault set openai_2 … --global`; it
validates like the base and is exported by `shell-init`. The old
`GOOGLE_CLOUD_API_KEY_2` is simply Google Cloud's slot 2.

**Custom entries.** Any other `UPPER_SNAKE` name is stored as-is and never
validated. Read it with `get_api_key("NAME")` or `apivault get NAME`.

## Project Integration Examples

### Example 1: FastAPI Application

```python
# app.py
from fastapi import FastAPI, HTTPException
from apivault import get_openai_key, test_openai_key

app = FastAPI()

@app.on_event("startup")
async def startup_event():
    # Validate API key on startup
    key = get_openai_key()
    if not key or not test_openai_key(key):
        raise HTTPException(500, "OpenAI API key not configured or invalid")

@app.get("/generate")
async def generate(prompt: str):
    import openai
    openai.api_key = get_openai_key()
    response = openai.Completion.create(...)
    return response
```

### Example 2: Data Science Notebook

```python
# At the top of your notebook
from apivault import get_vault

# Check what's available
vault = get_vault()
vault.print_status()

# Use keys as needed
import openai
openai.api_key = vault.get_key("OPENAI_API_KEY")
```

### Example 3: CI/CD Pipeline

```yaml
# .github/workflows/test.yml
env:
  OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
  ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}

steps:
  - uses: actions/checkout@v2
  - run: pip install apikeyvault
  - run: python -c "from apivault import get_vault; get_vault().print_status()"
  - run: python your_script.py
```

## Security Best Practices

1. **Never commit API keys** - Always use `.gitignore`
2. **Use environment variables in production** - Most secure
3. **Validate keys regularly** - Use the validation functions
4. **Rotate keys periodically** - Update through the CLI
5. **Use project-specific keys when possible** - Better isolation
6. **Check file permissions** - Global config should be 600
7. **Keep the global vault encrypted** - Run `apivault encrypt` and delete export files once imported

## Troubleshooting

### Keys not loading?

Check the priority order:
```python
from apivault import get_vault
vault = get_vault()
key, source = vault.get_key_with_source("OPENAI_API_KEY")
print(f"Key source: {source}")  # Shows where it's loaded from
```

### Validation failing?

Ask for the reason instead of the bool: select the row in `apivault gui` and
click **Show error**, or in Python:
```python
from apivault.validators import check_openai_key
from apivault import get_openai_key
result = check_openai_key(get_openai_key())
print(result.ok, result.detail)      # e.g. False, "HTTP 401 Unauthorized from https://api.openai.com/v1/models"
```
"Unreachable" means the service could not be contacted (network down, or a
regional block such as Sakana from the UK); the key itself was not judged.

### Vault cannot be read?

`VaultError` names the cause. The two common ones: both `keys.json` and
`keys.enc` exist (delete the one you do not want), or `keys.enc` is present but
this machine's keyring has no vault key (import an export with
`apivault import <file>`). Files under `~/.config/apivault/` should be mode 600:
```bash
chmod 600 ~/.config/apivault/keys.enc
```

## Contributing

Pull requests welcome! Please ensure:
- No API keys in code
- Tests pass
- Code follows existing style

## License

MIT. See [LICENSE](LICENSE).

## Credits

Designed and directed by [Jason Smith](https://github.com/beatboxio). The
code, tests, and documentation were written with Claude Code (Anthropic), with
every feature specified, reviewed, and verified live before release.

## Support

For issues or questions:
- Check existing keys: `apivault`
- Validate configuration: `python -c "from apivault import get_vault; get_vault().print_status()"`
- File an issue on GitHub
