mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 15:11:10 +00:00
Makes SQL injection security tests exercise the database and centralizes test setup helpers.
This commit is contained in:
1 parent
cbe27ab22e
commit
a13eeee43e
26 files changed
+589
-138
No files matched your search
+33
@@ -6,6 +6,7 @@ using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
@@ -97,6 +98,38 @@ public class ChangePasswordEndpointTests : IClassFixture<LuminaApiFactory>, IDis
|
||||
AssertProblemDetail(secondContent, "General.Failure", "InvalidCurrentPassword");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Users--")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task ChangePassword_WithSQLInjectionInUsername_ShouldNotCorruptOrDeleteData(string maliciousUsername)
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateAndAuthenticateUser();
|
||||
string originalPasswordHash = user.Password;
|
||||
ChangePasswordRequest request = new(
|
||||
Username: maliciousUsername,
|
||||
CurrentPassword: "TestPass123!",
|
||||
NewPassword: "NewPass123!",
|
||||
NewPasswordConfirm: "NewPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
|
||||
|
||||
// Assert
|
||||
// the malicious username is queried by GetByUsernameAsync, so it must never be executed against the database;
|
||||
// if a boolean-injection regression returned the only user in the database, the current password would match and
|
||||
// the password would change, so the response must be a failure and the stored password hash must be unchanged
|
||||
Assert.NotEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity? storedUser = await dbContext.Users.FirstOrDefaultAsync(candidate => candidate.Id == user.Id);
|
||||
Assert.NotNull(storedUser);
|
||||
Assert.Equal(originalPasswordHash, storedUser!.Password);
|
||||
}
|
||||
|
||||
private void AssertProblemDetail(string content, string expectedTitle, string expectedDetail)
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
|
||||
+9
-10
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
@@ -8,6 +9,7 @@ using Lumina.Infrastructure.Core.Authentication;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
@@ -26,6 +28,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.A
|
||||
public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly ICryptographyService _cryptographyService;
|
||||
private readonly TotpTokenGenerator _totpTokenGenerator = new();
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
@@ -197,6 +200,11 @@ public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
Assert.DoesNotContain("Exception", content);
|
||||
Assert.DoesNotContain(legitimateUser.Username, content); // shouldn't expose other usernames
|
||||
Assert.DoesNotContain(legitimateUser.Password, content); // shouldn't expose password hashes
|
||||
|
||||
// the injected statement must never be executed: the Users table and the seeded user must still be there
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.NotNull(await dbContext.Users.FirstOrDefaultAsync(user => user.Id == legitimateUser.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -255,16 +263,7 @@ public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity user = new()
|
||||
{
|
||||
Username = _testUsername,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!"));
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
+56
@@ -1,15 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
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.SecurityTests.Core.Endpoints.UsersManagement.Authentication;
|
||||
@@ -22,6 +30,8 @@ public class RecoverPasswordEndpointTests : IClassFixture<LuminaApiFactory>, IDi
|
||||
{
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
@@ -75,6 +85,52 @@ public class RecoverPasswordEndpointTests : IClassFixture<LuminaApiFactory>, IDi
|
||||
Assert.True(lastResponse.Headers.Contains("X-RateLimit-Remaining"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Users--")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task RecoverPassword_WithSQLInjectionInUsername_ShouldNotCorruptOrDeleteData(string maliciousUsername)
|
||||
{
|
||||
// Arrange
|
||||
// use a dedicated unique IP, so the rate-limit test (which exhausts the 10-permit window on its own IP)
|
||||
// cannot run first and 429 this test; the NotEqual(TooManyRequests) assertion below guards against any collision
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
client.DefaultRequestHeaders.Clear();
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
UserEntity legitimateUser = await CreateTestUser();
|
||||
RecoverPasswordRequest request = new(
|
||||
Username: maliciousUsername,
|
||||
TotpCode: "123456"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/auth/recover-password", request);
|
||||
|
||||
// Assert
|
||||
// the malicious username queries for a user, so it must never be executed against the database
|
||||
Assert.NotEqual(HttpStatusCode.TooManyRequests, response.StatusCode);
|
||||
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.NotNull(await dbContext.Users.FirstOrDefaultAsync(user => user.Id == legitimateUser.Id));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user in the database.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateTestUser()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!"));
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return user;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
|
||||
+5
-10
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
@@ -22,6 +23,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.A
|
||||
public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
@@ -110,6 +112,8 @@ public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
public async Task Register_WithSQLInjectionAttempt_ShouldRemainSecure(string maliciousUsername)
|
||||
{
|
||||
// Arrange
|
||||
// note: the register validator rejects these usernames (invalid username format) with 422 before any DB access,
|
||||
// so the malicious username never reaches a query; the 422 assertion below is the security guarantee
|
||||
RegistrationRequest request = new(
|
||||
Username: maliciousUsername,
|
||||
Password: "TestPass123!",
|
||||
@@ -210,16 +214,7 @@ public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity user = new()
|
||||
{
|
||||
Username = _testUsername,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!"));
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
Reference in new issue
Block a user