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
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
<PackageVersion Include="Azure.Identity" Version="1.21.0" />
<PackageVersion Include="Azure.Monitor.OpenTelemetry.AspNetCore" Version="1.5.0" />
<PackageVersion Include="TUnit" Version="1.40.5" />
<PackageVersion Include="TUnit.AspNetCore" Version="1.40.5" />
<PackageVersion Include="EssentialCSharp.Shared.Models" Version="$(ToolingPackagesVersion)" />
<PackageVersion Include="HtmlAgilityPack" Version="1.12.4" />
<PackageVersion Include="IntelliTect.Multitool" Version="2.1.0" />
Expand Down
12 changes: 3 additions & 9 deletions EssentialCSharp.Web.Tests/ContentRateLimitingTests.cs
Original file line number Diff line number Diff line change
@@ -1,24 +1,18 @@
using System.Net;
using Microsoft.AspNetCore.Mvc.Testing;

namespace EssentialCSharp.Web.Tests;

/// <summary>
/// HTTP integration tests for the "content" rate limit policy.
/// Uses its own factory (PerClass) to get a fresh in-memory rate limiter for each run.
/// Each test gets its own factory (fresh IHost) so the rate limiter starts from a clean state.
/// Anonymous users are limited to 10 requests per minute on chapter content pages.
/// </summary>
[ClassDataSource<WebApplicationFactory>(Shared = SharedType.PerClass)]
public class ContentRateLimitingTests(WebApplicationFactory factory)
public class ContentRateLimitingTests : IntegrationTestBase
{
[Test]
public async Task ContentEndpoint_ExceedingPerMinuteLimit_Returns429()
{
// AllowAutoRedirect = false prevents redirect-following from consuming extra permits.
HttpClient client = factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
HttpClient client = Factory.CreateClient();

// Anonymous limit is 10/min. First 10 requests should not be rate-limited.
for (int i = 0; i < 10; i++)
Expand Down
1 change: 1 addition & 0 deletions EssentialCSharp.Web.Tests/EssentialCSharp.Web.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<PackageReference Include="Moq" />
<PackageReference Include="Moq.AutoMock" />
<PackageReference Include="TUnit" />
<PackageReference Include="TUnit.AspNetCore" />
<PackageReference Include="Newtonsoft.Json" />
</ItemGroup>

Expand Down
12 changes: 5 additions & 7 deletions EssentialCSharp.Web.Tests/FunctionalTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@

namespace EssentialCSharp.Web.Tests;

[NotInParallel("FunctionalTests")]
[ClassDataSource<WebApplicationFactory>(Shared = SharedType.PerClass)]
public class FunctionalTests(WebApplicationFactory factory)
public class FunctionalTests : IntegrationTestBase
{
[Test]
[Arguments("/")]
Expand All @@ -15,7 +13,7 @@ public class FunctionalTests(WebApplicationFactory factory)
[Arguments("/alive")]
public async Task WhenTheApplicationStarts_ItCanLoadLoadPages(string relativeUrl)
{
HttpClient client = factory.CreateClient();
HttpClient client = CreateRedirectFollowingClient();
using HttpResponseMessage response = await client.GetAsync(relativeUrl);

await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
Expand All @@ -31,7 +29,7 @@ public async Task WhenTheApplicationStarts_ItCanLoadLoadPages(string relativeUrl
[Arguments("/about?someOtherParam=value")]
public async Task WhenPagesAreAccessed_TheyReturnHtml(string relativeUrl)
{
HttpClient client = factory.CreateClient();
HttpClient client = CreateRedirectFollowingClient();
using HttpResponseMessage response = await client.GetAsync(relativeUrl);

await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
Expand All @@ -47,9 +45,9 @@ public async Task WhenPagesAreAccessed_TheyReturnHtml(string relativeUrl)
[Test]
public async Task WhenTheApplicationStarts_NonExistingPage_GivesCorrectStatusCode()
{
HttpClient client = factory.CreateClient();
HttpClient client = CreateRedirectFollowingClient();
using HttpResponseMessage response = await client.GetAsync("/non-existing-page1234");

await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
}
}
}
42 changes: 42 additions & 0 deletions EssentialCSharp.Web.Tests/IntegrationTestBase.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using TUnit.AspNetCore;

namespace EssentialCSharp.Web.Tests;

public abstract class IntegrationTestBase : WebApplicationTest<WebApplicationFactory, Program>
{
/// <summary>
/// Creates an HTTP client with redirect following enabled.
/// NOTE: This bypasses TUnit trace correlation because <see cref="TracedWebApplicationFactory{T}"/>
/// does not expose a <c>CreateClient(WebApplicationFactoryClientOptions)</c> overload.
/// Use <see cref="TUnit.AspNetCore.TracedWebApplicationFactory{T}.CreateClient()"/> for all
/// other tests where AllowAutoRedirect=false is acceptable.
/// </summary>
protected HttpClient CreateRedirectFollowingClient() =>
Factory.Inner.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = true });

public T InServiceScope<T>(Func<IServiceProvider, T> action)
{
using IServiceScope scope = Factory.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
return action(scope.ServiceProvider);
}

public void InServiceScope(Action<IServiceProvider> action)
{
using IServiceScope scope = Factory.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
action(scope.ServiceProvider);
}

public async Task<T> InServiceScopeAsync<T>(Func<IServiceProvider, Task<T>> action)
{
using IServiceScope scope = Factory.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
return await action(scope.ServiceProvider);
}

public async Task InServiceScopeAsync(Func<IServiceProvider, Task> action)
{
using IServiceScope scope = Factory.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
await action(scope.ServiceProvider);
}
}
13 changes: 6 additions & 7 deletions EssentialCSharp.Web.Tests/ListingSourceCodeControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,13 @@

namespace EssentialCSharp.Web.Tests;

[ClassDataSource<WebApplicationFactory>(Shared = SharedType.PerClass)]
public class ListingSourceCodeControllerTests(WebApplicationFactory factory)
public class ListingSourceCodeControllerTests : IntegrationTestBase
{
[Test]
public async Task GetListing_WithValidChapterAndListing_Returns200WithContent()
{
// Arrange
HttpClient client = factory.CreateClient();
HttpClient client = Factory.CreateClient();

// Act
using HttpResponseMessage response = await client.GetAsync("/api/ListingSourceCode/chapter/1/listing/1");
Expand All @@ -35,7 +34,7 @@ public async Task GetListing_WithValidChapterAndListing_Returns200WithContent()
public async Task GetListing_WithInvalidChapter_Returns404()
{
// Arrange
HttpClient client = factory.CreateClient();
HttpClient client = Factory.CreateClient();

// Act
using HttpResponseMessage response = await client.GetAsync("/api/ListingSourceCode/chapter/999/listing/1");
Expand All @@ -48,7 +47,7 @@ public async Task GetListing_WithInvalidChapter_Returns404()
public async Task GetListing_WithInvalidListing_Returns404()
{
// Arrange
HttpClient client = factory.CreateClient();
HttpClient client = Factory.CreateClient();

// Act
using HttpResponseMessage response = await client.GetAsync("/api/ListingSourceCode/chapter/1/listing/999");
Expand All @@ -61,7 +60,7 @@ public async Task GetListing_WithInvalidListing_Returns404()
public async Task GetListingsByChapter_WithValidChapter_ReturnsMultipleListings()
{
// Arrange
HttpClient client = factory.CreateClient();
HttpClient client = Factory.CreateClient();

// Act
using HttpResponseMessage response = await client.GetAsync("/api/ListingSourceCode/chapter/1");
Expand Down Expand Up @@ -92,7 +91,7 @@ public async Task GetListingsByChapter_WithValidChapter_ReturnsMultipleListings(
public async Task GetListingsByChapter_WithInvalidChapter_ReturnsEmptyList()
{
// Arrange
HttpClient client = factory.CreateClient();
HttpClient client = Factory.CreateClient();

// Act
using HttpResponseMessage response = await client.GetAsync("/api/ListingSourceCode/chapter/999");
Expand Down
11 changes: 4 additions & 7 deletions EssentialCSharp.Web.Tests/McpApiTokenServiceTests.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
using EssentialCSharp.Web.Models;
using EssentialCSharp.Web.Services;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;

namespace EssentialCSharp.Web.Tests;

[NotInParallel("McpTests")]
[ClassDataSource<WebApplicationFactory>(Shared = SharedType.PerClass)]
public class McpApiTokenServiceTests(WebApplicationFactory factory)
public class McpApiTokenServiceTests : IntegrationTestBase
{
private readonly List<IServiceScope> _scopes = [];

Expand All @@ -21,16 +18,16 @@ public void DisposeScopes()

private async Task<(string UserId, McpApiTokenService TokenService)> ArrangeAsync(string prefix)
{
string userId = await McpTestHelper.CreateUserAsync(factory, prefix);
var scope = factory.Services.CreateScope();
string userId = await McpTestHelper.CreateUserAsync(Factory, prefix);
var scope = Factory.Services.CreateScope();
_scopes.Add(scope);
var tokenService = scope.ServiceProvider.GetRequiredService<McpApiTokenService>();
return (userId, tokenService);
}

private async Task<McpApiTokenService> FillToLimitAsync(string userId)
{
var scope = factory.Services.CreateScope();
var scope = Factory.Services.CreateScope();
_scopes.Add(scope);
var tokenService = scope.ServiceProvider.GetRequiredService<McpApiTokenService>();
for (int i = 0; i < McpApiTokenService.MaxTokensPerUser; i++)
Expand Down
62 changes: 18 additions & 44 deletions EssentialCSharp.Web.Tests/McpRateLimitingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,25 @@
using System.Text.Json;
using EssentialCSharp.Web.Data;
using EssentialCSharp.Web.Services;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;

namespace EssentialCSharp.Web.Tests;

/// <summary>
/// Each class gets its own factory so the global limiter starts from a fresh state.
/// Each test method gets its own per-test factory (fresh IHost + rate limiter state)
/// via TUnit.AspNetCore's WebApplicationTest, so [NotInParallel] is no longer needed.
/// </summary>
[NotInParallel("McpTests")]
[ClassDataSource<WebApplicationFactory>(Shared = SharedType.PerClass)]
public class McpDistinctUserRateLimitingTests(WebApplicationFactory factory)
public class McpRateLimitingTests : IntegrationTestBase
{
[Test]
public async Task DistinctValidMcpUsers_DoNotShareRateLimitBucket()
{
HttpClient client = McpTestHelper.CreateClient(factory);
HttpClient client = McpTestHelper.CreateClient(Factory);

for (int i = 0; i < 31; i++)
{
(_, string rawToken) = await McpTestHelper.CreateUserAndTokenAsync(
factory,
Factory,
$"mcp-rate-limit-isolation-{i}",
userPrefix: $"mcp-isolation-{i}");

Expand All @@ -35,20 +33,15 @@ await Assert.That(response.StatusCode)
.Because($"distinct MCP user request {i + 1} should use its own rate-limit bucket");
}
}
}

[NotInParallel("McpTests")]
[ClassDataSource<WebApplicationFactory>(Shared = SharedType.PerClass)]
public class McpPerUserRateLimitingTests(WebApplicationFactory factory)
{
[Test]
public async Task SingleValidMcpUser_ExceedingTokenBucket_Returns429AndDoesNotCountRejectedRequests()
{
(_, string rawToken) = await McpTestHelper.CreateUserAndTokenAsync(
factory,
Factory,
"mcp-rate-limit-single-user",
userPrefix: "mcp-single-user");
HttpClient client = McpTestHelper.CreateClient(factory);
HttpClient client = McpTestHelper.CreateClient(Factory);
List<HttpStatusCode> statuses = [];
string? rateLimitedPayload = null;
string? rateLimitedContentType = null;
Expand All @@ -70,7 +63,7 @@ public async Task SingleValidMcpUser_ExceedingTokenBucket_Returns429AndDoesNotCo
}
}

(long UsageCount, bool HasLastUsedAt) tokenUsage = factory.InServiceScope(services =>
(long UsageCount, bool HasLastUsedAt) tokenUsage = InServiceScope(services =>
{
var db = services.GetRequiredService<EssentialCSharpWebContext>();
byte[] tokenHash = McpApiTokenService.HashToken(rawToken);
Expand Down Expand Up @@ -104,16 +97,11 @@ await Assert.That(statuses.Skip(McpRateLimiterPolicy.AuthenticatedTokenLimit)
await Assert.That(error.GetProperty("code").GetInt32()).IsEqualTo(-32000);
await Assert.That(error.GetProperty("message").GetString()).Contains("Rate limit exceeded");
}
}

[NotInParallel("McpTests")]
[ClassDataSource<WebApplicationFactory>(Shared = SharedType.PerClass)]
public class McpAnonymousRateLimitingTests(WebApplicationFactory factory)
{
[Test]
public async Task InvalidMcpBearerRequests_FallBackToAnonymousIpBucket()
{
HttpClient client = McpTestHelper.CreateClient(factory);
HttpClient client = McpTestHelper.CreateClient(Factory);

for (int i = 0; i < McpRateLimiterPolicy.AnonymousPermitLimit; i++)
{
Expand All @@ -132,21 +120,16 @@ await Assert.That(response.StatusCode)
using HttpResponseMessage rateLimitedResponse = await client.SendAsync(rateLimitedRequest);
await Assert.That(rateLimitedResponse.StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests);
}
}

[NotInParallel("McpTests")]
[ClassDataSource<WebApplicationFactory>(Shared = SharedType.PerClass)]
public class McpCookieIsolationRateLimitingTests(WebApplicationFactory factory)
{
[Test]
public async Task InvalidMcpBearerRequests_WithDifferentSiteCookies_StillShareAnonymousIpBucket()
{
HttpClient client = McpTestHelper.CreateClient(factory);
HttpClient client = McpTestHelper.CreateClient(Factory);

for (int i = 0; i < McpRateLimiterPolicy.AnonymousPermitLimit; i++)
{
string cookieUserId = await McpTestHelper.CreateUserAsync(factory, $"mcp-cookie-user-{i}");
(string cookieName, string cookieValue) = await McpTestHelper.CreateIdentityApplicationCookieAsync(factory, cookieUserId);
string cookieUserId = await McpTestHelper.CreateUserAsync(Factory, $"mcp-cookie-user-{i}");
(string cookieName, string cookieValue) = await McpTestHelper.CreateIdentityApplicationCookieAsync(Factory, cookieUserId);

using var request = McpTestHelper.CreateInitializeRequest("/mcp");
McpTestHelper.AddBearerToken(request, "mcp_invalid_token_that_does_not_exist");
Expand All @@ -158,8 +141,8 @@ await Assert.That(response.StatusCode)
.Because($"invalid MCP bearer request {i + 1} should ignore the site cookie principal and stay in the anonymous/IP bucket");
}

string finalCookieUserId = await McpTestHelper.CreateUserAsync(factory, "mcp-cookie-user-final");
(string finalCookieName, string finalCookieValue) = await McpTestHelper.CreateIdentityApplicationCookieAsync(factory, finalCookieUserId);
string finalCookieUserId = await McpTestHelper.CreateUserAsync(Factory, "mcp-cookie-user-final");
(string finalCookieName, string finalCookieValue) = await McpTestHelper.CreateIdentityApplicationCookieAsync(Factory, finalCookieUserId);

using var rateLimitedRequest = McpTestHelper.CreateInitializeRequest("/mcp");
McpTestHelper.AddBearerToken(rateLimitedRequest, "mcp_invalid_token_that_does_not_exist");
Expand All @@ -168,20 +151,15 @@ await Assert.That(response.StatusCode)
using HttpResponseMessage rateLimitedResponse = await client.SendAsync(rateLimitedRequest);
await Assert.That(rateLimitedResponse.StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests);
}
}

[NotInParallel("McpTests")]
[ClassDataSource<WebApplicationFactory>(Shared = SharedType.PerClass)]
public class McpGlobalBypassRateLimitingTests(WebApplicationFactory factory)
{
[Test]
public async Task ValidMcpPostRequests_DoNotConsumeGlobalLimiterBudgetForGetShim()
{
(_, string rawToken) = await McpTestHelper.CreateUserAndTokenAsync(
factory,
Factory,
"mcp-global-bypass",
userPrefix: "mcp-bypass");
HttpClient client = McpTestHelper.CreateClient(factory);
HttpClient client = McpTestHelper.CreateClient(Factory);

for (int i = 0; i < 10; i++)
{
Expand Down Expand Up @@ -211,16 +189,11 @@ await Assert.That(getResponse.StatusCode)
using HttpResponseMessage rateLimitedGetResponse = await client.SendAsync(rateLimitedGetRequest);
await Assert.That(rateLimitedGetResponse.StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests);
}
}

[NotInParallel("McpTests")]
[ClassDataSource<WebApplicationFactory>(Shared = SharedType.PerClass)]
public class McpWellKnownIsolationRateLimitingTests(WebApplicationFactory factory)
{
[Test]
public async Task WellKnownRequests_DoNotConsumeContentLimiterBudget()
{
HttpClient client = McpTestHelper.CreateClient(factory);
HttpClient client = McpTestHelper.CreateClient(Factory);

for (int i = 0; i < 10; i++)
{
Expand All @@ -243,3 +216,4 @@ await Assert.That(contentResponse.StatusCode)
await Assert.That(rateLimitedResponse.StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests);
}
}

Loading
Loading