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

  1. Navigate to Settings > API Keys
  2. Find the key to rotate
  3. Click Rotate Key
  4. Copy the new key immediately
  5. 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:

  1. Create a new key (don't rotate yet)
  2. Update your application to use the new key
  3. Deploy the update
  4. Verify everything works with the new key
  5. 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

  1. Navigate to Settings > API Keys
  2. Find the compromised key
  3. Click Revoke
  4. 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

  1. Create a new key
  2. Update all applications using the old key
  3. Review logs for suspicious activity during exposure window
  4. 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.*.local

What 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:

  1. Immediately revoke the key (it's in git history forever)
  2. Create a new key
  3. Use tools like git-secrets to 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 keys

Never 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 instead

Never 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]}...")  # OK

Monitoring 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-cicd

This 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:

  1. Revoke any keys they created
  2. Rotate shared keys they had access to
  3. Review audit logs for their access
  4. Update any systems using their keys

Emergency Response

If You Suspect Compromise

  1. Revoke the key immediately
  2. Create a new key
  3. Update affected applications
  4. Review logs for unauthorized activity
  5. Check for data access or modification
  6. 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
  • .env files 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