API Key Security
API keys are sensitive credentials that provide access to your LangMart account and connected AI providers. This guide covers best practices for keeping your keys secure.
Security Fundamentals
Treat Keys Like Passwords
API keys provide full access to your account within their permission scope. If someone obtains your key, they can:
- Make API requests charged to your account
- Access your data and analytics
- Potentially modify your settings (with admin keys)
Always treat API keys with the same care as passwords.
The Principle of Least Privilege
Only grant the minimum permissions necessary:
| Use Case | Recommended Permissions |
|---|---|
| Read-only dashboard | read |
| Standard application | read, write |
| Admin tools only | admin (when absolutely needed) |
Key Rotation
Regularly rotating keys reduces risk from potential exposure.
When to Rotate
- Scheduled: Every 90 days for production keys
- Immediately if:
- Key may have been exposed (logs, screenshots, etc.)
- Team member with access leaves
- Security incident suspected
- Key was accidentally committed to version control
How to Rotate
Using the Web Interface
- Navigate to Settings > API Keys
- Find the key to rotate
- Click Rotate Key
- Copy the new key immediately
- Update your applications with the new key
Using the API
curl -X POST https://api.langmart.ai/api/keys/KEY_ID/rotate \
-H "Authorization: Bearer YOUR_CURRENT_KEY"Response:
{
"id": "key-new-id",
"key": "sk-test-newkey123...",
"key_prefix": "sk-test-newk",
"name": "Production Backend (rotated)",
"permissions": ["read", "write"],
"old_key_id": "key-old-id",
"message": "API key rotated successfully. Please save the new key."
}The old key is automatically revoked when you rotate.
Zero-Downtime Rotation
For production systems, follow this pattern:
- Create a new key (don't rotate yet)
- Update your application to use the new key
- Deploy the update
- Verify everything works with the new key
- Revoke the old key
# Your application can support multiple keys during rotation
import os
# During rotation, set both keys
PRIMARY_KEY = os.environ.get("LANGMART_API_KEY")
BACKUP_KEY = os.environ.get("LANGMART_API_KEY_BACKUP")
def get_client():
try:
return create_client(PRIMARY_KEY)
except AuthenticationError:
return create_client(BACKUP_KEY)Revoking Compromised Keys
If a key may be compromised, revoke it immediately.
Using the Web Interface
- Navigate to Settings > API Keys
- Find the compromised key
- Click Revoke
- Confirm the revocation
Using the API
curl -X DELETE https://api.langmart.ai/api/keys/KEY_ID \
-H "Authorization: Bearer YOUR_ADMIN_KEY"Response:
{
"success": true,
"message": "API key revoked successfully",
"key_id": "key-abc123"
}Note: You cannot revoke the key you're currently using for authentication.
After Revoking
- Create a new key
- Update all applications using the old key
- Review logs for suspicious activity during exposure window
- Consider rotating other credentials if exposure was significant
Storage Best Practices
Environment Variables
Recommended for most applications:
# .bashrc or .zshrc (personal machines)
export LANGMART_API_KEY="sk-test-yourkey..."
# Or in systemd service files
Environment="LANGMART_API_KEY=sk-test-yourkey..."Secret Managers
Recommended for production:
AWS Secrets Manager
import boto3
import json
def get_api_key():
client = boto3.client('secretsmanager')
response = client.get_secret_value(SecretId='langmart/api-key')
return json.loads(response['SecretString'])['api_key']Google Secret Manager
from google.cloud import secretmanager
def get_api_key():
client = secretmanager.SecretManagerServiceClient()
name = "projects/my-project/secrets/langmart-api-key/versions/latest"
response = client.access_secret_version(request={"name": name})
return response.payload.data.decode("UTF-8")HashiCorp Vault
import hvac
def get_api_key():
client = hvac.Client(url='https://vault.example.com')
secret = client.secrets.kv.v2.read_secret_version(
path='langmart/api-key'
)
return secret['data']['data']['api_key'].env Files
Acceptable for development, but add to .gitignore:
# .env file (NEVER commit this!)
LANGMART_API_KEY=sk-test-yourkey....gitignore:
.env
.env.local
.env.*.localWhat NOT to Do
Never Hardcode Keys
# NEVER do this!
client = OpenAI(api_key="sk-test-actualkey...")Never Commit Keys to Git
If you accidentally commit a key:
- Immediately revoke the key (it's in git history forever)
- Create a new key
- Use tools like
git-secretsto prevent future accidents
# Install git-secrets
brew install git-secrets # macOS
# Configure for your repo
cd your-repo
git secrets --install
git secrets --register-aws # Detects AWS keys
git secrets --add 'sk-test-[a-zA-Z0-9]{64}' # Detect LangMart test keys
git secrets --add 'sk-prod-[a-zA-Z0-9]{64}' # Detect LangMart prod keysNever Share Keys in Chat/Email
If you need to share credentials:
- Use a secret manager with temporary access
- Use a secure password manager (1Password, LastPass)
- Never send keys in plain text
Never Include Keys in Frontend Code
// NEVER do this in browser JavaScript!
const apiKey = "sk-test-yourkey...";
// Keys in frontend code are visible to anyone
// Use a backend proxy insteadNever Log Keys
# NEVER log API keys
logger.info(f"Using API key: {api_key}") # DON'T!
# Instead, log only the prefix
logger.info(f"Using API key: {api_key[:12]}...") # OKMonitoring and Auditing
Monitor Key Usage
Regularly check your API key usage:
curl https://api.langmart.ai/api/keys \
-H "Authorization: Bearer YOUR_KEY"Look for:
- Unexpected usage spikes
- Keys with no recent activity (candidates for deletion)
- Keys used from unexpected locations
Review Access Logs
Check request logs for suspicious patterns:
curl https://api.langmart.ai/api/account/request-logs \
-H "Authorization: Bearer YOUR_KEY"Signs of compromise:
- Requests at unusual times
- Requests from unexpected IP addresses
- Requests for resources you don't use
- High error rates (might indicate probing)
Set Up Alerts
Configure alerts for:
- Unusual spending spikes
- High error rates
- Usage from new IP addresses/regions
Team Security
Dedicated Keys Per Service
Don't share keys across multiple services:
Production Backend -> key-prod-backend
Analytics Service -> key-analytics
Mobile App -> key-mobile
CI/CD Pipeline -> key-cicdThis way, if one key is compromised, you only need to rotate that specific key.
Use Organization Keys
For team access, use organization-scoped keys instead of sharing personal keys:
curl -X POST https://api.langmart.ai/api/keys \
-H "Authorization: Bearer ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Team Backend Service",
"permissions": ["read", "write"],
"scope": "organization"
}'Access Control
| Role | Recommended Access |
|---|---|
| Developers | Individual keys for development |
| CI/CD | Dedicated service key |
| Production | Organization key managed by ops |
| Read-only tools | Read-only keys |
Offboarding
When team members leave:
- Revoke any keys they created
- Rotate shared keys they had access to
- Review audit logs for their access
- Update any systems using their keys
Emergency Response
If You Suspect Compromise
- Revoke the key immediately
- Create a new key
- Update affected applications
- Review logs for unauthorized activity
- Check for data access or modification
- Report to security team if applicable
Quick Revocation Script
#!/bin/bash
# emergency-revoke.sh
KEY_ID=$1
AUTH_KEY=$2
if [ -z "$KEY_ID" ] || [ -z "$AUTH_KEY" ]; then
echo "Usage: ./emergency-revoke.sh KEY_ID AUTH_KEY"
exit 1
fi
curl -X DELETE "https://api.langmart.ai/api/keys/$KEY_ID" \
-H "Authorization: Bearer $AUTH_KEY"
echo "Key $KEY_ID revoked. Create a new key immediately."Security Checklist
Use this checklist for regular security audits:
- All production keys use secret managers (not environment variables)
- No keys hardcoded in source code
-
.envfiles are in.gitignore - Keys have minimum necessary permissions
- Production keys are rotated every 90 days
- Unused keys are revoked
- Each service has its own dedicated key
- Team access is via organization keys
- Usage is monitored for anomalies
- Offboarding process includes key revocation
- Git hooks prevent accidental key commits
Related Topics
- Creating API Keys - Set up new keys securely
- Using API Keys - Integration patterns
- Connections Overview - Manage provider credentials