Updates the provider configuration and ownership tests

Covers the provider and reader choices saved with a library, the reconciliation and stale configuration deletion in the provider store, the library type lookups, the ownership and permission checks for update and delete, and the validator behavior for enum names.
This commit is contained in:
BinaryAlley committed 2026-11-03 10:00:00 +02:00
1 parent 48ad8692af
commit 64e5163229
127 files changed
+5541 -5296

No files matched your search

@@ -9,6 +9,7 @@ using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Common.Interceptors;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.Security;
using Microsoft.AspNetCore.Authentication.JwtBearer;
@@ -45,6 +46,8 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
private readonly UserEntityFixture _userEntityFixture = new();
private readonly RoleEntityFixture _roleEntityFixture = new();
private readonly UserRoleEntityFixture _userRoleEntityFixture = new();
private readonly PermissionEntityFixture _permissionEntityFixture = new();
private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=";
@@ -55,11 +58,11 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
/// </summary>
public LuminaApiFactory()
{
// each factory gets its own uniquely named shared in-memory database, so that parallel test classes remain isolated from one another;
// Each factory gets its own uniquely named shared in-memory database, so that parallel test classes remain isolated from one another;
// the shared cache allows each DbContext to open its own pooled connection to the same database, instead of sharing a single connection,
// which would otherwise serialize every request on one connection and cause nested transaction errors between requests
// which would otherwise serialize every request on one connection and cause nested transaction errors between requests.
_sharedInMemoryConnectionString = string.Format(SHARED_IN_MEMORY_CONNECTION_STRING_PREFIX, Guid.NewGuid());
// keep a single anchor connection open, so that the shared in-memory database it refers to is not dropped
// Keep a single anchor connection open, so that the shared in-memory database it refers to is not dropped.
_connection = new SqliteConnection(_sharedInMemoryConnectionString);
_connection.Open();
}
@@ -202,6 +205,40 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
return (userId, username);
}
/// <summary>
/// Creates a test user that holds a single permission directly, 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>
/// <param name="permission">The permission granted to the created user.</param>
/// <returns>The Id and username of the created test user.</returns>
public async Task<(Guid UserId, string Username)> CreateAndAuthenticateUserWithPermissionAsync(HttpClient client, AuthorizationPermission permission)
{
// 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 = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
user.TotpSecret = null;
dbContext.Users.Add(user);
PermissionEntity permissionEntity = _permissionEntityFixture.Create(permissionName: permission);
dbContext.Permissions.Add(permissionEntity);
dbContext.UserPermissions.Add(_userPermissionEntityFixture.Create(user, permissionEntity));
await dbContext.SaveChangesAsync();
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "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>
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
@@ -60,12 +61,12 @@ public class DeleteLibraryEndpointTests : IClassFixture<LuminaApiFactory>
}
[Theory]
[InlineData("' OR '1'='1")] // basic SQL injection
[InlineData("'; DROP TABLE Libraries--")] // destructive injection
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Libraries--")] // Destructive injection.
public async Task DeleteLibrary_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId)
{
// Arrange
// authenticate with an admin user and seed a library, so a valid id would reach the handler and be authorized
// Authenticate with an admin user and seed a library, so a valid id would reach the handler and be authorized.
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
await SeedLibraryAsync(userId);
@@ -74,10 +75,9 @@ public class DeleteLibraryEndpointTests : IClassFixture<LuminaApiFactory>
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}");
// Assert
// note: the {id} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler
// 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 {id} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler.
// The 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).
// 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("SqliteException", content, StringComparison.OrdinalIgnoreCase);
@@ -86,6 +86,68 @@ public class DeleteLibraryEndpointTests : IClassFixture<LuminaApiFactory>
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task DeleteLibrary_WhenTheOwnerLacksTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary()
{
// Arrange
// The created user holds no permission, so it owns the library without being allowed to change it.
HttpClient client = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.NotNull(await dbContext.Libraries.FindAsync(libraryId));
}
await _apiFactory.RemoveTestUserAsync(ownerUsername);
}
[Fact]
public async Task DeleteLibrary_WhenNonOwnerHoldsTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary()
{
// Arrange
// Ownership and the manage permission are both required, so a user that holds the permission must not delete a library it does not own.
HttpClient client = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
(Guid _, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserWithPermissionAsync(client, AuthorizationPermission.CanCreateLibraries);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.NotNull(await dbContext.Libraries.FindAsync(libraryId));
}
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveTestUserAsync(attackerUsername);
}
/// <summary>
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
@@ -4,6 +4,7 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Manage
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
@@ -13,6 +14,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Nodes;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.UpdateLibrary;
@@ -49,7 +51,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
string libraryId = Guid.NewGuid().ToString();
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: Guid.NewGuid(),
userId: Guid.NewGuid(),
title: "Updated Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -79,8 +80,8 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
}
[Theory]
[InlineData("' OR '1'='1")] // basic SQL injection
[InlineData("'; DROP TABLE Libraries--")] // destructive injection
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Libraries--")] // Destructive injection.
public async Task UpdateLibrary_WithSQLInjectionInTitle_ShouldNotLeakOrError(string maliciousTitle)
{
// Arrange
@@ -90,7 +91,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
await SeedLibraryAsync(libraryId, userId);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: maliciousTitle,
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -106,7 +106,7 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
// the malicious title passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim
// 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("SqliteException", content, StringComparison.OrdinalIgnoreCase);
@@ -123,10 +123,10 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
}
[Theory]
[InlineData(-1)] // just below the allowed range
[InlineData(101)] // just above the allowed range
[InlineData(int.MinValue)] // lowest possible value
[InlineData(int.MaxValue)] // highest possible value
[InlineData(-1)] // Just below the allowed range.
[InlineData(101)] // Just above the allowed range.
[InlineData(int.MinValue)] // Lowest possible value.
[InlineData(int.MaxValue)] // Highest possible value.
public async Task UpdateLibrary_WhenThresholdIsOutsideAllowedRange_ShouldRejectTheRequestAndKeepTheStoredSettings(int completionThresholdPercentage)
{
// Arrange
@@ -136,7 +136,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
await SeedLibraryAsync(libraryId, userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Test Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -177,7 +176,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
await SeedLibraryAsync(libraryId, userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Test Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -223,7 +221,6 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
(Guid _, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: ownerId,
title: "Test Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -275,6 +272,129 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
await _apiFactory.RemoveTestUserAsync(ownerUsername);
}
[Fact]
public async Task UpdateLibrary_WhenNonOwnerHoldsTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary()
{
// Arrange
// Ownership and the manage permission are both required, so a user that holds the permission must not update a library it does not own.
HttpClient client = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, ownerId, title: "Original Title");
(Guid _, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserWithPermissionAsync(client, AuthorizationPermission.CanCreateLibraries);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.Equal("Original Title", storedLibrary!.Title);
}
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveTestUserAsync(attackerUsername);
}
[Fact]
public async Task UpdateLibrary_WhenTheOwnerLacksTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary()
{
// Arrange
// The created user holds no permission, so it owns the library without being allowed to change it.
HttpClient client = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, ownerId, title: "Original Title");
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
title: "Updated Title",
libraryType: "Book",
contentLocations: ["C:/Media"],
coverImage: null
);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.Equal("Original Title", storedLibrary!.Title);
Assert.Equal(LibraryType.EBook, storedLibrary.LibraryType);
}
await _apiFactory.RemoveTestUserAsync(ownerUsername);
}
[Fact]
public async Task UpdateLibrary_WhenBodyNamesAnotherOwner_ShouldKeepTheStoredOwner()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, ownerId);
HttpClient client = _apiFactory.CreateClient();
Guid adminId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
title: "Test Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true
);
// The request has no owner, so the claimed owner is added to the raw body, the way a crafted request would carry it.
JsonObject body = JsonSerializer.SerializeToNode(request, new JsonSerializerOptions(JsonSerializerDefaults.Web))!.AsObject();
body["userId"] = adminId.ToString();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", body);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.Equal(ownerId, storedLibrary!.UserId);
}
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveAdminUserAsync(adminId);
}
/// <summary>
/// Asserts that <paramref name="response"/> carries the standard validation problem of the update library route.
/// </summary>
@@ -0,0 +1,114 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders;
/// <summary>
/// Contains security tests for the <see cref="GetLibraryTypeArtworkProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeArtworkProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryTypeArtworkProvidersEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetLibraryTypeArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryType = "Music";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/artwork-providers/{libraryType}");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/artwork-providers/{libraryType}", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Libraries--")] // Destructive SQL injection.
[InlineData("Music; rm -rf /")] // Command injection.
[InlineData("$(whoami)")] // Command substitution injection.
[InlineData("`whoami`")] // Backtick command injection.
[InlineData("{0}{1}{0}")] // Template/placeholder injection.
[InlineData("..\\..\\..\\Windows\\System32\\config\\SAM")] // Windows path traversal.
[InlineData("%2e%2e%2fetc%2fpasswd")] // Encoded path traversal.
public async Task GetLibraryTypeArtworkProviders_WithInjectionInLibraryType_ShouldNotLeakOrError(string maliciousLibraryType)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/artwork-providers/{Uri.EscapeDataString(maliciousLibraryType)}");
string content = await response.Content.ReadAsStringAsync();
// Assert
// An unrecognized library type fails the validation of the query, so it is reported as a validation problem, and the response
// must stay generic: the failed request leaks no database, filesystem or framework internals.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("UnknownLibraryType", errors!["General.Validation"]);
Assert.StartsWith("/api/v1/libraries/artwork-providers/", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
}
}
@@ -0,0 +1,114 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeBookReaders;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryTypeBookReaders;
/// <summary>
/// Contains security tests for the <see cref="GetLibraryTypeBookReadersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeBookReadersEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeBookReadersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryTypeBookReadersEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetLibraryTypeBookReaders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryType = "Music";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/book-readers/{libraryType}");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/book-readers/{libraryType}", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Libraries--")] // Destructive SQL injection.
[InlineData("Music; rm -rf /")] // Command injection.
[InlineData("$(whoami)")] // Command substitution injection.
[InlineData("`whoami`")] // Backtick command injection.
[InlineData("{0}{1}{0}")] // Template/placeholder injection.
[InlineData("..\\..\\..\\Windows\\System32\\config\\SAM")] // Windows path traversal.
[InlineData("%2e%2e%2fetc%2fpasswd")] // Encoded path traversal.
public async Task GetLibraryTypeBookReaders_WithInjectionInLibraryType_ShouldNotLeakOrError(string maliciousLibraryType)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/book-readers/{Uri.EscapeDataString(maliciousLibraryType)}");
string content = await response.Content.ReadAsStringAsync();
// Assert
// An unrecognized library type fails the validation of the query, so it is reported as a validation problem, and the response
// must stay generic: the failed request leaks no database, filesystem or framework internals.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("UnknownLibraryType", errors!["General.Validation"]);
Assert.StartsWith("/api/v1/libraries/book-readers/", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
}
}
@@ -0,0 +1,114 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders;
/// <summary>
/// Contains security tests for the <see cref="GetLibraryTypeMetadataProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeMetadataProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryTypeMetadataProvidersEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetLibraryTypeMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryType = "Music";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/metadata-providers/{libraryType}");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/metadata-providers/{libraryType}", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Libraries--")] // Destructive SQL injection.
[InlineData("Music; rm -rf /")] // Command injection.
[InlineData("$(whoami)")] // Command substitution injection.
[InlineData("`whoami`")] // Backtick command injection.
[InlineData("{0}{1}{0}")] // Template/placeholder injection.
[InlineData("..\\..\\..\\Windows\\System32\\config\\SAM")] // Windows path traversal.
[InlineData("%2e%2e%2fetc%2fpasswd")] // Encoded path traversal.
public async Task GetLibraryTypeMetadataProviders_WithInjectionInLibraryType_ShouldNotLeakOrError(string maliciousLibraryType)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/metadata-providers/{Uri.EscapeDataString(maliciousLibraryType)}");
string content = await response.Content.ReadAsStringAsync();
// Assert
// An unrecognized library type fails the validation of the query, so it is reported as a validation problem, and the response
// must stay generic: the failed request leaks no database, filesystem or framework internals.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("UnknownLibraryType", errors!["General.Validation"]);
Assert.StartsWith("/api/v1/libraries/metadata-providers/", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
}
}
@@ -1,133 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders;
/// <summary>
/// Contains security tests for the <see cref="ReorderLibraryArtworkProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryArtworkProvidersEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryArtworkProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ReorderLibraryArtworkProvidersEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task ReorderLibraryArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryId = Guid.NewGuid().ToString();
ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(
libraryId: Guid.NewGuid(),
pluginIds: [Guid.NewGuid()]
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // basic SQL injection
[InlineData("'; DROP TABLE Plugins--")] // destructive injection
public async Task ReorderLibraryArtworkProviders_WithSQLInjectionInPluginIds_ShouldNotLeakOrError(string maliciousPluginId)
{
// Arrange
// authenticate with an admin user and seed a library with artwork provider configurations, so valid ids would reach the handler
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
Guid libraryId = await SeedLibraryAsync(userId);
await SeedConfigurationAsync(libraryId, rank: 1);
await SeedConfigurationAsync(libraryId, rank: 2);
// Act
// the malicious value cannot bind to the Guid-typed PluginIds request property, so the body fails JSON deserialization
// before it ever reaches the endpoint handler
HttpResponseMessage response = await client.PutAsJsonAsync(
$"/api/v1/libraries/{libraryId}/artwork-providers/reorder",
new { libraryId, pluginIds = new[] { maliciousPluginId } });
// Assert
// note: observed status is 500 because the JSON body cannot be deserialized into the Guid-typed PluginIds property, and
// FastEndpoints, combined with DontCatchExceptions(), turns the resulting JsonException into a 500 response instead of 400
// (pre-existing production bug, not fixed here)
// 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("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a <see cref="Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a <see cref="LibraryArtworkProviderConfigurationEntity"/> for the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library.</param>
/// <param name="rank">The rank of the provider.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedConfigurationAsync(Guid libraryId, int rank)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: rank));
await dbContext.SaveChangesAsync();
}
}
@@ -1,133 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders;
/// <summary>
/// Contains security tests for the <see cref="ReorderLibraryMetadataProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryMetadataProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ReorderLibraryMetadataProvidersEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task ReorderLibraryMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryId = Guid.NewGuid().ToString();
ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(
libraryId: Guid.NewGuid(),
pluginIds: [Guid.NewGuid()]
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/reorder", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/metadata-providers/reorder", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // basic SQL injection
[InlineData("'; DROP TABLE Plugins--")] // destructive injection
public async Task ReorderLibraryMetadataProviders_WithSQLInjectionInPluginIds_ShouldNotLeakOrError(string maliciousPluginId)
{
// Arrange
// authenticate with an admin user and seed a library with metadata provider configurations, so valid ids would reach the handler
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
Guid libraryId = await SeedLibraryAsync(userId);
await SeedConfigurationAsync(libraryId, rank: 1);
await SeedConfigurationAsync(libraryId, rank: 2);
// Act
// the malicious value cannot bind to the Guid-typed PluginIds request property, so the body fails JSON deserialization
// before it ever reaches the endpoint handler
HttpResponseMessage response = await client.PutAsJsonAsync(
$"/api/v1/libraries/{libraryId}/metadata-providers/reorder",
new { libraryId = libraryId, pluginIds = new[] { maliciousPluginId } });
// Assert
// note: observed status is 500 because the JSON body cannot be deserialized into the Guid-typed PluginIds property, and
// FastEndpoints, combined with DontCatchExceptions(), turns the resulting JsonException into a 500 response instead of 400
// (pre-existing production bug, not fixed here)
// 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("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a <see cref="LibraryMetadataProviderConfigurationEntity"/> for the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library.</param>
/// <param name="rank">The rank of the provider.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedConfigurationAsync(Guid libraryId, int rank)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: rank));
await dbContext.SaveChangesAsync();
}
}
@@ -1,126 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled;
/// <summary>
/// Contains security tests for the <see cref="SetLibraryArtworkProviderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryArtworkProviderEnabledEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryArtworkProviderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public SetLibraryArtworkProviderEnabledEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task SetLibraryArtworkProviderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryId = Guid.NewGuid().ToString();
string pluginId = Guid.NewGuid().ToString();
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create();
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // basic SQL injection
[InlineData("'; DROP TABLE Libraries--")] // destructive injection
public async Task SetLibraryArtworkProviderEnabled_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId)
{
// Arrange
// authenticate with an admin user and seed a library with an artwork provider configuration, so valid ids would reach the handler
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
Guid libraryId = await SeedLibraryAsync(userId);
await SeedConfigurationAsync(libraryId);
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), isEnabled: true);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/artwork-providers/{Guid.NewGuid()}/enabled", request);
// Assert
// note: the {libraryId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler
// 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
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a <see cref="Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a <see cref="LibraryArtworkProviderConfigurationEntity"/> for the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedConfigurationAsync(Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1, isEnabled: false));
await dbContext.SaveChangesAsync();
}
}
@@ -1,77 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled;
/// <summary>
/// Contains security tests for the <see cref="SetLibraryBookReaderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryBookReaderEnabledEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryBookReaderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public SetLibraryBookReaderEnabledEndpointTests(LuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
}
[Fact]
public async Task SetLibraryBookReaderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
}
[Theory]
[InlineData("' OR '1'='1")] // basic SQL injection
[InlineData("'; DROP TABLE LibraryBookReaderConfigurations--")] // destructive injection
public async Task SetLibraryBookReaderEnabled_WithSQLInjectionInPluginId_ShouldNotLeakDatabaseDetails(string maliciousPluginId)
{
// Arrange
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: Guid.NewGuid(), pluginId: Guid.NewGuid(), isEnabled: true);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/book-readers/{Uri.EscapeDataString(maliciousPluginId)}/enabled", request);
string content = await response.Content.ReadAsStringAsync();
// Assert
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,126 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled;
/// <summary>
/// Contains security tests for the <see cref="SetLibraryMetadataProviderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryMetadataProviderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public SetLibraryMetadataProviderEnabledEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task SetLibraryMetadataProviderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryId = Guid.NewGuid().ToString();
string pluginId = Guid.NewGuid().ToString();
SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create();
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // basic SQL injection
[InlineData("'; DROP TABLE Libraries--")] // destructive injection
public async Task SetLibraryMetadataProviderEnabled_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId)
{
// Arrange
// authenticate with an admin user and seed a library with a metadata provider configuration, so valid ids would reach the handler
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
Guid libraryId = await SeedLibraryAsync(userId);
await SeedConfigurationAsync(libraryId);
SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), isEnabled: true);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/metadata-providers/{Guid.NewGuid()}/enabled", request);
// Assert
// note: the {libraryId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler
// 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
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a <see cref="LibraryMetadataProviderConfigurationEntity"/> for the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedConfigurationAsync(Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1, isEnabled: false));
await dbContext.SaveChangesAsync();
}
}