You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
External integrators and partner services need programmatic access to the EquipChain API without going through the Stellar wallet authentication flow (Issue #5). This issue implements an API key management system that allows administrators to generate, revoke, and manage API keys for external services, with granular permission scopes and rate limit tiers.
The API key system must include: Key Generation — admin endpoint to generate a new API key with a name (for identification), expiration date (optional), allowed scopes (comma-separated list of endpoint patterns), and rate limit tier (free, standard, premium); Key Authentication — a middleware that checks for API key in X-API-Key header or api_key query parameter, validates it against the store, and attaches scope information to the request; Scope Enforcement — each protected endpoint must define required scopes, and the middleware must verify the API key's scopes include the required scope for the requested endpoint; Rate Limit Integration — the API key's rate limit tier must override the global rate limit (Issue #6) for key-authenticated requests, allowing different limits per tier (free: 100 req/h, standard: 1000 req/h, premium: 10000 req/h); Usage Tracking — each API key should track request counts, last used timestamp, and total usage for billing or quota monitoring.
The system should store API keys in memory for MVP (similar to other stores), with a migration path to database storage. API keys should be generated as cryptographically random strings (using crypto.randomBytes) prefixed with eq_ for easy identification. The secret key itself should be stored hashed (SHA-256) in the store — the raw key is shown only once at creation time.
Architecture: New src/services/apiKey.js managing key store. New src/middleware/apiKeyAuth.js for authentication and scope enforcement. New src/routes/admin/apiKeys.js for CRUD operations by admins. Integration with rate limiter middleware.
Impact: Essential for B2B integrations. Without API keys, external partners would need to implement Stellar wallet authentication, which may not be feasible for server-to-server integrations. This feature also enables monetization through tiered access.
Step-by-Step Implementation Guide
Create API Key Service: Write src/services/apiKey.js exporting generateKey(name, scopes, tier, expiresAt), validateKey(key), revokeKey(id), listKeys(). Store keys in a Map with hashed key values. Generate keys using crypto.randomBytes(32).toString('hex') with eq_ prefix. Hash using crypto.createHash('sha256').
Create API Key Auth Middleware: Write src/middleware/apiKeyAuth.js that extracts the key from headers/query, hashes it, looks up in store, checks expiration, and attaches req.apiKey with metadata. If key is invalid/expired, return 401. Integrate with rate limiter to apply tier-specific limits.
Create Admin API Key Routes: Write src/routes/admin/apiKeys.js with POST /api/admin/api-keys (create), GET /api/admin/api-keys (list), DELETE /api/admin/api-keys/:id (revoke), PATCH /api/admin/api-keys/:id (update scopes/tier). Mount under admin routes.
Write Tests: Create tests/unit/apiKey.test.js testing key generation (format, uniqueness, hashing), validation (valid, expired, revoked), scope checking. Create tests/integration/apiKey.test.js testing full auth flow via API with supertest.
Verification & Testing Steps
Authenticate as admin and create a new API key via POST /api/admin/api-keys with scopes ["read:meters", "read:readings"] and tier standard. Verify the response includes the raw key (shown only once) and metadata.
Use the generated API key to call a meters endpoint via X-API-Key header — expect 200. Call without the header — expect 401.
Create a key with scope read:meters and try to call an admin endpoint — expect 403 (scope not allowed).
Create a key with tier free and exceed 100 requests in an hour — expect 429 (rate limit exceeded).
Revoke a key via admin endpoint and then use it — expect 401. Verify the revoked key is listed as inactive in the list endpoint.
Description
External integrators and partner services need programmatic access to the EquipChain API without going through the Stellar wallet authentication flow (Issue #5). This issue implements an API key management system that allows administrators to generate, revoke, and manage API keys for external services, with granular permission scopes and rate limit tiers.
The API key system must include: Key Generation — admin endpoint to generate a new API key with a name (for identification), expiration date (optional), allowed scopes (comma-separated list of endpoint patterns), and rate limit tier (free, standard, premium); Key Authentication — a middleware that checks for API key in
X-API-Keyheader orapi_keyquery parameter, validates it against the store, and attaches scope information to the request; Scope Enforcement — each protected endpoint must define required scopes, and the middleware must verify the API key's scopes include the required scope for the requested endpoint; Rate Limit Integration — the API key's rate limit tier must override the global rate limit (Issue #6) for key-authenticated requests, allowing different limits per tier (free: 100 req/h, standard: 1000 req/h, premium: 10000 req/h); Usage Tracking — each API key should track request counts, last used timestamp, and total usage for billing or quota monitoring.The system should store API keys in memory for MVP (similar to other stores), with a migration path to database storage. API keys should be generated as cryptographically random strings (using
crypto.randomBytes) prefixed witheq_for easy identification. The secret key itself should be stored hashed (SHA-256) in the store — the raw key is shown only once at creation time.Technical Context & Impact
crypto(built-in) for key generation and hashing. Integration with rate limiter from Issue [Middleware] Add Request Logging, Error Handling, Rate Limiting, and Request Validation Middleware #6. No additional npm dependencies.src/services/apiKey.jsmanaging key store. Newsrc/middleware/apiKeyAuth.jsfor authentication and scope enforcement. Newsrc/routes/admin/apiKeys.jsfor CRUD operations by admins. Integration with rate limiter middleware.Step-by-Step Implementation Guide
src/services/apiKey.jsexportinggenerateKey(name, scopes, tier, expiresAt),validateKey(key),revokeKey(id),listKeys(). Store keys in a Map with hashed key values. Generate keys usingcrypto.randomBytes(32).toString('hex')witheq_prefix. Hash usingcrypto.createHash('sha256').src/middleware/apiKeyAuth.jsthat extracts the key from headers/query, hashes it, looks up in store, checks expiration, and attachesreq.apiKeywith metadata. If key is invalid/expired, return 401. Integrate with rate limiter to apply tier-specific limits.req.apiKeyand use tier-based limits when present. Define limits: free: 100/hour, standard: 1000/hour, premium: 10000/hour, admin: unlimited.src/routes/admin/apiKeys.jswithPOST /api/admin/api-keys(create),GET /api/admin/api-keys(list),DELETE /api/admin/api-keys/:id(revoke),PATCH /api/admin/api-keys/:id(update scopes/tier). Mount under admin routes.tests/unit/apiKey.test.jstesting key generation (format, uniqueness, hashing), validation (valid, expired, revoked), scope checking. Createtests/integration/apiKey.test.jstesting full auth flow via API with supertest.Verification & Testing Steps
POST /api/admin/api-keyswith scopes["read:meters", "read:readings"]and tierstandard. Verify the response includes the raw key (shown only once) and metadata.X-API-Keyheader — expect 200. Call without the header — expect 401.read:metersand try to call an admin endpoint — expect 403 (scope not allowed).freeand exceed 100 requests in an hour — expect 429 (rate limit exceeded).