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
9 changes: 9 additions & 0 deletions EssentialCSharp.Chat.Shared/Models/AIOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,13 @@ public class AIOptions
/// MCP tools. Should only be set in non-production environments.
/// </summary>
public bool AllowAllMcpTools { get; set; }

/// <summary>
/// Maximum tokens the model may generate for one chat response, including reasoning tokens.
/// Bounds the cost of a single request. Set to 0 to leave the provider's default (no app-side cap).
/// </summary>
public int MaxOutputTokens { get; set; } = DefaultMaxOutputTokens;

/// <summary>Default for <see cref="MaxOutputTokens"/>.</summary>
public const int DefaultMaxOutputTokens = 8192;
}
10 changes: 10 additions & 0 deletions EssentialCSharp.Chat.Shared/Services/AIChatService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -519,6 +519,16 @@ private async Task<CreateResponseOptions> CreateResponseOptionsAsync(
}
}

// Bound what one request can cost: cap the output, and let the provider drop the oldest turns of a long
// conversation (continued through previous_response_id) instead of sending the whole chain every time.
if (_Options.MaxOutputTokens > 0)
{
options.MaxOutputTokenCount = _Options.MaxOutputTokens;
}
#pragma warning disable OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
options.TruncationMode = ResponseTruncationMode.Auto;
#pragma warning restore OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.

// Add reasoning options if specified
if (reasoningEffortLevel.HasValue)
{
Expand Down
84 changes: 84 additions & 0 deletions EssentialCSharp.Chat.Tests/AIChatServiceCostLimitTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
using System.ClientModel;
using System.ClientModel.Primitives;
using System.Net;
using System.Text;
using System.Text.Json;
using EssentialCSharp.Chat;
using EssentialCSharp.Chat.Common.Services;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using OpenAI.Responses;

namespace EssentialCSharp.Chat.Tests;

/// <summary>
/// Regression tests: every chat request sent to the model provider caps its output and lets the provider truncate a
/// long continued conversation, so one permitted request can't run up an unbounded token bill.
/// </summary>
public class AIChatServiceCostLimitTests
{
[Test]
public async Task GetChatCompletion_SendsTheConfiguredOutputCapAndAutoTruncation()
{
CapturingHandler handler = new();
AIChatService service = CreateService(handler, new AIOptions { ChatDeploymentName = "test-deployment", MaxOutputTokens = 1234 });

await service.GetChatCompletion("hello", previousResponseId: "resp_previous");

using JsonDocument body = JsonDocument.Parse(handler.LastRequestBody!);
using (Assert.Multiple())
{
await Assert.That(body.RootElement.GetProperty("max_output_tokens").GetInt32()).IsEqualTo(1234);
await Assert.That(body.RootElement.GetProperty("truncation").GetString()).IsEqualTo("auto");
await Assert.That(body.RootElement.GetProperty("previous_response_id").GetString()).IsEqualTo("resp_previous");
}
}

[Test]
public async Task GetChatCompletion_UsesADefaultOutputCapWhenNoneIsConfigured()
{
CapturingHandler handler = new();
AIChatService service = CreateService(handler, new AIOptions { ChatDeploymentName = "test-deployment" });

await service.GetChatCompletion("hello");

using JsonDocument body = JsonDocument.Parse(handler.LastRequestBody!);
await Assert.That(body.RootElement.GetProperty("max_output_tokens").GetInt32()).IsEqualTo(AIOptions.DefaultMaxOutputTokens);
}

private static AIChatService CreateService(CapturingHandler handler, AIOptions aiOptions)
{
#pragma warning disable OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
ResponsesClientOptions options = new()
{
Endpoint = new Uri("http://localhost/openai/deployments/test-deployment"),
Transport = new HttpClientPipelineTransport(new HttpClient(handler)),
};
ResponsesClient responseClient = new(new ApiKeyCredential("test-key"), options);
#pragma warning restore OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.

return new AIChatService(Options.Create(aiOptions), searchService: null!, responseClient, NullLogger<AIChatService>.Instance);
}

private sealed class CapturingHandler : HttpMessageHandler
{
private const string CompletedResponse =
"""{"id":"resp_new","object":"response","created_at":0,"status":"completed","model":"test-deployment","output":[{"id":"msg_1","type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":"hi","annotations":[]}]}]}""";

public string? LastRequestBody { get; private set; }

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
LastRequestBody = request.Content is null ? null : await request.Content.ReadAsStringAsync(cancellationToken);
return CreateResponse();
}

// The response goes to the HttpClient pipeline, which disposes it.
private static HttpResponseMessage CreateResponse()
{
HttpResponseMessage response = new(HttpStatusCode.OK);
response.Content = new StringContent(CompletedResponse, Encoding.UTF8, "application/json");
return response;
}
}
}
54 changes: 54 additions & 0 deletions EssentialCSharp.Web.Tests/ChatRateLimitTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using System.Net;
using System.Net.Http.Json;
using EssentialCSharp.Web.Services;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;

namespace EssentialCSharp.Web.Tests;

/// <summary>
/// Regression tests: the configured <c>ChatThrottling</c> per-window message cap is enforced per user, in addition to
/// the per-minute burst limit. It used to exist only in configuration.
/// </summary>
public class ChatRateLimitTests : IntegrationTestBase
{
private const string HCaptchaTestToken = "10000000-aaaa-bbbb-cccc-000000000001";

private static async Task<HttpStatusCode> SendChatMessageAsync(HttpClient client, (string Name, string Value) cookie)
{
using HttpRequestMessage request = new(HttpMethod.Post, "/api/chat/message")
{
Content = JsonContent.Create(new { message = "Hello", enableContextualSearch = false, captchaResponse = HCaptchaTestToken })
};
McpTestHelper.AddCookie(request, cookie.Name, cookie.Value);
using HttpResponseMessage response = await client.SendAsync(request);
return response.StatusCode;
}

[Test]
public async Task ChatMessages_BeyondTheConfiguredWindowCap_AreRejectedWith429()
{
WebApplicationFactory<Program> factory = Factory.Inner.WithWebHostBuilder(builder => builder.ConfigureServices(services =>
services.PostConfigure<ChatThrottlingOptions>(options => options.MaxMessagesPerWindow = 3)));
HttpClient client = factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });
string userId = await McpTestHelper.CreateUserAsync(factory.Services, "chat-hourly-cap");
(string Name, string Value) cookie = await McpTestHelper.CreateIdentityApplicationCookieAsync(factory.Services, userId);
string otherUserId = await McpTestHelper.CreateUserAsync(factory.Services, "chat-hourly-cap-other");
(string Name, string Value) otherCookie = await McpTestHelper.CreateIdentityApplicationCookieAsync(factory.Services, otherUserId);

List<HttpStatusCode> statuses = [];
for (int i = 0; i < 4; i++)
{
statuses.Add(await SendChatMessageAsync(client, cookie));
}
HttpStatusCode otherUser = await SendChatMessageAsync(client, otherCookie);

using (Assert.Multiple())
{
// The test chat backend is unavailable, so permitted requests return 503.
await Assert.That(statuses.Take(3)).DoesNotContain(HttpStatusCode.TooManyRequests);
await Assert.That(statuses[3]).IsEqualTo(HttpStatusCode.TooManyRequests);
await Assert.That(otherUser).IsNotEqualTo(HttpStatusCode.TooManyRequests);
}
}
}
85 changes: 85 additions & 0 deletions EssentialCSharp.Web.Tests/ChatStorageIsolationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
using System.Net;
using System.Text.RegularExpressions;

namespace EssentialCSharp.Web.Tests;

/// <summary>
/// Regression tests: AI chat history kept in browser storage must not carry over to the next account that signs in
/// on the same browser. Logout clears site storage, and each page tells the chat widget whose state it may reuse.
/// </summary>
public partial class ChatStorageIsolationTests : IntegrationTestBase
{
[GeneratedRegex("window\\.CHAT_STORAGE_OWNER = (null|\"[0-9A-F]{32}\");")]
private static partial Regex StorageOwnerScript();

private static async Task<string> GetStorageOwnerAsync(HttpClient client, (string Name, string Value)? cookie)
{
using HttpRequestMessage request = new(HttpMethod.Get, "/home");
if (cookie is { } c)
{
McpTestHelper.AddCookie(request, c.Name, c.Value);
}
using HttpResponseMessage response = await client.SendAsync(request);
Match match = StorageOwnerScript().Match(await response.Content.ReadAsStringAsync());
if (!match.Success)
{
throw new InvalidOperationException($"CHAT_STORAGE_OWNER not found on /home ({(int)response.StatusCode}).");
}
return match.Groups[1].Value;
}

[Test]
public async Task Logout_ClearsSiteStorage()
{
string userId = await McpTestHelper.CreateUserAsync(Factory, "chat-logout");
(string Name, string Value) cookie = await McpTestHelper.CreateIdentityApplicationCookieAsync(Factory, userId);
using HttpClient client = CreateClientWithoutAutoRedirect();

using HttpRequestMessage page = new(HttpMethod.Get, "/Identity/Account/Logout");
McpTestHelper.AddCookie(page, cookie.Name, cookie.Value);
using HttpResponseMessage pageResponse = await client.SendAsync(page);
string html = await pageResponse.Content.ReadAsStringAsync();
string token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value;
string antiforgeryCookie = pageResponse.Headers.GetValues("Set-Cookie")
.Select(v => v.Split(';')[0])
.First(v => v.StartsWith(".AspNetCore.Antiforgery.", StringComparison.Ordinal));

using HttpRequestMessage logout = new(HttpMethod.Post, "/Identity/Account/Logout")
{
Content = new FormUrlEncodedContent(new Dictionary<string, string> { ["__RequestVerificationToken"] = token })
};
logout.Headers.Add("Cookie", $"{cookie.Name}={cookie.Value}; {antiforgeryCookie}");
using HttpResponseMessage response = await client.SendAsync(logout);

using (Assert.Multiple())
{
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Redirect);
await Assert.That(response.Headers.TryGetValues("Clear-Site-Data", out IEnumerable<string>? values)).IsTrue();
await Assert.That(string.Join(",", values ?? [])).IsEqualTo("\"storage\"");
}
}

[Test]
public async Task Pages_ExposeAStorageOwnerThatDiffersPerUserAndIsNullWhenSignedOut()
{
string userA = await McpTestHelper.CreateUserAsync(Factory, "chat-owner-a");
string userB = await McpTestHelper.CreateUserAsync(Factory, "chat-owner-b");
(string Name, string Value) cookieA = await McpTestHelper.CreateIdentityApplicationCookieAsync(Factory, userA);
(string Name, string Value) cookieB = await McpTestHelper.CreateIdentityApplicationCookieAsync(Factory, userB);
using HttpClient client = CreateClientWithoutAutoRedirect();

string ownerA = await GetStorageOwnerAsync(client, cookieA);
string ownerAAgain = await GetStorageOwnerAsync(client, cookieA);
string ownerB = await GetStorageOwnerAsync(client, cookieB);
string anonymous = await GetStorageOwnerAsync(client, null);

using (Assert.Multiple())
{
await Assert.That(ownerA).IsNotEqualTo("null");
await Assert.That(ownerA).IsEqualTo(ownerAAgain);
await Assert.That(ownerB).IsNotEqualTo(ownerA);
await Assert.That(anonymous).IsEqualTo("null");
await Assert.That(ownerA).DoesNotContain(userA);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,16 @@ public async Task<IActionResult> OnPost(string? returnUrl = null)
{
await signInManager.SignOutAsync();
LogUserLoggedOut(logger);
// Remove what the signed-in user left in browser storage (the AI chat history and its conversation ID),
// so the next person to sign in on this browser doesn't see or continue it. Browsers honor this on HTTPS.
Response.Headers["Clear-Site-Data"] = ClearSiteDataStorage;
// This needs to be a redirect so that the browser performs a new
// request and the identity for the user gets updated.
return returnUrl is not null ? LocalRedirect(returnUrl) : RedirectToPage();
}

internal const string ClearSiteDataStorage = "\"storage\"";

[LoggerMessage(Level = LogLevel.Information, Message = "User logged out.")]
private static partial void LogUserLoggedOut(ILogger<LogoutModel> logger);
}
19 changes: 19 additions & 0 deletions EssentialCSharp.Web/Extensions/ClaimsExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;

namespace EssentialCSharp.Web.Extensions;

Expand All @@ -24,5 +26,22 @@ public static class ClaimsExtensions
return httpContext?.User?.GetReferrerId();
}

/// <summary>
/// A non-secret marker of the signed-in user that the browser stores next to the AI chat history, so a page
/// loaded by a different account (or after sign-out) can tell the stored conversation isn't its own.
/// </summary>
/// <returns>A hash of the user ID, or <see langword="null"/> when nobody is signed in.</returns>
public static string? GetChatStorageOwner(this ClaimsPrincipal claimsPrincipal)
{
if (claimsPrincipal.Identity?.IsAuthenticated != true
|| claimsPrincipal.FindFirstValue(ClaimTypes.NameIdentifier) is not { Length: > 0 } userId)
{
return null;
}

byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes($"EssentialCSharp.ChatStorageOwner:{userId}"));
return Convert.ToHexString(hash, 0, 16);
}

public const string ReferrerIdClaimType = "ReferrerId";
}
24 changes: 7 additions & 17 deletions EssentialCSharp.Web/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,10 @@ private static void Main(string[] args)
builder.Services.AddMailjetEmailSender(builder.Configuration.GetSection(AuthMessageSenderOptions.AuthMessageSender), builder.Environment);
builder.Services.Configure<SiteSettings>(builder.Configuration.GetSection(SiteSettings.SectionName));
builder.Services.Configure<ContentRateLimitOptions>(builder.Configuration.GetSection(ContentRateLimitOptions.SectionName));
builder.Services.AddOptions<ChatThrottlingOptions>()
.Bind(builder.Configuration.GetSection(ChatThrottlingOptions.SectionName))
.ValidateDataAnnotations()
.ValidateOnStart();

// Add services to the container.
builder.Services.AddRazorPages();
Expand Down Expand Up @@ -253,23 +257,9 @@ private static void Main(string[] args)
});
});

options.AddPolicy("ChatEndpoint", httpContext =>
{
// Partitioned per-user (when authenticated) or per-IP (anonymous)
var partitionKey = httpContext.User.Identity?.IsAuthenticated == true
? $"chat-user:{httpContext.User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "unknown-user"}"
: $"chat-ip:{httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown-ip"}";

return RateLimitPartition.GetFixedWindowLimiter(
partitionKey: partitionKey,
factory: _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 15,
Window = TimeSpan.FromMinutes(1),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0
});
});
// 15 per minute plus the configured ChatThrottling per-window cap, per user (or IP when anonymous).
// See Services/ChatRateLimiterPolicy.cs.
options.AddPolicy<string, ChatRateLimiterPolicy>(ChatRateLimiterPolicy.PolicyName);

// Combined per-minute burst (10/min) + per-hour cap (150/hr) for book content pages.
// A scraper cycling through the full ~400-page book needs 2+ hours at minimum.
Expand Down
Loading
Loading