using System.IdentityModel.Tokens.Jwt; using System.Net; using System.Net.Http.Headers; using System.Security.Claims; using System.Text; using System.Text.Json; using ClassNotify.Server.Configuration; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; namespace ClassNotify.RateLimitTests; public class CustomWebApplicationFactory : WebApplicationFactory { public const string TestJwtKey = "THIS_IS_A_VERY_LONG_TEST_SIGNING_KEY_EXCEEDING_SIXTY_FOUR_BYTES_IN_LENGTH_FOR_TESTS!"; public const string TestIssuer = "ClassNotify.Server"; public const string TestAudience = "ClassNotify.Clients"; private readonly string _testDbName = "classnotify_test_" + Guid.NewGuid().ToString("N"); protected override void ConfigureWebHost(IWebHostBuilder builder) { var dir = new DirectoryInfo(AppContext.BaseDirectory); while (dir != null && !File.Exists(Path.Combine(dir.FullName, "ClassNotify.sln"))) { dir = dir.Parent; } var rootDir = dir?.FullName ?? Directory.GetCurrentDirectory(); var serverPath = Path.Combine(rootDir, "src", "Server", "ClassNotify.Server"); builder.UseContentRoot(serverPath); builder.UseEnvironment("Development"); builder.ConfigureAppConfiguration((context, config) => { config.AddInMemoryCollection(new Dictionary { ["RateLimit:AuthPermitLimit"] = "3", ["RateLimit:ActivationPermitLimit"] = "3", ["RateLimit:SendPermitLimit"] = "3", ["Jwt:SigningKey"] = TestJwtKey, ["Jwt:Issuer"] = TestIssuer, ["Jwt:Audience"] = TestAudience, ["Jwt:LifetimeDays"] = "14", ["ConnectionStrings:DefaultConnection"] = "Host=127.0.0.1;Database=classnotify_test;Username=postgres;" }); }); builder.ConfigureServices(services => { services.Configure(options => { options.ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedFor | Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedProto; options.KnownNetworks.Clear(); options.KnownProxies.Clear(); }); services.PostConfigure(options => { options.AuthPermitLimit = 3; options.ActivationPermitLimit = 3; options.SendPermitLimit = 3; }); // Remove PostgreSQL and replace with isolated InMemory Database for testing var dbDescriptors = services.Where(d => d.ServiceType == typeof(DbContextOptions) || d.ServiceType == typeof(ClassNotifyDbContext)).ToList(); foreach (var d in dbDescriptors) { services.Remove(d); } services.AddDbContext(options => { options.UseInMemoryDatabase(_testDbName); }); }); } public static string CreateTeacherJwt(IServiceProvider services, string userId, string userName, string tenantId) { var jwtOptions = services.GetRequiredService>().Value; var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.UTF8.GetBytes(jwtOptions.SigningKey); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, userId), new Claim(ClaimTypes.Name, userName), new Claim(ClaimTypes.Role, "Teacher"), new Claim("tenant_id", tenantId), new Claim("token_version", "1") }), Issuer = jwtOptions.Issuer, Audience = jwtOptions.Audience, Expires = DateTime.UtcNow.AddHours(2), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } } public class RateLimitTestRunner { private static int _passedTests = 0; private static int _failedTests = 0; public static async Task Main(string[] args) { Environment.SetEnvironmentVariable("RateLimit__AuthPermitLimit", "3"); Environment.SetEnvironmentVariable("RateLimit__ActivationPermitLimit", "3"); Environment.SetEnvironmentVariable("RateLimit__SendPermitLimit", "3"); Console.WriteLine("=========================================================="); Console.WriteLine(" ClassNotify Rate Limiter Partition Integration Tests "); Console.WriteLine("=========================================================="); using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); // Seed necessary in-memory entities for SendNotification testing using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); await db.Database.EnsureCreatedAsync(); if (!await db.Tenants.AnyAsync(t => t.Id == "t_beijing_no4")) { db.Tenants.Add(new Tenant { Id = "t_beijing_no4", Name = "北京四中" }); } if (!await db.Tenants.AnyAsync(t => t.Id == "t_shanghai_high")) { db.Tenants.Add(new Tenant { Id = "t_shanghai_high", Name = "上海中学" }); } if (!await db.Classrooms.AnyAsync(c => c.Id == "cls_801")) { db.Classrooms.Add(new Classroom { Id = "cls_801", TenantId = "t_beijing_no4", DisplayName = "八年级(1)班", Grade = "8", RoomNumber = "801" }); } if (!await db.Classrooms.AnyAsync(c => c.Id == "cls_901")) { db.Classrooms.Add(new Classroom { Id = "cls_901", TenantId = "t_shanghai_high", DisplayName = "九年级(1)班", Grade = "9", RoomNumber = "901" }); } if (!await db.Users.AnyAsync(u => u.Id == "usr_101")) { db.Users.Add(new User { Id = "usr_101", Username = "teacher_zhang", PasswordHash = "hash", FullName = "张老师", Role = "Teacher", TenantId = "t_beijing_no4", IsLocked = false, TokenVersion = 1, CreatedAt = DateTimeOffset.UtcNow }); } if (!await db.Users.AnyAsync(u => u.Id == "usr_201")) { db.Users.Add(new User { Id = "usr_201", Username = "teacher_li", PasswordHash = "hash", FullName = "李老师", Role = "Teacher", TenantId = "t_shanghai_high", IsLocked = false, TokenVersion = 1, CreatedAt = DateTimeOffset.UtcNow }); } await db.SaveChangesAsync(); } Console.WriteLine("\n[1/3] Running Test A: AuthLimiter Partitioned by IP..."); var (authIpAFinal, authIpBFirst) = await Test_AuthLimiter_IpPartition(client); Console.WriteLine("\n[2/3] Running Test B: ActivationLimiter Partitioned by IP..."); var (actIpAFinal, actIpBFirst) = await Test_ActivationLimiter_IpPartition(client); Console.WriteLine("\n[3/3] Running Test C: SendLimiter Partitioned by UserId..."); var (teacherAFinal, teacherBFirst) = await Test_SendLimiter_UserPartition(factory, client); Console.WriteLine("\n=========================================================="); Console.WriteLine("=== Rate Limit Partition Summary ==="); Console.WriteLine("Auth:"); Console.WriteLine($"IP A final = {authIpAFinal}"); Console.WriteLine($"IP B first = {authIpBFirst} (not 429)"); Console.WriteLine(); Console.WriteLine("Activation:"); Console.WriteLine($"IP A final = {actIpAFinal}"); Console.WriteLine($"IP B first = {actIpBFirst} (not 429)"); Console.WriteLine(); Console.WriteLine("Send:"); Console.WriteLine($"Teacher A final = {teacherAFinal}"); Console.WriteLine($"Teacher B first = {teacherBFirst} (not 429)"); Console.WriteLine(); var partitionIsolationPass = (authIpAFinal == 429 && authIpBFirst != 429) && (actIpAFinal == 429 && actIpBFirst != 429) && (teacherAFinal == 429 && teacherBFirst != 429); Console.WriteLine($"Partition isolation: {(partitionIsolationPass ? "PASS" : "FAIL")}"); Console.WriteLine("=========================================================="); Console.WriteLine($"Results: {_passedTests} Passed, {_failedTests} Failed"); return (_failedTests == 0 && partitionIsolationPass) ? 0 : 1; } private static async Task<(int ipAFinal, int ipBFirst)> Test_AuthLimiter_IpPartition(HttpClient client) { var ipA = "10.0.0.1"; var ipB = "10.0.0.2"; int ipAFinal = 0; int ipBFirst = 0; // Send 4 requests from IP A (Limit = 3) for (int i = 1; i <= 4; i++) { var req = new HttpRequestMessage(HttpMethod.Post, "/api/auth/login"); req.Headers.Add("X-Forwarded-For", ipA); req.Content = new StringContent(JsonSerializer.Serialize(new { username = "test_user", password = "wrong_password" }), Encoding.UTF8, "application/json"); var resp = await client.SendAsync(req); var code = (int)resp.StatusCode; Console.WriteLine($" IP A ({ipA}) Request {i} -> HTTP {code}"); if (i == 4) { ipAFinal = code; } } // Send 1st request from IP B { var req = new HttpRequestMessage(HttpMethod.Post, "/api/auth/login"); req.Headers.Add("X-Forwarded-For", ipB); req.Content = new StringContent(JsonSerializer.Serialize(new { username = "test_user", password = "wrong_password" }), Encoding.UTF8, "application/json"); var resp = await client.SendAsync(req); ipBFirst = (int)resp.StatusCode; Console.WriteLine($" IP B ({ipB}) Request 1 -> HTTP {ipBFirst}"); } Assert(ipAFinal == 429, $"IP A final request must be 429 Too Many Requests (Actual: {ipAFinal})"); Assert(ipBFirst != 429, $"IP B first request must NOT be 429 (Actual: {ipBFirst})"); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("[PASS] AuthLimiter correctly isolated per IP partition."); Console.ResetColor(); _passedTests++; return (ipAFinal, ipBFirst); } private static async Task<(int ipAFinal, int ipBFirst)> Test_ActivationLimiter_IpPartition(HttpClient client) { var ipA = "10.0.0.1"; var ipB = "10.0.0.2"; int ipAFinal = 0; int ipBFirst = 0; // Send 4 requests from IP A (Limit = 3) for (int i = 1; i <= 4; i++) { var req = new HttpRequestMessage(HttpMethod.Post, "/api/device/activate"); req.Headers.Add("X-Forwarded-For", ipA); req.Content = new StringContent(JsonSerializer.Serialize(new { code = "TEST-CODE", installationId = "inst_1" }), Encoding.UTF8, "application/json"); var resp = await client.SendAsync(req); var code = (int)resp.StatusCode; Console.WriteLine($" IP A ({ipA}) Request {i} -> HTTP {code}"); if (i == 4) { ipAFinal = code; } } // Send 1st request from IP B { var req = new HttpRequestMessage(HttpMethod.Post, "/api/device/activate"); req.Headers.Add("X-Forwarded-For", ipB); req.Content = new StringContent(JsonSerializer.Serialize(new { code = "TEST-CODE", installationId = "inst_1" }), Encoding.UTF8, "application/json"); var resp = await client.SendAsync(req); ipBFirst = (int)resp.StatusCode; Console.WriteLine($" IP B ({ipB}) Request 1 -> HTTP {ipBFirst}"); } Assert(ipAFinal == 429, $"IP A final request must be 429 Too Many Requests (Actual: {ipAFinal})"); Assert(ipBFirst != 429, $"IP B first request must NOT be 429 (Actual: {ipBFirst})"); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("[PASS] ActivationLimiter correctly isolated per IP partition."); Console.ResetColor(); _passedTests++; return (ipAFinal, ipBFirst); } private static async Task<(int teacherAFinal, int teacherBFirst)> Test_SendLimiter_UserPartition(CustomWebApplicationFactory factory, HttpClient client) { var tokenTeacherA = CustomWebApplicationFactory.CreateTeacherJwt(factory.Services, "usr_101", "teacher_zhang", "t_beijing_no4"); var tokenTeacherB = CustomWebApplicationFactory.CreateTeacherJwt(factory.Services, "usr_201", "teacher_li", "t_shanghai_high"); int teacherAFinal = 0; int teacherBFirst = 0; var notifA = new NotificationDto { ClassId = "cls_801", StudentName = "张三", Title = "请来办公室", Message = "张三请到办公室一趟", Voice = true, Shake = true, DurationSeconds = 15 }; var notifB = new NotificationDto { ClassId = "cls_901", StudentName = "李四", Title = "请来办公室", Message = "李四请到办公室一趟", Voice = true, Shake = true, DurationSeconds = 15 }; // Teacher A sends 4 notifications (Limit = 3) for (int i = 1; i <= 4; i++) { var req = new HttpRequestMessage(HttpMethod.Post, "/api/notification/send"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokenTeacherA); req.Content = new StringContent(JsonSerializer.Serialize(notifA), Encoding.UTF8, "application/json"); var resp = await client.SendAsync(req); var code = (int)resp.StatusCode; Console.WriteLine($" Teacher A Request {i} -> HTTP {code}"); if (i == 4) { teacherAFinal = code; } } // Teacher B sends 1st notification { var req = new HttpRequestMessage(HttpMethod.Post, "/api/notification/send"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokenTeacherB); req.Content = new StringContent(JsonSerializer.Serialize(notifB), Encoding.UTF8, "application/json"); var resp = await client.SendAsync(req); teacherBFirst = (int)resp.StatusCode; Console.WriteLine($" Teacher B Request 1 -> HTTP {teacherBFirst}"); } Assert(teacherAFinal == 429, $"Teacher A final request must be 429 Too Many Requests (Actual: {teacherAFinal})"); Assert(teacherBFirst != 429, $"Teacher B first request must NOT be 429 (Actual: {teacherBFirst})"); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("[PASS] SendLimiter correctly isolated per User partition."); Console.ResetColor(); _passedTests++; return (teacherAFinal, teacherBFirst); } private static void Assert(bool condition, string message) { if (!condition) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"[FAIL] Assertion Failed: {message}"); Console.ResetColor(); _failedTests++; throw new InvalidOperationException(message); } } }