Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions EssentialCSharp.Chat.Shared/Models/EmbeddingRetryOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,9 @@ public sealed class EmbeddingRetryOptions
public int MaxEmbeddingBatchSize { get; set; } = 1024;

/// <summary>
/// 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.
/// </summary>
[Range(0, 600000)]
public int MinInterRequestDelayMs { get; set; } = 250;
Expand Down
9 changes: 6 additions & 3 deletions EssentialCSharp.Chat.Shared/Services/EmbeddingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -318,12 +318,15 @@ private async Task<T> ExecuteWithRetryAsync<T>(
/// Generate an embedding for the given text.
/// Automatically retries on transient Azure OpenAI failures.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public async Task<ReadOnlyMemory<float>> 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;
Expand Down
49 changes: 49 additions & 0 deletions EssentialCSharp.Chat.Tests/EmbeddingServiceTests.cs
Original file line number Diff line number Diff line change
@@ -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<IEmbeddingGenerator<string, Embedding<float>>> generator = new();
generator
.Setup(g => g.GenerateAsync(It.IsAny<IEnumerable<string>>(), It.IsAny<EmbeddingGenerationOptions?>(), It.IsAny<CancellationToken>()))
.Returns(async (IEnumerable<string> _, EmbeddingGenerationOptions? _, CancellationToken cancellationToken) =>
{
if (Interlocked.Increment(ref started) == concurrentQueries)
{
allStarted.TrySetResult();
}
await release.Task.WaitAsync(cancellationToken);
return new GeneratedEmbeddings<Embedding<float>>([new Embedding<float>(new float[8])]);
});
EmbeddingService service = new(
new Mock<VectorStore>().Object,
generator.Object,
Options.Create(new EmbeddingRetryOptions { MinInterRequestDelayMs = 250 }));

Task<ReadOnlyMemory<float>>[] 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);
}
}
39 changes: 39 additions & 0 deletions EssentialCSharp.Web.Tests/BookGuidelinesToolTests.cs
Original file line number Diff line number Diff line change
@@ -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<IGuidelinesService> 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);
}
}
79 changes: 79 additions & 0 deletions EssentialCSharp.Web.Tests/McpBearerRateLimitIsolationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
using System.Net;
using EssentialCSharp.Web.Data;
using EssentialCSharp.Web.Services;
using Microsoft.Extensions.DependencyInjection;

namespace EssentialCSharp.Web.Tests;

/// <summary>
/// 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.
/// </summary>
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<HttpStatusCode> 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<EssentialCSharpWebContext>().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);
}
}
84 changes: 84 additions & 0 deletions EssentialCSharp.Web.Tests/ReferralTrackingMiddlewareTests.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
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<UserManager<EssentialCSharpWebUser>>().FindByIdAsync(userId)
?? throw new InvalidOperationException("Referrer was not created.");
return await services.GetRequiredService<IReferralService>().EnsureReferralIdAsync(user)
?? throw new InvalidOperationException("No referral ID.");
});
return (userId, referralId);
}

private Task<int> GetReferralCountAsync(string userId) => InServiceScopeAsync(services =>
services.GetRequiredService<EssentialCSharpWebContext>().Users
.Where(u => u.Id == userId)
.Select(u => u.ReferralCount)
.SingleAsync());
}
12 changes: 11 additions & 1 deletion EssentialCSharp.Web/Middleware/ReferralTrackingMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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;
Expand All @@ -36,4 +37,13 @@ public async Task InvokeAsync(HttpContext context, IReferralService referralServ

await _Next(context);
}

/// <summary>
/// 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.
/// </summary>
private static bool IsTrackableRequest(HttpContext context) =>
HttpMethods.IsGet(context.Request.Method)
&& context.GetEndpoint()?.Metadata.GetMetadata<DisableRateLimitingAttribute>() is null;
}
12 changes: 7 additions & 5 deletions EssentialCSharp.Web/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<McpTokenNormalizationMiddleware>());

app.UseRateLimiter();
Expand Down
4 changes: 3 additions & 1 deletion EssentialCSharp.Web/Services/Referrals/ReferralService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
8 changes: 8 additions & 0 deletions EssentialCSharp.Web/Tools/BookGuidelinesTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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<GuidelineListing> filtered = _guidelinesService.Guidelines;

if (chapter is int chapterValue)
Expand Down
Loading