mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +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
+5
-3
@@ -21,8 +21,10 @@ public class UserEntityFixture
|
||||
/// Creates a random valid <see cref="UserEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryCount">Number of libraries to generate. Default is 0.</param>
|
||||
/// <param name="username">Optional username to pin, or <see langword="null"/> to generate a random one.</param>
|
||||
/// <param name="password">Optional password to pin, or <see langword="null"/> to generate a random one.</param>
|
||||
/// <returns>The created user entity.</returns>
|
||||
public UserEntity Create(int libraryCount = 0)
|
||||
public UserEntity Create(int libraryCount = 0, string? username = null, string? password = null)
|
||||
{
|
||||
Guid userId = Guid.NewGuid();
|
||||
List<LibraryEntity> libraries = libraryCount > 0
|
||||
@@ -42,8 +44,8 @@ public class UserEntityFixture
|
||||
UserRole = null,
|
||||
CreatedBy = userId
|
||||
})
|
||||
.RuleFor(x => x.Username, f => f.Internet.UserName())
|
||||
.RuleFor(x => x.Password, f => Uri.EscapeDataString(f.Internet.Password()))
|
||||
.RuleFor(x => x.Username, f => username ?? f.Internet.UserName())
|
||||
.RuleFor(x => x.Password, f => password ?? Uri.EscapeDataString(f.Internet.Password()))
|
||||
.RuleFor(x => x.CreatedOnUtc, f => f.Date.Past())
|
||||
.RuleFor(x => x.TotpSecret, f => f.Random.Bool() ? f.Random.String2(32) : null)
|
||||
.Generate();
|
||||
|
||||
+138
-1
@@ -1,10 +1,13 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Common.Interceptors;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
@@ -109,6 +112,16 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a unique IP address derived from a fresh GUID, to isolate the rate-limiting partition of each test.
|
||||
/// </summary>
|
||||
/// <returns>A unique IP address in the 192.168.0.0/16 private range.</returns>
|
||||
public static string GetUniqueTestIp()
|
||||
{
|
||||
byte[] bytes = Guid.NewGuid().ToByteArray();
|
||||
return $"192.168.{bytes[0]}.{bytes[1]}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user with the Admin role, authenticates it on <paramref name="client"/>, and returns its Id.
|
||||
/// </summary>
|
||||
@@ -118,7 +131,7 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
|
||||
{
|
||||
// a unique X-Forwarded-For isolates rate limiting state per test
|
||||
client.DefaultRequestHeaders.Clear();
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", GetUniqueTestIp());
|
||||
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
@@ -169,6 +182,130 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user, authenticates it on <paramref name="client"/>, and returns its Id and username.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to configure with authentication headers.</param>
|
||||
/// <returns>The Id and username of the created test user.</returns>
|
||||
public async Task<(Guid UserId, string Username)> CreateAndAuthenticateUserAsync(HttpClient client)
|
||||
{
|
||||
// a unique X-Forwarded-For isolates rate limiting state per test
|
||||
client.DefaultRequestHeaders.Clear();
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", GetUniqueTestIp());
|
||||
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = userId,
|
||||
Username = username,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a test user and its owned libraries from the database.
|
||||
/// </summary>
|
||||
/// <param name="username">The username of the test user to remove.</param>
|
||||
public async Task RemoveTestUserAsync(string username)
|
||||
{
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity? user = await dbContext.Users.Include(candidate => candidate.Libraries).FirstOrDefaultAsync(candidate => candidate.Username == username).ConfigureAwait(false);
|
||||
if (user is not null)
|
||||
{
|
||||
dbContext.Libraries.RemoveRange(user.Libraries);
|
||||
dbContext.Users.Remove(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a test admin user, its role, and its user-role link from the database.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the admin test user to remove.</param>
|
||||
public async Task RemoveAdminUserAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserRoleEntity? userRole = await dbContext.UserRoles.FirstOrDefaultAsync(candidate => candidate.UserId == userId).ConfigureAwait(false);
|
||||
if (userRole is not null)
|
||||
{
|
||||
RoleEntity? role = await dbContext.Roles.FirstOrDefaultAsync(candidate => candidate.Id == userRole.RoleId).ConfigureAwait(false);
|
||||
if (role is not null)
|
||||
dbContext.Roles.Remove(role);
|
||||
dbContext.UserRoles.Remove(userRole);
|
||||
}
|
||||
UserEntity? user = await dbContext.Users.FirstOrDefaultAsync(candidate => candidate.Id == userId).ConfigureAwait(false);
|
||||
if (user is not null)
|
||||
dbContext.Users.Remove(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library to seed.</param>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
public async Task SeedLibraryAsync(Guid libraryId, Guid userId)
|
||||
{
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="BookEntity"/> belonging to the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
||||
/// <param name="title">The title of the book.</param>
|
||||
public async Task SeedBookAsync(Guid libraryId, string title)
|
||||
{
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Books.Add(new BookEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
Path = $"/books/{Guid.NewGuid()}.epub",
|
||||
Title = title,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the connection to the database.
|
||||
/// </summary>
|
||||
|
||||
+83
-1
@@ -1,10 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorization.Roles;
|
||||
@@ -13,13 +22,17 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorizati
|
||||
/// Contains security tests for the <c>/auth/roles</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddRoleEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
public class AddRoleEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private Guid _adminUserId;
|
||||
private Guid _seededPermissionId;
|
||||
private string _createdRoleName = "";
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddRoleEndpointTests"/> class.
|
||||
@@ -27,6 +40,7 @@ public class AddRoleEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public AddRoleEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
@@ -57,4 +71,72 @@ public class AddRoleEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
Assert.Equal("/api/v1/auth/roles", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Roles--")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task AddRole_WithSQLInjectionInRoleName_ShouldNotCorruptOrDeleteData(string maliciousRoleName)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
_adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
_seededPermissionId = Guid.NewGuid();
|
||||
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
seedDbContext.Permissions.Add(new PermissionEntity
|
||||
{
|
||||
Id = _seededPermissionId,
|
||||
PermissionName = AuthorizationPermission.CanDeleteUsers,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
await seedDbContext.SaveChangesAsync();
|
||||
}
|
||||
var requestBody = new
|
||||
{
|
||||
RoleName = maliciousRoleName,
|
||||
Permissions = new[] { _seededPermissionId }
|
||||
};
|
||||
_createdRoleName = maliciousRoleName;
|
||||
StringContent content = new(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsync("/api/v1/auth/roles", content);
|
||||
|
||||
// Assert
|
||||
// the malicious role name passes the authenticated handler and the permissions validation, reaches the
|
||||
// parameterized insert, and is persisted verbatim: if it were concatenated into raw SQL, the insert would fail
|
||||
Assert.Equal(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>();
|
||||
Assert.NotNull(await dbContext.Roles.FirstOrDefaultAsync(role => role.RoleName == maliciousRoleName));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
if (_seededPermissionId != Guid.Empty)
|
||||
{
|
||||
PermissionEntity? permission = dbContext.Permissions.FirstOrDefault(candidate => candidate.Id == _seededPermissionId);
|
||||
if (permission is not null)
|
||||
dbContext.Permissions.Remove(permission);
|
||||
}
|
||||
if (!string.IsNullOrEmpty(_createdRoleName))
|
||||
{
|
||||
RoleEntity? createdRole = dbContext.Roles.FirstOrDefault(candidate => candidate.RoleName == _createdRoleName);
|
||||
if (createdRole is not null)
|
||||
dbContext.Roles.Remove(createdRole);
|
||||
}
|
||||
dbContext.SaveChanges();
|
||||
if (_adminUserId != Guid.Empty)
|
||||
_apiFactory.RemoveAdminUserAsync(_adminUserId).GetAwaiter().GetResult();
|
||||
}
|
||||
}
|
||||
+93
-1
@@ -1,11 +1,20 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Contracts.Requests.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorization.Roles;
|
||||
@@ -14,13 +23,17 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorizati
|
||||
/// Contains security tests for the <c>/auth/roles</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateRoleEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
public class UpdateRoleEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private Guid _adminUserId;
|
||||
private Guid _seededPermissionId;
|
||||
private Guid _seededRoleId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateRoleEndpointTests"/> class.
|
||||
@@ -28,6 +41,7 @@ public class UpdateRoleEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdateRoleEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
@@ -63,4 +77,82 @@ public class UpdateRoleEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
Assert.Equal("/api/v1/auth/roles", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Roles--")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task UpdateRole_WithSQLInjectionInRoleName_ShouldNotCorruptOrDeleteData(string maliciousRoleName)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
_adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
_seededPermissionId = Guid.NewGuid();
|
||||
_seededRoleId = Guid.NewGuid();
|
||||
RoleEntity seededRole = new()
|
||||
{
|
||||
Id = _seededRoleId,
|
||||
RoleName = "ExistingRole",
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
seedDbContext.Permissions.Add(new PermissionEntity
|
||||
{
|
||||
Id = _seededPermissionId,
|
||||
PermissionName = AuthorizationPermission.CanDeleteUsers,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
seedDbContext.Roles.Add(seededRole);
|
||||
await seedDbContext.SaveChangesAsync();
|
||||
}
|
||||
UpdateRoleRequest requestBody = new(
|
||||
RoleId: seededRole.Id,
|
||||
RoleName: maliciousRoleName,
|
||||
Permissions: [_seededPermissionId]
|
||||
);
|
||||
StringContent content = new(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsync("/api/v1/auth/roles", content);
|
||||
|
||||
// Assert
|
||||
// the malicious role name passes the authenticated handler and the permissions validation, reaches the
|
||||
// parameterized update, and is persisted verbatim: if it were concatenated into raw SQL, the update would fail
|
||||
Assert.Equal(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>();
|
||||
RoleEntity? updatedRole = await dbContext.Roles.FirstOrDefaultAsync(role => role.Id == seededRole.Id);
|
||||
Assert.NotNull(updatedRole);
|
||||
Assert.Equal(maliciousRoleName, updatedRole!.RoleName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
if (_seededPermissionId != Guid.Empty)
|
||||
{
|
||||
PermissionEntity? permission = dbContext.Permissions.FirstOrDefault(candidate => candidate.Id == _seededPermissionId);
|
||||
if (permission is not null)
|
||||
dbContext.Permissions.Remove(permission);
|
||||
}
|
||||
if (_seededRoleId != Guid.Empty)
|
||||
{
|
||||
RoleEntity? role = dbContext.Roles.FirstOrDefault(candidate => candidate.Id == _seededRoleId);
|
||||
if (role is not null)
|
||||
dbContext.Roles.Remove(role);
|
||||
}
|
||||
dbContext.SaveChanges();
|
||||
if (_adminUserId != Guid.Empty)
|
||||
_apiFactory.RemoveAdminUserAsync(_adminUserId).GetAwaiter().GetResult();
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -101,7 +101,7 @@ public class AddLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
// the malicious title passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
+1
-1
@@ -86,7 +86,7 @@ public class CancelLibraryScanEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
+1
-1
@@ -85,7 +85,7 @@ public class DeleteLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
+3
-1
@@ -89,9 +89,11 @@ public class GetLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
// note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding
|
||||
// ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here)
|
||||
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
|
||||
// note: the payloads never contain the literal "SQL", so checking for that word would assert nothing; what matters
|
||||
// is that the injection never reaches the database, so no SQL engine error (SqliteException) may surface
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
+1
-1
@@ -85,7 +85,7 @@ public class GetLibraryScanProgressEndpointTests : IClassFixture<LuminaApiFactor
|
||||
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
+1
-1
@@ -85,7 +85,7 @@ public class ScanLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
+1
-1
@@ -109,7 +109,7 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
// the malicious title passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.AddBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/books</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddBookEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly AddBookRequestFixture _addBookRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddBookEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public AddBookEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Books; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task AddBook_WithSQLInjectionInPath_ShouldNotCorruptOrDeleteData(string maliciousPath)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await _apiFactory.SeedLibraryAsync(libraryId, userId);
|
||||
AddBookRequest request = _addBookRequestFixture.Create() with { LibraryId = libraryId, Path = maliciousPath };
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/books", request);
|
||||
|
||||
// Assert
|
||||
// the malicious path passes the authenticated handler, reaches the parameterized insert, and is persisted
|
||||
// verbatim: if it were concatenated into raw SQL, the insert would fail and the book would not be created
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Equal(1, await dbContext.Libraries.CountAsync(library => library.Id == libraryId));
|
||||
// the single book in the library is the one inserted by this request, with the malicious path stored as data
|
||||
Assert.Equal(1, await dbContext.Books.CountAsync(book => book.LibraryId == libraryId));
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
// nothing to clean up: each test removes its own seeded rows
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -58,7 +58,7 @@ public class GetBookEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
// Assert
|
||||
// the endpoint processes the value without querying the persistence medium and without leaking it
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
+21
-96
@@ -1,20 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
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.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks;
|
||||
@@ -23,11 +17,10 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenCo
|
||||
/// Contains security tests for the <c>/books</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetBooksEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
public class GetBooksEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
@@ -64,16 +57,16 @@ public class GetBooksEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Books--")] // destructive injection
|
||||
public async Task GetBooks_WhenSearchTermContainsSqlInjection_ShouldNotLeakOrError(string maliciousSearchTerm)
|
||||
[InlineData("'; DROP TABLE Books; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task GetBooks_WhenSearchTermContainsSqlInjection_ShouldNotCorruptOrDeleteData(string maliciousSearchTerm)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await CreateAndAuthenticateUserAsync(client);
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
await SeedBookAsync(libraryId, "Book A");
|
||||
await _apiFactory.SeedLibraryAsync(libraryId, userId);
|
||||
await _apiFactory.SeedBookAsync(libraryId, "Book A");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/books?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}");
|
||||
@@ -81,89 +74,21 @@ public class GetBooksEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// the injected statement must never be executed: the Books table and the seeded rows must still be there
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Equal(1, await dbContext.Books.CountAsync(book => book.LibraryId == libraryId));
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user, authenticates it on <paramref name="client"/>, and returns its Id.
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>The Id of the created test user.</returns>
|
||||
private async Task<Guid> CreateAndAuthenticateUserAsync(HttpClient client)
|
||||
public void Dispose()
|
||||
{
|
||||
client.DefaultRequestHeaders.Clear();
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = username,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library to seed.</param>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="BookEntity"/> belonging to the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
||||
/// <param name="title">The title of the book.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedBookAsync(Guid libraryId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Books.Add(new BookEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
Path = $"/books/{Guid.NewGuid()}.epub",
|
||||
Title = title,
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
// nothing to clean up: each test removes its own seeded rows
|
||||
}
|
||||
}
|
||||
+45
-1
@@ -1,9 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite;
|
||||
@@ -12,9 +18,10 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenCo
|
||||
/// Contains security tests for the <c>/books/lite</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetBooksLiteEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
public class GetBooksLiteEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
@@ -26,6 +33,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetBooksLiteEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
@@ -48,4 +56,40 @@ public class GetBooksLiteEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
Assert.Equal("/api/v1/books/lite", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Books; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task GetBooksLite_WhenSearchTermContainsSqlInjection_ShouldNotCorruptOrDeleteData(string maliciousSearchTerm)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await _apiFactory.SeedLibraryAsync(libraryId, userId);
|
||||
await _apiFactory.SeedBookAsync(libraryId, "Book A");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// the injected statement must never be executed: the Books table and the seeded rows must still be there
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Equal(1, await dbContext.Books.CountAsync(book => book.LibraryId == libraryId));
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
// nothing to clean up: each test removes its own seeded rows
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -86,7 +86,7 @@ public class GetLibraryMetadataProvidersEndpointTests : IClassFixture<LuminaApiF
|
||||
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
+1
-1
@@ -84,7 +84,7 @@ public class GetPluginSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
+1
-1
@@ -97,7 +97,7 @@ public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture<Lumina
|
||||
// note: that 500 body leaks the JsonException details, so no DoesNotContain("Exception") is asserted here
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
+1
-1
@@ -99,7 +99,7 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture<Lumi
|
||||
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
+1
-1
@@ -90,7 +90,7 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
// the malicious value passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
+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();
|
||||
|
||||
+2
@@ -41,5 +41,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\src\Lumina.Presentation.Api\Lumina.Presentation.Api.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Application.Fixtures\Lumina.Application.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
+3
-2
@@ -6,6 +6,7 @@ using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookL
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
@@ -45,8 +46,8 @@ public class BookMappingTests
|
||||
Assert.Equal(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.LanguageCode : null, result.OriginalLanguageCode);
|
||||
Assert.Equal(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.LanguageName : null, result.OriginalLanguageName);
|
||||
Assert.Equal(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.NativeName.Value : null, result.OriginalLanguageNativeName);
|
||||
Assert.Equal(book.Metadata.Tags.ToRepositoryEntities(), result.Tags);
|
||||
Assert.Equal(book.Metadata.Genres.ToRepositoryEntities(), result.Genres);
|
||||
Assert.Equal(book.Metadata.Tags.ToRepositoryEntities().OrderBy(tag => tag.Name), result.Tags.OrderBy(tag => tag.Name));
|
||||
Assert.Equal(book.Metadata.Genres.ToRepositoryEntities().OrderBy(genre => genre.Name), result.Genres.OrderBy(genre => genre.Name));
|
||||
Assert.Equal(book.Metadata.Publisher.HasValue ? book.Metadata.Publisher.Value : null, result.Publisher);
|
||||
Assert.Equal(book.Metadata.PageCount.HasValue ? book.Metadata.PageCount.Value : null, result.PageCount);
|
||||
Assert.Equal(book.Format.HasValue ? book.Format.Value : null, result.Format);
|
||||
|
||||
Reference in new issue
Block a user