feat(backend): Implement MCP API Key Management System (Story 5.2)
Implemented comprehensive API Key authentication and management system
for MCP Server to ensure only authorized AI agents can access ColaFlow.
## Domain Layer
- Created McpApiKey aggregate root with BCrypt password hashing
- Implemented ApiKeyPermissions value object (read/write, resource/tool filtering)
- Added ApiKeyStatus enum (Active, Revoked)
- Created domain events (ApiKeyCreatedEvent, ApiKeyRevokedEvent)
- API key format: cola_<36 random chars> (cryptographically secure)
- Default expiration: 90 days
## Application Layer
- Implemented McpApiKeyService with full CRUD operations
- Created DTOs for API key creation, validation, and updates
- Validation logic: hash verification, expiration check, IP whitelist
- Usage tracking: last_used_at, usage_count
## Infrastructure Layer
- Created McpDbContext with PostgreSQL configuration
- EF Core entity configuration with JSONB for permissions/IP whitelist
- Implemented McpApiKeyRepository with prefix-based lookup
- Database migration: mcp_api_keys table with indexes
- Created McpApiKeyAuthenticationMiddleware for API key validation
- Middleware validates Authorization: Bearer <api_key> header
## API Layer
- Created McpApiKeysController with REST endpoints:
- POST /api/mcp/keys - Create API Key (returns plain key once!)
- GET /api/mcp/keys - List tenant's API Keys
- GET /api/mcp/keys/{id} - Get API Key details
- PATCH /api/mcp/keys/{id}/metadata - Update name/description
- PATCH /api/mcp/keys/{id}/permissions - Update permissions
- DELETE /api/mcp/keys/{id} - Revoke API Key
- Requires JWT authentication (not API key auth)
## Testing
- Created 17 unit tests for McpApiKey entity
- Created 7 unit tests for ApiKeyPermissions value object
- All 49 tests passing (including existing MCP tests)
- Test coverage > 80% for Domain layer
## Security Features
- BCrypt hashing with work factor 12
- API key shown only once at creation (never logged)
- Key prefix lookup for fast validation (indexed)
- Multi-tenant isolation (tenant_id filter)
- IP whitelist support
- Permission scopes (read/write, resources, tools)
- Automatic expiration after 90 days
## Database Schema
Table: mcp.mcp_api_keys
- Indexes: key_prefix (unique), tenant_id, tenant_user, expires_at, status
- JSONB columns for permissions and IP whitelist
- Soft delete via revoked_at
## Integration
- Updated Program.cs to register MCP module with configuration
- Added MCP DbContext migration in development mode
- Authentication middleware runs before MCP protocol handler
Changes:
- Created 31 new files (2321+ lines)
- Domain: 6 files (McpApiKey, events, repository, value objects)
- Application: 9 files (service, DTOs)
- Infrastructure: 8 files (DbContext, repository, middleware, migration)
- API: 1 file (McpApiKeysController)
- Tests: 2 files (17 + 7 unit tests)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,12 @@
|
||||
using ColaFlow.Modules.Mcp.Application.Handlers;
|
||||
using ColaFlow.Modules.Mcp.Application.Services;
|
||||
using ColaFlow.Modules.Mcp.Domain.Repositories;
|
||||
using ColaFlow.Modules.Mcp.Infrastructure.Middleware;
|
||||
using ColaFlow.Modules.Mcp.Infrastructure.Persistence;
|
||||
using ColaFlow.Modules.Mcp.Infrastructure.Persistence.Repositories;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace ColaFlow.Modules.Mcp.Infrastructure.Extensions;
|
||||
@@ -13,8 +19,21 @@ public static class McpServiceExtensions
|
||||
/// <summary>
|
||||
/// Registers MCP module services
|
||||
/// </summary>
|
||||
public static IServiceCollection AddMcpModule(this IServiceCollection services)
|
||||
public static IServiceCollection AddMcpModule(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
// Register DbContext
|
||||
services.AddDbContext<McpDbContext>(options =>
|
||||
{
|
||||
var connectionString = configuration.GetConnectionString("DefaultConnection");
|
||||
options.UseNpgsql(connectionString);
|
||||
});
|
||||
|
||||
// Register repositories
|
||||
services.AddScoped<IMcpApiKeyRepository, McpApiKeyRepository>();
|
||||
|
||||
// Register application services
|
||||
services.AddScoped<IMcpApiKeyService, McpApiKeyService>();
|
||||
|
||||
// Register protocol handler
|
||||
services.AddScoped<IMcpProtocolHandler, McpProtocolHandler>();
|
||||
|
||||
@@ -29,10 +48,16 @@ public static class McpServiceExtensions
|
||||
|
||||
/// <summary>
|
||||
/// Adds MCP middleware to the application pipeline
|
||||
/// IMPORTANT: Add authentication middleware BEFORE MCP middleware
|
||||
/// </summary>
|
||||
public static IApplicationBuilder UseMcpMiddleware(this IApplicationBuilder app)
|
||||
{
|
||||
// Authentication middleware MUST come first
|
||||
app.UseMiddleware<McpApiKeyAuthenticationMiddleware>();
|
||||
|
||||
// Then the MCP protocol handler
|
||||
app.UseMiddleware<McpMiddleware>();
|
||||
|
||||
return app;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user