- Title: Add API Key Rotation Support
- Description: Introduce a mechanism to rotate API keys without downtime, improving long-term security
- Database schema with key lifecycle states (active, deprecated, revoked)
- Expiration support with
expires_atfield - Automatic expiration checking during validation
- Key versioning through multiple active keys
- Metadata field for extensibility
Implementation: src/models/apiKeys.js - Complete key lifecycle management
- Updated middleware to support database-backed keys
- Backward compatibility with legacy environment keys
- Role-based access from database
- Last usage tracking
- Deprecation warnings in response headers
- Integration with RBAC system
Implementation:
src/middleware/apiKeyMiddleware.js- Updated authenticationsrc/middleware/rbacMiddleware.js- Updated role attachment
- Complete rotation guide with best practices
- Quick start reference for common tasks
- CLI tool documentation
- API endpoint documentation
- Migration guide from legacy keys
- Troubleshooting guide
- Security recommendations
Documentation:
docs/API_KEY_ROTATION.md- Complete guidedocs/API_KEY_ROTATION_QUICK_START.md- Quick referencedocs/MIGRATION_TO_DATABASE_KEYS.md- Migration guideREADME.md- Updated with feature description
Status: PASSED
Evidence:
- Keys can be marked as deprecated while remaining functional
deprecateApiKey()function changes status without invalidating key- Deprecated keys return HTTP 200 with warning headers
- Clients receive
X-API-Key-Deprecated: trueheader - Warning header:
299 - "API key is deprecated and will be revoked soon" - Grace period allows gradual client migration
Test Coverage:
// tests/apiKeys.test.js
it('should warn when using deprecated key')
it('should return warning headers when using deprecated key')Usage:
npm run keys -- deprecate --id 1
# Key still works but clients are warnedStatus: PASSED
Evidence:
- Multiple keys can be active simultaneously
- New keys created while old keys remain active
- Backward compatible with legacy
API_KEYSenvironment variable - Middleware checks database first, then falls back to legacy
- Zero downtime during rotation process
- Gradual rollout supported
Rotation Process:
- Create new key (old key still active)
- Deploy new key to clients gradually
- Deprecate old key (still works, warns clients)
- Monitor usage during grace period
- Revoke old key after migration complete
Test Coverage:
// tests/apiKeys.test.js
it('should authenticate with valid database key')
it('should validate active key')
describe('Authentication Middleware')Backward Compatibility:
- Legacy keys in
API_KEYScontinue to work - Database keys and legacy keys coexist
- No breaking changes to existing API
-
Database Model (
src/models/apiKeys.js)- Key creation with hashing
- Validation with expiration checking
- Lifecycle management (deprecate, revoke)
- Listing with filters
- Cleanup of old keys
-
API Routes (
src/routes/apiKeys.js)- POST /api-keys - Create key
- GET /api-keys - List keys
- POST /api-keys/:id/deprecate - Deprecate key
- DELETE /api-keys/:id - Revoke key
- POST /api-keys/cleanup - Clean up old keys
-
CLI Tool (
src/scripts/manageApiKeys.js)- create, list, deprecate, revoke, cleanup commands
- Integrated with npm scripts
- Help documentation
-
Middleware Updates
src/middleware/apiKeyMiddleware.js- Database + legacy supportsrc/middleware/rbacMiddleware.js- Role from database
-
Documentation
- Complete rotation guide
- Quick start reference
- Migration guide
- Updated README
-
Tests (
tests/apiKeys.test.js)- Key creation and validation
- Deprecation and revocation
- Authentication middleware
- Role-based access
- Edge cases
CREATE TABLE api_keys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
key_hash TEXT NOT NULL UNIQUE, -- SHA-256 hash
key_prefix TEXT NOT NULL, -- First 8 chars for identification
name TEXT, -- Descriptive name
role TEXT NOT NULL DEFAULT 'user', -- admin, user, guest
status TEXT NOT NULL DEFAULT 'active', -- active, deprecated, revoked
created_at INTEGER NOT NULL,
expires_at INTEGER, -- Optional expiration
deprecated_at INTEGER,
revoked_at INTEGER,
last_used_at INTEGER, -- Usage tracking
created_by TEXT,
metadata TEXT -- JSON metadata
);- Hashed storage: SHA-256 hashing of keys
- One-time display: Plain text shown only at creation
- Prefix identification: Only first 8 chars stored in plain text
- Audit logging: All operations logged
- Admin-only management: Key endpoints require admin role
- Automatic expiration: Keys can expire automatically
- Rate limiting: API endpoints are rate-limited
"keys": "node src/scripts/manageApiKeys.js",
"keys:create": "node src/scripts/manageApiKeys.js create",
"keys:list": "node src/scripts/manageApiKeys.js list",
"keys:help": "node src/scripts/manageApiKeys.js help"-
Create a key:
npm run keys:create -- --name "Test Key" --role user --expires 365 -
List keys:
npm run keys:list
-
Test authentication:
curl http://localhost:3000/health -H "x-api-key: YOUR_KEY" -
Deprecate key:
npm run keys -- deprecate --id 1 curl http://localhost:3000/health -H "x-api-key: YOUR_KEY" -v # Should see X-API-Key-Deprecated header
-
Revoke key:
npm run keys -- revoke --id 1 curl http://localhost:3000/health -H "x-api-key: YOUR_KEY" # Should return 401 Unauthorized
Run test suite:
npm test tests/apiKeys.test.jsTest coverage includes:
- Key creation with various parameters
- Validation of active, deprecated, revoked, and expired keys
- Authentication middleware behavior
- Role-based access control
- API endpoints (create, list, deprecate, revoke, cleanup)
- Edge cases and error handling
src/models/apiKeys.js- Core modelsrc/routes/apiKeys.js- API routessrc/scripts/manageApiKeys.js- CLI tooldocs/API_KEY_ROTATION.md- Complete guidedocs/API_KEY_ROTATION_QUICK_START.md- Quick referencedocs/MIGRATION_TO_DATABASE_KEYS.md- Migration guidetests/apiKeys.test.js- Test suiteAPI_KEY_ROTATION_IMPLEMENTATION.md- Implementation summaryISSUE_121_COMPLETION_CHECKLIST.md- This file
src/middleware/apiKeyMiddleware.js- Updated authenticationsrc/middleware/rbacMiddleware.js- Updated role attachmentsrc/routes/app.js- Added initialization and routespackage.json- Added npm scripts.env.example- Documented new systemREADME.md- Added feature and documentation links
- Review all code changes
- Run test suite
- Test in development environment
- Create initial admin key
- Document admin key securely
- Update deployment documentation
- Deploy to staging
- Test rotation process in staging
- Deploy to production
- Create production keys
- Migrate clients from legacy keys
- Monitor for issues
- Schedule first rotation
✅ All tasks completed ✅ All acceptance criteria met ✅ Comprehensive documentation provided ✅ Test coverage implemented ✅ Backward compatibility maintained ✅ Zero-downtime rotation supported
Issue #121 is complete and ready for review.