From 5929d7ee680c2417bf0b2a75c4b2d4a1010580ce Mon Sep 17 00:00:00 2001 From: Benjamin Michaelis Date: Thu, 26 Nov 2026 13:13:07 -0800 Subject: [PATCH 1/2] Harden MCP rate limits, referrals, guidelines topic and embedding queue (security audit) Fixes the non-Identity findings from the 2026-11 security audit: - Normalize the MCP bearer principal only for the MCP transport (POST /mcp). Elsewhere a bearer token no longer acts as its user, so a leaked token can't spend the owner's site-wide or content rate-limit budgets (and lock them out of revoking it). - Referral tracking skips endpoints that opt out of rate limiting (/health, /alive, /version, /.well-known) and non-GET requests, counts a visitor once per referral ID per 24 hours, and compares the self-referral check case-insensitively like the database lookup. - GetCSharpGuidelines rejects topics over 500 characters, like the sibling tools. - Interactive query embeddings no longer go through the process-wide pacing lock; the 250 ms pacing now applies only to batch rebuilds. Adds regression tests derived from the audit's reproductions. Co-Authored-By: Claude Opus 5.5 --- .../Models/EmbeddingRetryOptions.cs | 5 +- .../Services/EmbeddingService.cs | 9 +- .../EmbeddingServiceTests.cs | 49 +++++++++++ .../BookGuidelinesToolTests.cs | 39 +++++++++ .../McpBearerRateLimitIsolationTests.cs | 79 +++++++++++++++++ .../ReferralTrackingMiddlewareTests.cs | 84 +++++++++++++++++++ .../Middleware/ReferralTrackingMiddleware.cs | 49 +++++++++-- EssentialCSharp.Web/Program.cs | 12 +-- .../Services/Referrals/ReferralService.cs | 4 +- .../Tools/BookGuidelinesTool.cs | 8 ++ 10 files changed, 320 insertions(+), 18 deletions(-) create mode 100644 EssentialCSharp.Chat.Tests/EmbeddingServiceTests.cs create mode 100644 EssentialCSharp.Web.Tests/BookGuidelinesToolTests.cs create mode 100644 EssentialCSharp.Web.Tests/McpBearerRateLimitIsolationTests.cs create mode 100644 EssentialCSharp.Web.Tests/ReferralTrackingMiddlewareTests.cs 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..6bb7cd32 --- /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: anonymous ?rid= requests must not inflate a referrer's count through endpoints that skip rate +/// limiting, and repeat page views by the same visitor count once. +/// +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_CountOnce() + { + (string userId, string referralId) = await CreateReferrerAsync(); + using HttpClient client = CreateClientWithoutAutoRedirect(); + + for (int i = 0; i < 5; i++) + { + using HttpResponseMessage response = await client.GetAsync($"/hello-world?rid={referralId}"); + } + + await Assert.That(await GetReferralCountAsync(userId)).IsEqualTo(1); + } + + [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..fbb6ae79 100644 --- a/EssentialCSharp.Web/Middleware/ReferralTrackingMiddleware.cs +++ b/EssentialCSharp.Web/Middleware/ReferralTrackingMiddleware.cs @@ -1,12 +1,18 @@ +using System.Security.Claims; using System.Web; using EssentialCSharp.Web.Areas.Identity.Data; using EssentialCSharp.Web.Services.Referrals; using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.Extensions.Caching.Memory; namespace EssentialCSharp.Web.Middleware; public sealed class ReferralMiddleware { + // A visitor counts once per referral link per window, however many pages they load with it. + internal static readonly TimeSpan DedupeWindow = TimeSpan.FromHours(24); + private readonly RequestDelegate _Next; public ReferralMiddleware(RequestDelegate next) @@ -14,26 +20,55 @@ public ReferralMiddleware(RequestDelegate next) _Next = next; } - public async Task InvokeAsync(HttpContext context, IReferralService referralService, UserManager userManager) + public async Task InvokeAsync(HttpContext context, IReferralService referralService, UserManager userManager, IMemoryCache memoryCache) { // 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; } - if (context.User is { Identity.IsAuthenticated: true } claimsUser) + if (TryClaimVisit(memoryCache, referralId, GetVisitorKey(context))) { - referralService.TrackReferralAsync(referralId, claimsUser); + if (context.User is { Identity.IsAuthenticated: true } claimsUser) + { + referralService.TrackReferralAsync(referralId, claimsUser); + } + else + { + referralService.TrackReferralAsync(referralId, null); + } } - else + + await _Next(context); + } + + /// + /// Only page views count. Endpoints that opt out of rate limiting (health checks, /version, /.well-known) + /// would otherwise 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; + + private static string GetVisitorKey(HttpContext context) => + context.User.Identity?.IsAuthenticated == true + ? $"user:{context.User.FindFirstValue(ClaimTypes.NameIdentifier)}" + : $"ip:{context.Connection.RemoteIpAddress}"; + + private static bool TryClaimVisit(IMemoryCache memoryCache, string referralId, string visitorKey) + { + // Referral IDs are matched case-insensitively by the database, so dedupe them the same way. + string cacheKey = $"referral-visit:{referralId.ToUpperInvariant()}:{visitorKey}"; + if (memoryCache.TryGetValue(cacheKey, out _)) { - referralService.TrackReferralAsync(referralId, null); + return false; } - await _Next(context); + memoryCache.Set(cacheKey, true, DedupeWindow); + return true; } } 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) From 729f9e3b5594fd50fc39753e99a6216034a9f244 Mon Sep 17 00:00:00 2001 From: Benjamin Michaelis Date: Fri, 27 Nov 2026 09:54:20 -0800 Subject: [PATCH 2/2] Count every referral page view The owner wants page-visit metrics, so drop the per-visitor 24-hour dedupe. GET page views still count; endpoints that skip rate limiting still don't. Co-Authored-By: Claude Opus 5.5 --- .../ReferralTrackingMiddlewareTests.cs | 10 ++--- .../Middleware/ReferralTrackingMiddleware.cs | 45 +++++-------------- 2 files changed, 15 insertions(+), 40 deletions(-) diff --git a/EssentialCSharp.Web.Tests/ReferralTrackingMiddlewareTests.cs b/EssentialCSharp.Web.Tests/ReferralTrackingMiddlewareTests.cs index 6bb7cd32..52a73145 100644 --- a/EssentialCSharp.Web.Tests/ReferralTrackingMiddlewareTests.cs +++ b/EssentialCSharp.Web.Tests/ReferralTrackingMiddlewareTests.cs @@ -8,8 +8,8 @@ namespace EssentialCSharp.Web.Tests; /// -/// Regression tests: anonymous ?rid= requests must not inflate a referrer's count through endpoints that skip rate -/// limiting, and repeat page views by the same visitor count once. +/// 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 { @@ -32,17 +32,17 @@ public async Task RateLimitExemptEndpoints_DoNotCountReferrals(string path) } [Test] - public async Task RepeatPageViewsByTheSameVisitor_CountOnce() + public async Task RepeatPageViewsByTheSameVisitor_EachCount() { (string userId, string referralId) = await CreateReferrerAsync(); using HttpClient client = CreateClientWithoutAutoRedirect(); - for (int i = 0; i < 5; i++) + for (int i = 0; i < 2; i++) { using HttpResponseMessage response = await client.GetAsync($"/hello-world?rid={referralId}"); } - await Assert.That(await GetReferralCountAsync(userId)).IsEqualTo(1); + await Assert.That(await GetReferralCountAsync(userId)).IsEqualTo(2); } [Test] diff --git a/EssentialCSharp.Web/Middleware/ReferralTrackingMiddleware.cs b/EssentialCSharp.Web/Middleware/ReferralTrackingMiddleware.cs index fbb6ae79..dc974f4b 100644 --- a/EssentialCSharp.Web/Middleware/ReferralTrackingMiddleware.cs +++ b/EssentialCSharp.Web/Middleware/ReferralTrackingMiddleware.cs @@ -1,18 +1,13 @@ -using System.Security.Claims; using System.Web; using EssentialCSharp.Web.Areas.Identity.Data; using EssentialCSharp.Web.Services.Referrals; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.RateLimiting; -using Microsoft.Extensions.Caching.Memory; namespace EssentialCSharp.Web.Middleware; public sealed class ReferralMiddleware { - // A visitor counts once per referral link per window, however many pages they load with it. - internal static readonly TimeSpan DedupeWindow = TimeSpan.FromHours(24); - private readonly RequestDelegate _Next; public ReferralMiddleware(RequestDelegate next) @@ -20,7 +15,7 @@ public ReferralMiddleware(RequestDelegate next) _Next = next; } - public async Task InvokeAsync(HttpContext context, IReferralService referralService, UserManager userManager, IMemoryCache memoryCache) + public async Task InvokeAsync(HttpContext context, IReferralService referralService, UserManager userManager) { // Retrieve current referral Id for processing System.Collections.Specialized.NameValueCollection query = HttpUtility.ParseQueryString(context.Request.QueryString.Value ?? string.Empty); @@ -31,44 +26,24 @@ public async Task InvokeAsync(HttpContext context, IReferralService referralServ return; } - if (TryClaimVisit(memoryCache, referralId, GetVisitorKey(context))) + if (context.User is { Identity.IsAuthenticated: true } claimsUser) + { + referralService.TrackReferralAsync(referralId, claimsUser); + } + else { - if (context.User is { Identity.IsAuthenticated: true } claimsUser) - { - referralService.TrackReferralAsync(referralId, claimsUser); - } - else - { - referralService.TrackReferralAsync(referralId, null); - } + referralService.TrackReferralAsync(referralId, null); } await _Next(context); } /// - /// Only page views count. Endpoints that opt out of rate limiting (health checks, /version, /.well-known) - /// would otherwise let anyone add to a referral count as fast as they can send requests. + /// 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; - - private static string GetVisitorKey(HttpContext context) => - context.User.Identity?.IsAuthenticated == true - ? $"user:{context.User.FindFirstValue(ClaimTypes.NameIdentifier)}" - : $"ip:{context.Connection.RemoteIpAddress}"; - - private static bool TryClaimVisit(IMemoryCache memoryCache, string referralId, string visitorKey) - { - // Referral IDs are matched case-insensitively by the database, so dedupe them the same way. - string cacheKey = $"referral-visit:{referralId.ToUpperInvariant()}:{visitorKey}"; - if (memoryCache.TryGetValue(cacheKey, out _)) - { - return false; - } - - memoryCache.Set(cacheKey, true, DedupeWindow); - return true; - } }