|
| 1 | +using System.Security.Cryptography; |
| 2 | +using System.Text; |
| 3 | +using Microsoft.EntityFrameworkCore; |
| 4 | +using Taskdeck.Api.Contracts; |
| 5 | +using Taskdeck.Domain.Entities; |
| 6 | +using Taskdeck.Domain.Exceptions; |
| 7 | +using Taskdeck.Infrastructure.Mcp; |
| 8 | +using Taskdeck.Infrastructure.Persistence; |
| 9 | + |
| 10 | +namespace Taskdeck.Api.Middleware; |
| 11 | + |
| 12 | +/// <summary> |
| 13 | +/// Middleware that authenticates MCP HTTP requests using API keys. |
| 14 | +/// Extracts a Bearer token from the Authorization header, hashes it with SHA-256, |
| 15 | +/// looks up the hash in the ApiKeys table, and sets the user ID in |
| 16 | +/// HttpContext.Items for <see cref="HttpUserContextProvider"/>. |
| 17 | +/// |
| 18 | +/// Only active on the MCP endpoint path (/mcp). REST API endpoints continue |
| 19 | +/// to use JWT authentication. |
| 20 | +/// </summary> |
| 21 | +public sealed class ApiKeyMiddleware |
| 22 | +{ |
| 23 | + private readonly RequestDelegate _next; |
| 24 | + private readonly ILogger<ApiKeyMiddleware> _logger; |
| 25 | + |
| 26 | + /// <summary>The path prefix that triggers API key authentication.</summary> |
| 27 | + private const string McpPathPrefix = "/mcp"; |
| 28 | + |
| 29 | + public ApiKeyMiddleware(RequestDelegate next, ILogger<ApiKeyMiddleware> logger) |
| 30 | + { |
| 31 | + _next = next; |
| 32 | + _logger = logger; |
| 33 | + } |
| 34 | + |
| 35 | + public async Task InvokeAsync(HttpContext context, TaskdeckDbContext dbContext) |
| 36 | + { |
| 37 | + // Only authenticate MCP endpoint requests |
| 38 | + if (!context.Request.Path.StartsWithSegments(McpPathPrefix, StringComparison.OrdinalIgnoreCase)) |
| 39 | + { |
| 40 | + await _next(context); |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + var authHeader = context.Request.Headers.Authorization.ToString(); |
| 45 | + if (string.IsNullOrWhiteSpace(authHeader)) |
| 46 | + { |
| 47 | + await WriteErrorResponse(context, StatusCodes.Status401Unauthorized, |
| 48 | + "Missing Authorization header. Provide a Bearer token with your API key."); |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + if (!authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) |
| 53 | + { |
| 54 | + await WriteErrorResponse(context, StatusCodes.Status401Unauthorized, |
| 55 | + "Invalid Authorization header format. Use: Bearer tdsk_..."); |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + var token = authHeader["Bearer ".Length..].Trim(); |
| 60 | + |
| 61 | + if (string.IsNullOrWhiteSpace(token) || !token.StartsWith(ApiKey.KeyPrefix)) |
| 62 | + { |
| 63 | + await WriteErrorResponse(context, StatusCodes.Status401Unauthorized, |
| 64 | + "Invalid API key format. Keys must start with 'tdsk_'."); |
| 65 | + return; |
| 66 | + } |
| 67 | + |
| 68 | + // Hash the provided key and look up in the database |
| 69 | + var keyHash = HashKey(token); |
| 70 | + |
| 71 | + var apiKey = await dbContext.ApiKeys |
| 72 | + .AsNoTracking() |
| 73 | + .FirstOrDefaultAsync(k => k.KeyHash == keyHash, context.RequestAborted); |
| 74 | + |
| 75 | + if (apiKey is null) |
| 76 | + { |
| 77 | + _logger.LogWarning("MCP API key authentication failed: key not found (prefix: {Prefix})", |
| 78 | + token.Length >= 8 ? token[..8] : "short"); |
| 79 | + await WriteErrorResponse(context, StatusCodes.Status401Unauthorized, |
| 80 | + "Invalid API key."); |
| 81 | + return; |
| 82 | + } |
| 83 | + |
| 84 | + if (!apiKey.IsActive) |
| 85 | + { |
| 86 | + var reason = apiKey.RevokedAt is not null ? "revoked" : "expired"; |
| 87 | + _logger.LogWarning("MCP API key authentication failed: key is {Reason} (id: {KeyId})", |
| 88 | + reason, apiKey.Id); |
| 89 | + // Return generic message to avoid leaking key state (revoked vs expired) |
| 90 | + await WriteErrorResponse(context, StatusCodes.Status401Unauthorized, |
| 91 | + "Invalid API key."); |
| 92 | + return; |
| 93 | + } |
| 94 | + |
| 95 | + // Verify the user account is active |
| 96 | + var user = await dbContext.Users |
| 97 | + .AsNoTracking() |
| 98 | + .FirstOrDefaultAsync(u => u.Id == apiKey.UserId, context.RequestAborted); |
| 99 | + |
| 100 | + if (user is null || !user.IsActive) |
| 101 | + { |
| 102 | + _logger.LogWarning("MCP API key authentication failed: user inactive (userId: {UserId})", apiKey.UserId); |
| 103 | + await WriteErrorResponse(context, StatusCodes.Status401Unauthorized, |
| 104 | + "User account is inactive or has been deleted."); |
| 105 | + return; |
| 106 | + } |
| 107 | + |
| 108 | + // Set the authenticated user ID for HttpUserContextProvider |
| 109 | + context.Items[HttpUserContextProvider.UserIdItemKey] = apiKey.UserId; |
| 110 | + |
| 111 | + // Update last-used timestamp before continuing the pipeline. |
| 112 | + // This is non-critical so failures are swallowed. |
| 113 | + await UpdateLastUsedAsync(dbContext, apiKey.Id); |
| 114 | + |
| 115 | + await _next(context); |
| 116 | + } |
| 117 | + |
| 118 | + private static string HashKey(string plaintextKey) |
| 119 | + { |
| 120 | + var bytes = Encoding.UTF8.GetBytes(plaintextKey); |
| 121 | + var hash = SHA256.HashData(bytes); |
| 122 | + return Convert.ToHexString(hash).ToLowerInvariant(); |
| 123 | + } |
| 124 | + |
| 125 | + private async Task UpdateLastUsedAsync(TaskdeckDbContext dbContext, Guid keyId) |
| 126 | + { |
| 127 | + try |
| 128 | + { |
| 129 | + // Direct update to avoid concurrency issues with the read-only query above. |
| 130 | + await dbContext.ApiKeys |
| 131 | + .Where(k => k.Id == keyId) |
| 132 | + .ExecuteUpdateAsync(setters => setters |
| 133 | + .SetProperty(k => k.LastUsedAt, DateTimeOffset.UtcNow) |
| 134 | + .SetProperty(k => k.UpdatedAt, DateTimeOffset.UtcNow)); |
| 135 | + } |
| 136 | + catch (Exception ex) |
| 137 | + { |
| 138 | + // Non-critical: if usage tracking fails, authentication still succeeds. |
| 139 | + _logger.LogDebug(ex, "Failed to update API key last-used timestamp for key {KeyId}", keyId); |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + private static async Task WriteErrorResponse(HttpContext context, int statusCode, string message) |
| 144 | + { |
| 145 | + context.Response.StatusCode = statusCode; |
| 146 | + context.Response.ContentType = "application/json"; |
| 147 | + await context.Response.WriteAsJsonAsync(new ApiErrorResponse( |
| 148 | + ErrorCodes.Unauthorized, |
| 149 | + message)); |
| 150 | + } |
| 151 | +} |
0 commit comments