diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointRateLimitingTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointRateLimitingTests.cs deleted file mode 100644 index 9191a0c1..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointRateLimitingTests.cs +++ /dev/null @@ -1,88 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FluentAssertions; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Contracts.Requests.Authentication; -using Lumina.DataAccess.Core.UoW; -using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Json; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authentication; - -/// -/// Contains integration tests for the class. -/// -/// -/// This test class needs to be separate from because rate limiting is set per application run, not HTTP client instantiation. -/// -[ExcludeFromCodeCoverage] -public class LoginEndpointRateLimitingTests : IClassFixture, IDisposable -{ - private readonly LuminaApiFactory _apiFactory; - private readonly HttpClient _client; - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - private readonly string _testUsername; - - /// - /// Initializes a new instance of the class. - /// - /// Injected in-memory API factory. - public LoginEndpointRateLimitingTests(LuminaApiFactory apiFactory) - { - _apiFactory = apiFactory; - _client = apiFactory.CreateClient(); - _testUsername = $"testuser_{Guid.NewGuid()}"; - } - - [Fact] - public async Task ExecuteAsync_WhenRateLimitExceeded_ShouldReturnTooManyRequests() - { - // Arrange - LoginRequest request = new( - Username: "testuser", - Password: "TestPass123!" - ); - - // Act - List responses = []; - for (int i = 0; i < 11; i++) // exceed the 10 request limit - responses.Add(await _client.PostAsJsonAsync("/api/v1/auth/login", request)); - - // Assert - HttpResponseMessage lastResponse = responses.Last(); - lastResponse.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); - string content = await lastResponse.Content.ReadAsStringAsync(); - - Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); - problemDetails.Should().NotBeNull(); - problemDetails!["title"].GetString().Should().Be("TooManyRequests"); - problemDetails["retryAfter"].GetString().Should().Be("15"); - } - - public void Dispose() - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - - UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); - if (user is not null) - { - dbContext.Users.Remove(user); - dbContext.SaveChanges(); - } - } -} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs new file mode 100644 index 00000000..59b90215 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs @@ -0,0 +1,99 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.DataAccess.Core.UoW; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.Tokens; +using System.Diagnostics.CodeAnalysis; +using System.Text; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Common.Setup; + +/// +/// Factory for creating a web application for security tests. +/// +[ExcludeFromCodeCoverage] +public class LuminaApiFactory : WebApplicationFactory, IDisposable +{ + private readonly SqliteConnection _connection; + private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; + + /// + /// Initializes a new instance of the class. + /// + public LuminaApiFactory() + { + _connection = new SqliteConnection("DataSource=:memory:"); + _connection.Open(); + } + + /// + /// Configures the web host for the security tests. + /// + /// The web host builder to configure. + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.ConfigureAppConfiguration((context, config) => + { + // clear all existing configuration sources + config.Sources.Clear(); + + config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); + config.AddJsonFile($"appsettings.test.json", optional: true, reloadOnChange: true); + config.AddJsonFile("appsettings.shared.json", optional: true, reloadOnChange: true); + config.AddJsonFile($"appsettings.shared.test.json", optional: true, reloadOnChange: true); + // First add the test values directly + config.AddInMemoryCollection(initialData: new Dictionary + { + ["JwtSettings:SecretKey"] = "test-key-thats-at-least-32-chars-long-for-jwt", + ["JwtSettings:ExpiryMinutes"] = "15", // control the expiry time during tests + ["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY // base64 encoded test key + }); + }); + builder.ConfigureServices(services => + { + // remove existing DbContext configuration + ServiceDescriptor? descriptor = services.SingleOrDefault(serviceDescriptor => serviceDescriptor.ServiceType == typeof(DbContextOptions)); + if (descriptor is not null) + services.Remove(descriptor); + // add SQLite DbContext configuration + services.AddDbContext(options => options.UseSqlite(_connection)); + // configure JWT authentication for testing + services.PostConfigure(JwtBearerDefaults.AuthenticationScheme, options => + { + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuer = true, + ValidateAudience = true, + ValidateLifetime = true, + ValidateIssuerSigningKey = true, + ValidIssuer = "test-issuer", + ValidAudience = "test-audience", + IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("test-key-thats-at-least-32-chars-long-for-jwt")) + }; + }); + // build service provider and ensure database is created + ServiceProvider servicePreovider = services.BuildServiceProvider(); + using (IServiceScope scope = servicePreovider.CreateScope()) + { + IServiceProvider scopedServices = scope.ServiceProvider; + LuminaDbContext dbContext = scopedServices.GetRequiredService(); + dbContext.Database.Migrate(); + } + }); + } + + /// + /// Disposes the connection to the database. + /// + public new void Dispose() + { + _connection.Close(); + base.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthChangePasswordTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthChangePasswordTests.cs new file mode 100644 index 00000000..489480f5 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthChangePasswordTests.cs @@ -0,0 +1,157 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.DataAccess.Core.UoW; +using Lumina.Infrastructure.Core.Authentication; +using Lumina.Infrastructure.Core.Security; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IdentityModel.Tokens.Jwt; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication; + +/// +/// Contains security tests for the /auth/change-password route. +/// +[ExcludeFromCodeCoverage] +public class AuthChangePasswordTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly HashService _hashService; + private readonly string _testUsername; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public AuthChangePasswordTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.12"); + _hashService = new HashService(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + } + + [Fact] + public async Task ChangePassword_WithoutAuthentication_ShouldReturn401() + { + // Arrange + ChangePasswordRequest request = new( + Username: _testUsername, + CurrentPassword: "OldPass123!", + NewPassword: "NewPass123!", + NewPasswordConfirm: "NewPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task ChangePassword_WithValidRequest_ShouldNotLeakTimingInformation() + { + // Arrange + UserEntity user = await CreateAndAuthenticateUser(); + Stopwatch stopwatch = new(); + List timings = []; + + // Act + for (int i = 0; i < 10; i++) + { + await Task.Delay(100); + stopwatch.Restart(); + await _client.PostAsJsonAsync("/api/v1/auth/change-password", new ChangePasswordRequest( + Username: user.Username, + CurrentPassword: "WrongPass123!", + NewPassword: "NewPass123!", + NewPasswordConfirm: "NewPass123!" + )); + stopwatch.Stop(); + timings.Add(stopwatch.ElapsedMilliseconds); + } + + timings.Sort(); + timings = timings.Skip(1).SkipLast(1).ToList(); // remove outliers + + // Assert + double stdDev = CalculateStandardDeviation(timings); + stdDev.Should().BeLessThan(200); + } + + private double CalculateStandardDeviation(List values) + { + double average = values.Average(); + double sumOfSquaresOfDifferences = values.Select(value => (value - average) * (value - average)).Sum(); + return Math.Sqrt(sumOfSquaresOfDifferences / values.Count); + } + + private async Task CreateAndAuthenticateUser() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + // create test user + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + + // authenticate user + LoginRequest loginRequest = new( + Username: user.Username, + Password: "TestPass123!" + ); + + HttpResponseMessage loginResponse = await _client.PostAsJsonAsync("/api/v1/auth/login", loginRequest); + string content = await loginResponse.Content.ReadAsStringAsync(); + LoginResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + // set auth header for subsequent requests + _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token); + + return user; + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + + _client.DefaultRequestHeaders.Authorization = null; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthLoginTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthLoginTests.cs new file mode 100644 index 00000000..d8c74341 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthLoginTests.cs @@ -0,0 +1,350 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.DataAccess.Core.UoW; +using Lumina.Infrastructure.Core.Authentication; +using Lumina.Infrastructure.Core.Security; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IdentityModel.Tokens.Jwt; +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication; + +/// +/// Contains security tests for the /auth/login route. +/// +[ExcludeFromCodeCoverage] +public class AuthLoginTests : IClassFixture, IDisposable +{ + private readonly HashService _hashService; + private readonly ICryptographyService _cryptographyService; + private readonly TotpTokenGenerator _totpTokenGenerator; + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testUsername; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public AuthLoginTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // set a fake IP for this test instance + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.1"); + _hashService = new HashService(); + _totpTokenGenerator = new TotpTokenGenerator(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + + using IServiceScope scope = apiFactory.Services.CreateScope(); + _cryptographyService = scope.ServiceProvider.GetRequiredService(); + } + + [Fact] + public async Task Login_WithValidCredentials_ShouldAuthenticateSuccessfully() + { + // Arrange + UserEntity user = await CreateTestUser(); + LoginRequest request = new( + Username: user.Username, + Password: "TestPass123!" + ); + DateTimeOffset beforeRequest = DateTimeOffset.UtcNow; + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.10"); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + string content = await response.Content.ReadAsStringAsync(); + LoginResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + // Assert + JwtSecurityTokenHandler handler = new(); + JwtSecurityToken token = handler.ReadJwtToken(result!.Token); + + string expValue = token.Claims.First(c => c.Type == "exp").Value; // get token claims + DateTimeOffset tokenExpiration = DateTimeOffset.FromUnixTimeSeconds(long.Parse(expValue)); + DateTimeOffset expectedExpiration = beforeRequest.AddMinutes(15); + + // verify token duration (should be 15 minutes from request time - expiration value is set in tests setup class) + TimeSpan allowedVariance = TimeSpan.FromSeconds(30); // allow for processing time + TimeSpan actualDifference = tokenExpiration - beforeRequest; + TimeSpan expectedDifference = TimeSpan.FromMinutes(15); + + actualDifference.Should().BeCloseTo(expectedDifference, precision: allowedVariance); + + token.Header.Alg.Should().Be("HS256"); + token.Claims.Should().Contain(c => c.Type == "sub" && c.Value == user.Id.ToString()); + token.Claims.Should().Contain(c => c.Type == "unique_name" && c.Value == user.Username); + token.Claims.Should().Contain(c => c.Type == "jti"); + token.Claims.Should().Contain(c => c.Type == "iss" && c.Value == "Lumina"); + token.Claims.Should().Contain(c => c.Type == "aud" && c.Value == "Lumina"); + + content.Should().NotContain("password"); + content.Should().NotContain("hash"); + content.Should().NotContain("salt"); + + // TODO: implement more strict security checks: + // // check security headers + // response.Headers.Should().ContainKey("X-Content-Type-Options") + // .WhoseValue.Should().Contain("nosniff"); + // response.Headers.Should().ContainKey("X-Frame-Options") + // .WhoseValue.Should().Contain("DENY"); + // response.Headers.Should().ContainKey("X-XSS-Protection") + // .WhoseValue.Should().Contain("1; mode=block"); + } + + [Fact] + public async Task Login_WithValidCredentials_ShouldNotLeakTimingInformation() + { + // Arrange + UserEntity user = await CreateTestUser(); + Stopwatch stopwatch = new(); + List timings = []; + // since this test is rigged to trigger the rate limiting, assign a different IP to it + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.2"); + + // Act + for (int i = 0; i < 10; i++) + { + await Task.Delay(100); // add small delay between requests + stopwatch.Restart(); + await _client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest( + Username: user.Username, + Password: "TestPass123!" + )); + stopwatch.Stop(); + timings.Add(stopwatch.ElapsedMilliseconds); + } + // remove the highest and lowest values to account for outliers + timings.Sort(); + timings = timings.Skip(1).SkipLast(1).ToList(); + + // Assert + // check for timing consistency to prevent timing attacks + double stdDev = CalculateStandardDeviation(timings); + stdDev.Should().BeLessThan(200); + } + + [Fact] + public async Task ExecuteAsync_WhenRateLimitExceeded_ShouldReturnTooManyRequests() + { + // Arrange + // set a fake IP for this test instance + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.3"); + LoginRequest request = new( + Username: "testuser", + Password: "TestPass123!" + ); + + // Act + List responses = []; + for (int i = 0; i < 11; i++) // exceed the 10 request limit + responses.Add(await _client.PostAsJsonAsync("/api/v1/auth/login", request)); + + // Assert + HttpResponseMessage lastResponse = responses.Last(); + lastResponse.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + string content = await lastResponse.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status429TooManyRequests); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7231#section-6.5.29"); + problemDetails["title"].GetString().Should().Be("TooManyRequests"); + problemDetails["detail"].GetString().Should().Be("Too many attempts. Please try again later."); + problemDetails["retryAfter"].GetString().Should().Be("15"); + + lastResponse.Headers.Should().ContainKey("X-RateLimit-Limit"); + lastResponse.Headers.Should().ContainKey("X-RateLimit-Reset"); + lastResponse.Headers.Should().ContainKey("X-RateLimit-Remaining"); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("admin'--")] // comment injection + [InlineData("' UNION SELECT * FROM Users--")] // union injection + [InlineData("'; DROP TABLE Users--")] // destructive injection + [InlineData("' WAITFOR DELAY '0:0:10'--")] // time-based injection + public async Task Login_WithSQLInjectionAttempt_ShouldRemainSecure(string maliciousUsername) + { + // Arrange + UserEntity legitimateUser = await CreateTestUser(); + LoginRequest request = new( + Username: maliciousUsername, + Password: "Abcd123$" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + content.Should().NotContain("SQL"); + content.Should().NotContain("Exception"); + content.Should().NotContain(legitimateUser.Username); // shouldn't expose other usernames + content.Should().NotContain(legitimateUser.Password); // shouldn't expose password hashes + } + + [Fact] + public async Task Login_WithSQLInjectionInValidUser_ShouldRemainSecure() + { + // Arrange + UserEntity user = await CreateTestUser(); + LoginRequest request = new( + Username: user.Username, + Password: "' OR '1'='1" + ); + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.11"); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + content.Should().NotContain("SQL"); + content.Should().NotContain("Exception"); + } + + [Fact] + public async Task Login_WithInjectionInTotpCode_ShouldRemainSecure() + { + // Arrange + UserEntity user = await CreateTestUserWithTotp(); + LoginRequest request = new( + Username: user.Username, + Password: "TestPass123!", + TotpCode: "' OR '1'='1" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + content.Should().NotContain("SQL"); + content.Should().NotContain("Exception"); + } + + private double CalculateStandardDeviation(List values) + { + double average = values.Average(); + double sumOfSquaresOfDifferences = values.Select(value => (value - average) * (value - average)).Sum(); + return Math.Sqrt(sumOfSquaresOfDifferences / values.Count); + } + + private async Task CreateTestUser() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + private async Task CreateTestUserWithTotp() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + byte[] totpSecret = _totpTokenGenerator.GenerateSecret(); + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + private async Task CreateTestUserWithTempPassword() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")), + TempPasswordCreated = DateTime.UtcNow, + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + private async Task CreateTestUserWithExpiredTempPassword() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")), + TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16), // expired (> 15 minutes old) + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointRateLimitingTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthRecoverPasswordTests.cs similarity index 77% rename from tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointRateLimitingTests.cs rename to tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthRecoverPasswordTests.cs index 6ac4db70..b2268000 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointRateLimitingTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AuthRecoverPasswordTests.cs @@ -3,31 +3,23 @@ using FluentAssertions; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Requests.Authentication; using Lumina.DataAccess.Core.UoW; -using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Net; -using System.Net.Http; using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Serialization; -using System.Threading.Tasks; #endregion -namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authentication; +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication; /// -/// Contains integration tests for the class. +/// Contains security tests for the /auth/recover-password route. /// -/// -/// This test class needs to be separate from because rate limiting is set per application run, not HTTP client instantiation. -/// [ExcludeFromCodeCoverage] -public class RecoverPasswordEndpointRateLimitingTests : IClassFixture, IDisposable +public class AuthRecoverPasswordTests : IClassFixture, IDisposable { private readonly LuminaApiFactory _apiFactory; private readonly HttpClient _client; @@ -39,13 +31,16 @@ public class RecoverPasswordEndpointRateLimitingTests : IClassFixture - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// Injected in-memory API factory. - public RecoverPasswordEndpointRateLimitingTests(LuminaApiFactory apiFactory) + public AuthRecoverPasswordTests(LuminaApiFactory apiFactory) { _apiFactory = apiFactory; _client = apiFactory.CreateClient(); + // set a fake IP for this test instance + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.4"); _testUsername = $"testuser_{Guid.NewGuid()}"; } @@ -75,6 +70,10 @@ public class RecoverPasswordEndpointRateLimitingTests : IClassFixture +/// Contains security tests for the /auth/register route. +/// +[ExcludeFromCodeCoverage] +public class AuthRegisterTests : IClassFixture, IDisposable +{ + private readonly HashService _hashService; + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testUsername; + + public AuthRegisterTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.5"); + _hashService = new HashService(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + } + + [Fact] + public async Task Register_WithValidData_ShouldNotLeakTimingInformation() + { + // Arrange + Stopwatch stopwatch = new(); + List timings = []; + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.6"); + RegistrationRequest request = new( + Username: _testUsername, + Password: "TestPass123!", + PasswordConfirm: "TestPass123!" + ); + + // Act + for (int i = 0; i < 10; i++) + { + await Task.Delay(100); + stopwatch.Restart(); + await _client.PostAsJsonAsync("/api/v1/auth/register", request); + stopwatch.Stop(); + timings.Add(stopwatch.ElapsedMilliseconds); + } + timings.Sort(); + timings = timings.Skip(1).SkipLast(1).ToList(); + + // Assert + double stdDev = CalculateStandardDeviation(timings); + stdDev.Should().BeLessThan(200); + } + + [Fact] + public async Task Register_WhenRateLimitExceeded_ShouldReturnTooManyRequests() + { + // Arrange + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.7"); + RegistrationRequest request = new( + Username: _testUsername, + Password: "TestPass123!", + PasswordConfirm: "TestPass123!" + ); + + // Act + List responses = []; + for (int i = 0; i < 11; i++) + responses.Add(await _client.PostAsJsonAsync("/api/v1/auth/register", request)); + + // Assert + HttpResponseMessage lastResponse = responses.Last(); + lastResponse.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + string content = await lastResponse.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status429TooManyRequests); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7231#section-6.5.29"); + problemDetails["title"].GetString().Should().Be("TooManyRequests"); + problemDetails["detail"].GetString().Should().Be("Too many attempts. Please try again later."); + problemDetails["retryAfter"].GetString().Should().Be("15"); + + lastResponse.Headers.Should().ContainKey("X-RateLimit-Limit"); + lastResponse.Headers.Should().ContainKey("X-RateLimit-Reset"); + lastResponse.Headers.Should().ContainKey("X-RateLimit-Remaining"); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("admin'--")] // comment injection + [InlineData("' UNION SELECT * FROM Users--")] // union injection + [InlineData("'; DROP TABLE Users--")] // destructive injection + [InlineData("' WAITFOR DELAY '0:0:10'--")] // time-based injection + public async Task Register_WithSQLInjectionAttempt_ShouldRemainSecure(string maliciousUsername) + { + // Arrange + RegistrationRequest request = new( + Username: maliciousUsername, + Password: "TestPass123!", + PasswordConfirm: "TestPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + content.Should().NotContain("SQL"); + content.Should().NotContain("Exception"); + content.Should().NotContain("password"); + content.Should().NotContain("hash"); + content.Should().NotContain("salt"); + } + + [Theory] + [InlineData("password123")] // common password + [InlineData("123456789")] // numeric only + [InlineData("abcdefgh")] // lowercase only + [InlineData("short")] // too short + public async Task Register_WithWeakPassword_ShouldBeDenied(string weakPassword) + { + // Arrange + RegistrationRequest request = new( + Username: _testUsername, + Password: weakPassword, + PasswordConfirm: weakPassword + ); + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.8"); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + content.Should().NotContain(weakPassword); // shouldn't leak the actual password + } + + [Theory] + [InlineData("TestPass123!")] // valid password + [InlineData("Ab1!defghijklmnopqrstuvwxyz")] // long password + public async Task Register_WithValidPassword_ShouldAcceptPassword(string password) + { + // Arrange + RegistrationRequest request = new( + Username: _testUsername, + Password: password, + PasswordConfirm: password + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Created); + } + + [Fact] + public async Task Register_WithExistingUsername_ShouldNotLeakUserExistence() + { + // Arrange + await CreateTestUser(); + RegistrationRequest request = new( + Username: _testUsername, + Password: "TestPass123!", + PasswordConfirm: "TestPass123!" + ); + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.9"); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Conflict); + content.Should().NotContain(_testUsername); + content.Should().NotContain("password"); + content.Should().NotContain("hash"); + content.Should().NotContain("salt"); + } + + private double CalculateStandardDeviation(List values) + { + double average = values.Average(); + double sumOfSquaresOfDifferences = values.Select(value => (value - average) * (value - average)).Sum(); + return Math.Sqrt(sumOfSquaresOfDifferences / values.Count); + } + + private async Task CreateTestUser() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Lumina.Presentation.Api.SecurityTests.csproj b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Lumina.Presentation.Api.SecurityTests.csproj new file mode 100644 index 00000000..cce178dc --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Lumina.Presentation.Api.SecurityTests.csproj @@ -0,0 +1,46 @@ + + + + net8.0 + enable + enable + + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + +