diff --git a/EssentialCSharp.Chat.Shared/Models/EmbeddingRetryOptions.cs b/EssentialCSharp.Chat.Shared/Models/EmbeddingRetryOptions.cs index a85b3e53..284014fd 100644 --- a/EssentialCSharp.Chat.Shared/Models/EmbeddingRetryOptions.cs +++ b/EssentialCSharp.Chat.Shared/Models/EmbeddingRetryOptions.cs @@ -42,8 +42,9 @@ public sealed class EmbeddingRetryOptions public int MaxEmbeddingBatchSize { get; set; } = 1024; /// - /// Minimum delay between embedding API requests in milliseconds. - /// This adds request pacing to reduce sustained rate-limit pressure. + /// Minimum delay between embedding API requests made by a batch rebuild, in milliseconds. + /// This adds request pacing to reduce sustained rate-limit pressure. Interactive query + /// embeddings are not paced. /// [Range(0, 600000)] public int MinInterRequestDelayMs { get; set; } = 250; diff --git a/EssentialCSharp.Chat.Shared/Services/EmbeddingService.cs b/EssentialCSharp.Chat.Shared/Services/EmbeddingService.cs index a192fdb2..a214a265 100644 --- a/EssentialCSharp.Chat.Shared/Services/EmbeddingService.cs +++ b/EssentialCSharp.Chat.Shared/Services/EmbeddingService.cs @@ -318,12 +318,15 @@ private async Task ExecuteWithRetryAsync( /// Generate an embedding for the given text. /// Automatically retries on transient Azure OpenAI failures. /// + /// + /// Used for interactive queries (chat and MCP search), so it does not take the process-wide pacing lock that + /// spaces out batch rebuild requests: one caller's burst of queries must not queue every other user's search + /// behind it. + /// public async Task> GenerateEmbeddingAsync(string text, CancellationToken cancellationToken = default) { var embedding = await ExecuteWithRetryAsync( - async ct => await ExecuteEmbeddingRequestWithPacingAsync( - async pacingCt => await embeddingGenerator.GenerateAsync(text, cancellationToken: pacingCt), - ct), + async ct => await embeddingGenerator.GenerateAsync(text, cancellationToken: ct), "GenerateEmbedding", cancellationToken); return embedding.Vector; diff --git a/EssentialCSharp.Chat.Tests/EmbeddingServiceTests.cs b/EssentialCSharp.Chat.Tests/EmbeddingServiceTests.cs new file mode 100644 index 00000000..4990ba5f --- /dev/null +++ b/EssentialCSharp.Chat.Tests/EmbeddingServiceTests.cs @@ -0,0 +1,49 @@ +using EssentialCSharp.Chat.Common.Models; +using EssentialCSharp.Chat.Common.Services; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.Options; +using Microsoft.Extensions.VectorData; +using Moq; + +namespace EssentialCSharp.Chat.Tests; + +public class EmbeddingServiceTests +{ + // Regression test: interactive query embeddings used to share one process-wide, paced queue with batch + // rebuilds, so a burst of MCP tool calls from one user stalled every other user's search behind it. + [Test] + public async Task GenerateEmbeddingAsync_ConcurrentQueries_RunConcurrentlyRatherThanQueueing() + { + const int concurrentQueries = 5; + int started = 0; + TaskCompletionSource allStarted = new(TaskCreationOptions.RunContinuationsAsynchronously); + TaskCompletionSource release = new(TaskCreationOptions.RunContinuationsAsynchronously); + + Mock>> generator = new(); + generator + .Setup(g => g.GenerateAsync(It.IsAny>(), It.IsAny(), It.IsAny())) + .Returns(async (IEnumerable _, EmbeddingGenerationOptions? _, CancellationToken cancellationToken) => + { + if (Interlocked.Increment(ref started) == concurrentQueries) + { + allStarted.TrySetResult(); + } + await release.Task.WaitAsync(cancellationToken); + return new GeneratedEmbeddings>([new Embedding(new float[8])]); + }); + EmbeddingService service = new( + new Mock().Object, + generator.Object, + Options.Create(new EmbeddingRetryOptions { MinInterRequestDelayMs = 250 })); + + Task>[] queries = [.. Enumerable.Range(0, concurrentQueries) + .Select(i => service.GenerateEmbeddingAsync($"query {i}"))]; + + // With a shared serialized queue only one request would be in flight, and this would time out. + Task finished = await Task.WhenAny(allStarted.Task, Task.Delay(TimeSpan.FromSeconds(10))); + release.TrySetResult(); + await Task.WhenAll(queries); + + await Assert.That(finished).IsSameReferenceAs(allStarted.Task); + } +} diff --git a/EssentialCSharp.Web.Tests/BookGuidelinesToolTests.cs b/EssentialCSharp.Web.Tests/BookGuidelinesToolTests.cs new file mode 100644 index 00000000..14689702 --- /dev/null +++ b/EssentialCSharp.Web.Tests/BookGuidelinesToolTests.cs @@ -0,0 +1,39 @@ +using EssentialCSharp.Web.Services; +using EssentialCSharp.Web.Tools; +using Moq; + +namespace EssentialCSharp.Web.Tests; + +public class BookGuidelinesToolTests +{ + private static BookGuidelinesTool CreateTool() + { + Mock guidelines = new(); + guidelines.SetupGet(g => g.Guidelines).Returns([]); + return new BookGuidelinesTool(guidelines.Object); + } + + [Test] + public async Task GetCSharpGuidelines_TopicOverTheLimit_IsRejectedWithoutBeingEchoed() + { + string topic = string.Join(' ', Enumerable.Repeat("word", 200)); + + string result = CreateTool().GetCSharpGuidelines(topic: topic); + + using (Assert.Multiple()) + { + await Assert.That(result).IsEqualTo("Topic is too long (maximum 500 characters)."); + await Assert.That(result).DoesNotContain("word word"); + } + } + + [Test] + public async Task GetCSharpGuidelines_TopicAtTheLimit_IsSearched() + { + string topic = new('a', BookGuidelinesTool.MaxTopicLength); + + string result = CreateTool().GetCSharpGuidelines(topic: topic); + + await Assert.That(result).StartsWith("No guidelines found related to", StringComparison.Ordinal); + } +} diff --git a/EssentialCSharp.Web.Tests/McpBearerRateLimitIsolationTests.cs b/EssentialCSharp.Web.Tests/McpBearerRateLimitIsolationTests.cs new file mode 100644 index 00000000..ecc1989d --- /dev/null +++ b/EssentialCSharp.Web.Tests/McpBearerRateLimitIsolationTests.cs @@ -0,0 +1,79 @@ +using System.Net; +using EssentialCSharp.Web.Data; +using EssentialCSharp.Web.Services; +using Microsoft.Extensions.DependencyInjection; + +namespace EssentialCSharp.Web.Tests; + +/// +/// Regression tests: an MCP bearer token acts as its user only on the MCP transport (POST /mcp). Elsewhere it must +/// not spend the owner's site-wide or content rate-limit budget, or a leaked token could lock the owner out of the +/// site, including the page they would use to revoke it. +/// +public class McpBearerRateLimitIsolationTests : IntegrationTestBase +{ + private const int GlobalPermitLimit = 30; + + private static async Task SendBearerGetsAsync(HttpClient client, string path, string rawToken, int count) + { + for (int i = 0; i < count; i++) + { + using HttpRequestMessage request = new(HttpMethod.Get, path); + McpTestHelper.AddBearerToken(request, rawToken); + request.Headers.Accept.ParseAdd("text/event-stream"); + using HttpResponseMessage response = await client.SendAsync(request); + } + } + + private static async Task SendWithCookieAsync(HttpClient client, HttpMethod method, string path, (string Name, string Value) cookie) + { + using HttpRequestMessage request = new(method, path); + McpTestHelper.AddCookie(request, cookie.Name, cookie.Value); + using HttpResponseMessage response = await client.SendAsync(request); + return response.StatusCode; + } + + [Test] + public async Task BearerRequestsToTheGetShim_DoNotSpendTheOwnersSiteBucket() + { + (string userId, string rawToken) = await McpTestHelper.CreateUserAndTokenAsync(Factory, "isolation", userPrefix: "mcp-isolation"); + (string Name, string Value) ownerCookie = await McpTestHelper.CreateIdentityApplicationCookieAsync(Factory, userId); + HttpClient client = McpTestHelper.CreateClient(Factory); + + await SendBearerGetsAsync(client, "/mcp", rawToken, GlobalPermitLimit + 1); + HttpStatusCode ownerPage = await SendWithCookieAsync(client, HttpMethod.Get, "/Identity/Account/Manage/McpAccess", ownerCookie); + + await Assert.That(ownerPage).IsEqualTo(HttpStatusCode.OK); + } + + [Test] + public async Task BearerRequestsToOtherMcpPaths_DoNotSpendTheOwnersContentBucket() + { + (string userId, string rawToken) = await McpTestHelper.CreateUserAndTokenAsync(Factory, "isolation", userPrefix: "mcp-isolation"); + (string Name, string Value) ownerCookie = await McpTestHelper.CreateIdentityApplicationCookieAsync(Factory, userId); + HttpClient client = McpTestHelper.CreateClient(Factory); + + await SendBearerGetsAsync(client, "/mcp/anything", rawToken, 20); + HttpStatusCode ownerContent = await SendWithCookieAsync(client, HttpMethod.Get, "/hello-world", ownerCookie); + + await Assert.That(ownerContent).IsNotEqualTo(HttpStatusCode.TooManyRequests); + } + + [Test] + public async Task OwnerCanStillRevokeTheTokenAfterABearerBurst() + { + (string userId, string rawToken) = await McpTestHelper.CreateUserAndTokenAsync(Factory, "isolation", userPrefix: "mcp-isolation"); + (string Name, string Value) ownerCookie = await McpTestHelper.CreateIdentityApplicationCookieAsync(Factory, userId); + Guid tokenId = InServiceScope(services => + { + byte[] hash = McpApiTokenService.HashToken(rawToken); + return services.GetRequiredService().McpApiTokens.Single(t => t.TokenHash == hash).Id; + }); + HttpClient client = McpTestHelper.CreateClient(Factory); + + await SendBearerGetsAsync(client, "/mcp", rawToken, GlobalPermitLimit + 1); + HttpStatusCode revoke = await SendWithCookieAsync(client, HttpMethod.Delete, $"/api/McpToken/{tokenId}", ownerCookie); + + await Assert.That(revoke).IsEqualTo(HttpStatusCode.NoContent); + } +} diff --git a/EssentialCSharp.Web.Tests/ReferralTrackingMiddlewareTests.cs b/EssentialCSharp.Web.Tests/ReferralTrackingMiddlewareTests.cs new file mode 100644 index 00000000..52a73145 --- /dev/null +++ b/EssentialCSharp.Web.Tests/ReferralTrackingMiddlewareTests.cs @@ -0,0 +1,84 @@ +using EssentialCSharp.Web.Areas.Identity.Data; +using EssentialCSharp.Web.Data; +using EssentialCSharp.Web.Services.Referrals; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; + +namespace EssentialCSharp.Web.Tests; + +/// +/// Regression tests: every page view with ?rid= counts toward the referrer, but requests to endpoints that skip rate +/// limiting (which aren't page views) don't. +/// +public class ReferralTrackingMiddlewareTests : IntegrationTestBase +{ + [Test] + [Arguments("/health")] + [Arguments("/alive")] + [Arguments("/version")] + [Arguments("/.well-known/anything")] + public async Task RateLimitExemptEndpoints_DoNotCountReferrals(string path) + { + (string userId, string referralId) = await CreateReferrerAsync(); + using HttpClient client = CreateClientWithoutAutoRedirect(); + + for (int i = 0; i < 5; i++) + { + using HttpResponseMessage response = await client.GetAsync($"{path}?rid={referralId}"); + } + + await Assert.That(await GetReferralCountAsync(userId)).IsEqualTo(0); + } + + [Test] + public async Task RepeatPageViewsByTheSameVisitor_EachCount() + { + (string userId, string referralId) = await CreateReferrerAsync(); + using HttpClient client = CreateClientWithoutAutoRedirect(); + + for (int i = 0; i < 2; i++) + { + using HttpResponseMessage response = await client.GetAsync($"/hello-world?rid={referralId}"); + } + + await Assert.That(await GetReferralCountAsync(userId)).IsEqualTo(2); + } + + [Test] + public async Task PageViewsByDifferentVisitors_EachCount() + { + (string userId, string referralId) = await CreateReferrerAsync(); + using HttpClient client = CreateClientWithoutAutoRedirect(); + + foreach (string visitorPrefix in new[] { "visitor-a", "visitor-b" }) + { + string visitorId = await McpTestHelper.CreateUserAsync(Factory.Services, visitorPrefix); + (string name, string value) = await McpTestHelper.CreateIdentityApplicationCookieAsync(Factory.Services, visitorId); + using HttpRequestMessage request = new(HttpMethod.Get, $"/hello-world?rid={referralId}"); + McpTestHelper.AddCookie(request, name, value); + using HttpResponseMessage response = await client.SendAsync(request); + } + + await Assert.That(await GetReferralCountAsync(userId)).IsEqualTo(2); + } + + private async Task<(string UserId, string ReferralId)> CreateReferrerAsync() + { + string userId = await McpTestHelper.CreateUserAsync(Factory.Services, "referrer"); + string referralId = await InServiceScopeAsync(async services => + { + EssentialCSharpWebUser user = await services.GetRequiredService>().FindByIdAsync(userId) + ?? throw new InvalidOperationException("Referrer was not created."); + return await services.GetRequiredService().EnsureReferralIdAsync(user) + ?? throw new InvalidOperationException("No referral ID."); + }); + return (userId, referralId); + } + + private Task GetReferralCountAsync(string userId) => InServiceScopeAsync(services => + services.GetRequiredService().Users + .Where(u => u.Id == userId) + .Select(u => u.ReferralCount) + .SingleAsync()); +} diff --git a/EssentialCSharp.Web/Middleware/ReferralTrackingMiddleware.cs b/EssentialCSharp.Web/Middleware/ReferralTrackingMiddleware.cs index 54ec89c9..dc974f4b 100644 --- a/EssentialCSharp.Web/Middleware/ReferralTrackingMiddleware.cs +++ b/EssentialCSharp.Web/Middleware/ReferralTrackingMiddleware.cs @@ -2,6 +2,7 @@ using EssentialCSharp.Web.Areas.Identity.Data; using EssentialCSharp.Web.Services.Referrals; using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.RateLimiting; namespace EssentialCSharp.Web.Middleware; @@ -19,7 +20,7 @@ public async Task InvokeAsync(HttpContext context, IReferralService referralServ // Retrieve current referral Id for processing System.Collections.Specialized.NameValueCollection query = HttpUtility.ParseQueryString(context.Request.QueryString.Value ?? string.Empty); string? referralId = query["rid"]; - if (string.IsNullOrWhiteSpace(referralId)) + if (string.IsNullOrWhiteSpace(referralId) || !IsTrackableRequest(context)) { await _Next(context); return; @@ -36,4 +37,13 @@ public async Task InvokeAsync(HttpContext context, IReferralService referralServ await _Next(context); } + + /// + /// Only page views count: GET requests to endpoints that are rate limited. Endpoints that opt out of rate + /// limiting (health checks, /version, /.well-known) are not page views, and counting them would let anyone add + /// to a referral count as fast as they can send requests. + /// + private static bool IsTrackableRequest(HttpContext context) => + HttpMethods.IsGet(context.Request.Method) + && context.GetEndpoint()?.Metadata.GetMetadata() is null; } diff --git a/EssentialCSharp.Web/Program.cs b/EssentialCSharp.Web/Program.cs index 4fffe529..3d31dac9 100644 --- a/EssentialCSharp.Web/Program.cs +++ b/EssentialCSharp.Web/Program.cs @@ -489,12 +489,14 @@ await McpJsonRpcResponseWriter.WriteErrorAsync( app.UseAuthentication(); - // /mcp uses a named non-default scheme. Normalize the principal before - // rate limiting so valid MCP requests partition by MCP user while - // missing/invalid bearer requests fall back to the anonymous/IP bucket - // instead of inheriting the site's cookie principal. + // The MCP transport (POST /mcp) uses a named non-default scheme. Normalize the + // principal before rate limiting so valid MCP requests partition by MCP user while + // missing/invalid bearer requests fall back to the anonymous/IP bucket instead of + // inheriting the site's cookie principal. Only the transport endpoint is normalized: + // elsewhere (including other /mcp paths) a bearer token must not act as the user, or + // its holder could spend the owner's site-wide and content rate-limit budgets. app.UseWhen( - context => context.Request.Path.StartsWithSegments("/mcp"), + context => IsMcpTransportRequest(context.Request), branch => branch.UseMiddleware()); app.UseRateLimiter(); diff --git a/EssentialCSharp.Web/Services/Referrals/ReferralService.cs b/EssentialCSharp.Web/Services/Referrals/ReferralService.cs index 4d0e1325..c42e3b8d 100644 --- a/EssentialCSharp.Web/Services/Referrals/ReferralService.cs +++ b/EssentialCSharp.Web/Services/Referrals/ReferralService.cs @@ -64,7 +64,9 @@ public void TrackReferralAsync(string referralId, ClaimsPrincipal? user) // Check if the referrer ID exists in the claims principal string? claimsReferrerId = user?.GetReferrerId(); - if (claimsReferrerId == referralId) + // The database lookup below is case-insensitive in production (SQL Server collation), so compare the same + // way here: otherwise a referrer could count their own visits by changing the case of their ID. + if (claimsReferrerId is not null && string.Equals(claimsReferrerId, referralId, StringComparison.OrdinalIgnoreCase)) { // If the referrer ID in the claims principal matches the referral ID, do not track the referral return; diff --git a/EssentialCSharp.Web/Tools/BookGuidelinesTool.cs b/EssentialCSharp.Web/Tools/BookGuidelinesTool.cs index 6784c79a..69cb29b6 100644 --- a/EssentialCSharp.Web/Tools/BookGuidelinesTool.cs +++ b/EssentialCSharp.Web/Tools/BookGuidelinesTool.cs @@ -9,6 +9,8 @@ namespace EssentialCSharp.Web.Tools; [McpServerToolType] public sealed class BookGuidelinesTool { + internal const int MaxTopicLength = 500; + private readonly IGuidelinesService _guidelinesService; public BookGuidelinesTool(IGuidelinesService guidelinesService) @@ -33,6 +35,12 @@ public string GetCSharpGuidelines( return "Invalid guideline type. Valid values: 'do', 'consider', 'avoid', 'donot' (also accepts 'do not', 'dont')."; } + // Every word of the topic is matched against every guideline, so bound it like the other tools' inputs. + if (topic?.Length > MaxTopicLength) + { + return $"Topic is too long (maximum {MaxTopicLength} characters)."; + } + IEnumerable filtered = _guidelinesService.Guidelines; if (chapter is int chapterValue)