API Key Management
Proper API key management is critical for security. This guide covers best practices for storing, rotating, and monitoring your API keys.
API Key Types
Key Type Prefix Environment Capabilities Test fb_test_Development Test data only, no charges Live fb_live_Production Real verifications, charges apply
Never use test keys in production or live keys in development. Each environment should have its own credentials.
Secure Storage
Environment Variables
The minimum viable approach for local development:
# .env (never commit this file!)
FRAUD_BUSTER_API_KEY = fb_live_your_key_here
FRAUD_BUSTER_SECRET_KEY = your_secret_key_here
// Load from environment
import dotenv from 'dotenv' ;
dotenv . config ();
const client = new TxnCheckClient ({
apiKey: process . env . FRAUD_BUSTER_API_KEY ! ,
secretKey: process . env . FRAUD_BUSTER_SECRET_KEY ,
});
Secrets Manager (Recommended)
Use a dedicated secrets manager for production:
AWS Secrets Manager
HashiCorp Vault
Google Secret Manager
Azure Key Vault
import { SecretsManagerClient , GetSecretValueCommand } from '@aws-sdk/client-secrets-manager' ;
async function getApiKey () : Promise < string > {
const client = new SecretsManagerClient ({ region: 'ap-south-1' });
const response = await client . send (
new GetSecretValueCommand ({
SecretId: 'txncheck/api-keys' ,
})
);
const secrets = JSON . parse ( response . SecretString ! );
return secrets . FRAUD_BUSTER_API_KEY ;
}
import Vault from 'node-vault' ;
async function getApiKey () : Promise < string > {
const vault = Vault ({
endpoint: process . env . VAULT_ADDR ,
token: process . env . VAULT_TOKEN ,
});
const result = await vault . read ( 'secret/data/txncheck' );
return result . data . data . api_key ;
}
import { SecretManagerServiceClient } from '@google-cloud/secret-manager' ;
async function getApiKey () : Promise < string > {
const client = new SecretManagerServiceClient ();
const [ version ] = await client . accessSecretVersion ({
name: 'projects/my-project/secrets/txncheck-api-key/versions/latest' ,
});
return version . payload ! . data ! . toString ();
}
import { SecretClient } from '@azure/keyvault-secrets' ;
import { DefaultAzureCredential } from '@azure/identity' ;
async function getApiKey () : Promise < string > {
const client = new SecretClient (
'https://my-vault.vault.azure.net' ,
new DefaultAzureCredential ()
);
const secret = await client . getSecret ( 'txncheck-api-key' );
return secret . value ! ;
}
Kubernetes Secrets
For containerized deployments:
# secret.yaml
apiVersion : v1
kind : Secret
metadata :
name : txncheck-secrets
type : Opaque
stringData :
api-key : fb_live_your_key_here
secret-key : your_secret_key_here
---
# deployment.yaml
apiVersion : apps/v1
kind : Deployment
spec :
template :
spec :
containers :
- name : app
env :
- name : FRAUD_BUSTER_API_KEY
valueFrom :
secretKeyRef :
name : txncheck-secrets
key : api-key
Key Rotation
Rotate API keys regularly to limit exposure from potential leaks.
Rotation Process
Zero-Downtime Rotation
Support multiple valid keys during rotation:
// config/api-keys.ts
export interface APIKeyConfig {
primary : string ;
secondary ?: string ; // Used during rotation
}
// During rotation, try primary first, fall back to secondary
class RotatingTxnCheckClient {
private primaryClient : TxnCheckClient ;
private secondaryClient ?: TxnCheckClient ;
constructor ( config : APIKeyConfig ) {
this . primaryClient = new TxnCheckClient ({ apiKey: config . primary });
if ( config . secondary ) {
this . secondaryClient = new TxnCheckClient ({ apiKey: config . secondary });
}
}
async upiByMobile ( mobile : string , options : any ) {
try {
return await this . primaryClient . upiByMobile ( mobile , options );
} catch ( error ) {
if ( this . isAuthError ( error ) && this . secondaryClient ) {
console . warn ( 'Primary key failed, trying secondary' );
return await this . secondaryClient . upiByMobile ( mobile , options );
}
throw error ;
}
}
private isAuthError ( error : any ) : boolean {
return error . statusCode === 401 ;
}
}
Rotation Schedule
Environment Rotation Frequency Process Development On demand Regenerate in dashboard Staging Monthly Automated rotation Production Quarterly Manual with verification After incident Immediate Emergency rotation
Scoped API Keys
Request API keys with minimum necessary permissions:
// Key with limited scope
const limitedClient = new TxnCheckClient ({
apiKey: process . env . FRAUD_BUSTER_BLOCKLIST_ONLY_KEY ! ,
// This key only has access to vpa-chargeback-check
});
// Full access key for admin operations
const adminClient = new TxnCheckClient ({
apiKey: process . env . FRAUD_BUSTER_ADMIN_KEY ! ,
});
Contact TxnCheck support to request scoped API keys with limited method access.
Monitoring API Key Usage
Track Key Usage
// middleware/api-tracking.ts
export function trackApiUsage ( keyName : string ) {
return async ( req : Request , res : Response , next : NextFunction ) => {
const startTime = Date . now ();
res . on ( 'finish' , () => {
const duration = Date . now () - startTime ;
// Send to your monitoring system
metrics . increment ( 'fraud_buster.api_calls' , {
key: keyName ,
endpoint: req . path ,
status: res . statusCode ,
duration ,
});
});
next ();
};
}
Alert on Anomalies
Set up alerts for:
Unusual spike in API calls
High error rates (especially 401/403)
Calls from unexpected IP addresses
Usage outside business hours
// Example alert rule (pseudo-code)
const alertRules = [
{
name: 'High Error Rate' ,
condition: 'error_rate > 10% over 5 minutes' ,
action: 'page_oncall' ,
},
{
name: 'Unusual Volume' ,
condition: 'request_count > 3x baseline over 1 hour' ,
action: 'slack_alert' ,
},
{
name: 'Auth Failures' ,
condition: 'status_401_count > 10 in 1 minute' ,
action: 'page_security' ,
},
];
Preventing Key Exposure
Git Pre-commit Hooks
Prevent accidental commits:
# .git/hooks/pre-commit
#!/bin/bash
# Check for API keys
if git diff --cached | grep -E 'fb_(test|live)_[a-zA-Z0-9]+' ; then
echo "ERROR: Possible API key detected in commit"
echo "Remove sensitive data before committing"
exit 1
fi
.gitignore
Always ignore sensitive files:
# .gitignore
.env
.env.local
.env.*.local
*.key
secrets/
Secret Scanning
Enable GitHub secret scanning or use tools like:
# Run GitLeaks before pushing
gitleaks detect --source . --verbose
Emergency Key Revocation
If a key is compromised:
Revoke the compromised key in your TxnCheck dashboard
Generate a new key with same permissions
Update all services using the compromised key
Review logs for unauthorized usage
Automation Script
#!/bin/bash
# emergency-rotate.sh
set -e
echo "🚨 Emergency API Key Rotation"
# Generate new key via API (if available) or manually in dashboard
NEW_KEY = "fb_live_new_key_here"
# Update secrets manager
aws secretsmanager update-secret \
--secret-id txncheck/api-keys \
--secret-string "{ \" FRAUD_BUSTER_API_KEY \" : \" $NEW_KEY \" }"
# Force redeploy services
kubectl rollout restart deployment/my-service
# Revoke old key (via dashboard or API)
echo "⚠️ Remember to revoke the old key in the dashboard!"
echo "✅ Rotation complete"
Best Practices Summary
Use secrets manager in production
Never hardcode keys
Different keys per environment
Rotate quarterly minimum
Immediate rotation after suspected breach
Zero-downtime rotation process
Track all API key usage
Alert on anomalies
Regular access reviews
Pre-commit hooks
Secret scanning in CI/CD
Code review for key exposure