API Key Management & Rotation

Protect your SMS infrastructure from credential theft, unauthorized usage, and billing fraud.

Secure Storage Practices

API keys are equivalent to passwords. Treat them with identical security rigor:

Storage Method Security Level Recommendation
Hardcoded in Source Critical Risk Never do this. Visible in version control history forever
.env Files Good Standard for development; add to .gitignore immediately
Cloud Secrets Manager Excellent AWS Secrets Manager, GCP Secret Manager, Azure Key Vault
HashiCorp Vault Enterprise Grade Dynamic secrets, automatic rotation, audit logging
Kubernetes Secrets Good (with encryption) Enable encryption at rest; avoid default etcd storage

Real Cost of Leakage

A single exposed MacraSMS API key can result in KES 50,000+ in fraudulent SMS charges within hours before detection. Always assume keys will be leaked and design accordingly.

Environment Variables

The minimum viable security for any deployment:

  1. Create .env File: Store MACRASMS_API_KEY=your_key_here in project root
  2. Add to .gitignore: Ensure .env is listed before first commit
  3. Provide Template: Create .env.example with placeholder values for team onboarding
  4. Load Safely: Use established libraries (dotenv, python-dotenv) not custom parsers
  5. Validate on Startup: Fail fast if required keys are missing rather than mid-request
// Node.js example - secure key loading require('dotenv').config(); const MACRASMS_API_KEY = process.env.MACRASMS_API_KEY; if (!MACRASMS_API_KEY) { console.error('FATAL: MACRASMS_API_KEY not configured'); process.exit(1); } // Use in API calls - never log or expose const response = await fetch('https://sms.macrasms.com/api/v1/', { headers: { 'Authorization': `Bearer ${MACRASMS_API_KEY}` } });

Rotation Schedule

Regular rotation limits exposure window if keys are compromised:

Environment Rotation Frequency Method
Development Every 90 days Manual via dashboard; update .env files
Staging Every 60 days Semi-automated; CI/CD pipeline updates secrets
Production Every 30 days Fully automated via secrets manager integration
Post-Incident Immediate Revoke old key instantly; generate new; deploy update
Employee Departure Within 24 hours Rotate all keys they had access to as precaution

Zero-Downtime Rotation

Support dual-key validation during transition period. Accept both old and new keys for 24-48 hours while services update. Never rotate without fallback mechanism.

Access Control & Permissions

Apply principle of least privilege to API key usage:

  • Separate Keys Per Service: Don't share one key across billing, marketing, and OTP systems. Isolate blast radius
  • Read-Only Keys: Use restricted keys for analytics/reporting services that don't need send capability
  • IP Whitelisting: Restrict key usage to known server IPs when possible via dashboard settings
  • Spend Limits: Configure daily/monthly spend caps per key to contain damage from compromise
  • Team Roles: Assign view-only vs admin roles in MacraSMS dashboard; limit who can generate/rotate keys

Monitoring Usage Patterns

Detect anomalies before they become incidents:

  1. Baseline Normal Volume: Document typical daily/hourly send patterns for each key
  2. Set Alert Thresholds: Trigger notifications at 150%, 200%, 300% of baseline volume
  3. Monitor Error Spikes: Sudden 401/403 errors may indicate brute-force attempts against stolen keys
  4. Track Geographic Origins: Unexpected API calls from unfamiliar regions signal compromise
  5. Review Weekly Reports: Manual review catches subtle patterns automated alerts miss
// Example: Anomaly detection middleware const BASELINE_DAILY_SENDS = 5000; const ALERT_THRESHOLD = 2.0; // 200% of baseline async function checkUsageAnomaly(apiKeyId) { const todaySends = await db.query( 'SELECT COUNT(*) as count FROM sms_logs WHERE api_key_id = ? AND DATE(sent_at) = CURDATE()', [apiKeyId] ); if (todaySends.count > BASELINE_DAILY_SENDS * ALERT_THRESHOLD) { await alertSystem.notify({ type: 'USAGE_ANOMALY', apiKeyId, currentVolume: todaySends.count, threshold: BASELINE_DAILY_SENDS * ALERT_THRESHOLD, action: 'CONSIDER_TEMPORARY_SUSPENSION' }); } }

Incident Response Plan

When compromise is suspected, act immediately:

  1. Revoke Key: Disable compromised key in MacraSMS dashboard immediately
  2. Generate Replacement: Create new key with identical permissions
  3. Deploy Update: Push new key to all affected services via secrets manager
  4. Audit Logs: Review all API activity under compromised key for unauthorized sends
  5. Notify Stakeholders: Inform finance team of potential fraudulent charges; contact MacraSMS support
  6. Root Cause Analysis: Determine how key was exposed; fix vulnerability before restoring normal operations

Response Time Target

From detection to key revocation should take under 5 minutes. Pre-authorize emergency rotation procedures so approval delays don't extend exposure window.

Developer Onboarding Security

Prevent accidental exposure during team growth:

  • Security Training: Mandatory session on secret management before granting API access
  • Code Review Checklist: Include "no hardcoded secrets" as required review item
  • Automated Scanning: Integrate tools like GitLeaks, TruffleHog into CI/CD to catch commits containing keys
  • Sandbox Keys First: New developers start with sandbox credentials; production access granted after probation
  • Document Procedures: Maintain internal wiki with step-by-step key management SOPs

Audit Trails & Compliance

Maintain defensible records for security audits:

  • Key Generation Log: Record who created each key, when, and for what purpose
  • Rotation History: Track all rotation events with timestamps and responsible personnel
  • Access Records: Log which services/accounts used each key and when
  • Retention Period: Keep audit logs minimum 2 years for compliance verification
  • Export Capability: Generate PDF/CSV reports for ODPC or internal security audits on demand

Need Security Consultation?

Our team can audit your current API key management practices and recommend improvements.

Request Security Audit