mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 18:13:42 +00:00
Hardens test assertions and adds missing test coverage.
This commit is contained in:
1 parent
6b86fd5805
commit
1189bbaf36
489 files changed
+39982
-512
No files matched your search
+143
@@ -0,0 +1,143 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.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.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
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.Plugins.GetLibraryMetadataProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/libraries/{libraryId}/metadata-providers</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryMetadataProvidersEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryMetadataProvidersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetLibraryMetadataProvidersEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/metadata-providers");
|
||||
|
||||
// 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", 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 GetLibraryMetadataProviders_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
// authenticate with an admin user and seed a library with a metadata provider configuration, so a valid id would reach the handler
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
await SeedConfigurationAsync(libraryId, userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/metadata-providers");
|
||||
|
||||
// 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("SQL", 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(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
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="userId">The Id of the user that owns the data.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedConfigurationAsync(Guid libraryId, Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
PluginId = Guid.NewGuid(),
|
||||
IsEnabled = true,
|
||||
Rank = 1,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
|
||||
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.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetPluginSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/plugins/{pluginId}/settings</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPluginSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPluginSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetPluginSettingsEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPluginSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string pluginId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/plugins/{pluginId}/settings");
|
||||
|
||||
// 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/plugins/{pluginId}/settings", 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 GetPluginSettings_WithSQLInjectionInPluginId_ShouldNotLeakOrError(string maliciousPluginId)
|
||||
{
|
||||
// Arrange
|
||||
// authenticate with an admin user and seed a plugin, so a valid pluginId would reach the handler
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
await SeedPluginAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/plugins/{Uri.EscapeDataString(maliciousPluginId)}/settings");
|
||||
|
||||
// Assert
|
||||
// note: the {pluginId} 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("SQL", 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="PluginEntity"/> created by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the creator.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedPluginAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Plugins.Add(new PluginEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Test Plugin",
|
||||
Author = "Test Author",
|
||||
Version = "1.0.0",
|
||||
Description = "A test plugin.",
|
||||
LoadStatus = PluginLoadStatus.Loaded,
|
||||
LoadError = null,
|
||||
SettingsJson = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
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.Plugins.GetPlugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/plugins</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPluginsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPluginsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetPluginsEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlugins_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/plugins");
|
||||
|
||||
// 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/plugins", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.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.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
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.Plugins.ReorderLibraryMetadataProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/libraries/{libraryId}/metadata-providers/reorder</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <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 = new(
|
||||
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, userId, rank: 1);
|
||||
await SeedConfigurationAsync(libraryId, userId, 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("SQL", 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(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
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="userId">The Id of the user that owns the data.</param>
|
||||
/// <param name="rank">The rank of the provider.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedConfigurationAsync(Guid libraryId, Guid userId, int rank)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
PluginId = Guid.NewGuid(),
|
||||
IsEnabled = true,
|
||||
Rank = rank,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.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.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
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.Plugins.SetLibraryMetadataProviderEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/libraries/{libraryId}/metadata-providers/{pluginId}/enabled</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <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 = new(
|
||||
LibraryId: Guid.NewGuid(),
|
||||
PluginId: Guid.NewGuid(),
|
||||
IsEnabled: true
|
||||
);
|
||||
|
||||
// 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, userId);
|
||||
SetLibraryMetadataProviderEnabledRequest request = new(
|
||||
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("SQL", 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(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
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="userId">The Id of the user that owns the data.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedConfigurationAsync(Guid libraryId, Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
PluginId = Guid.NewGuid(),
|
||||
IsEnabled = false,
|
||||
Rank = 1,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Contracts.Requests.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
|
||||
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.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.Plugins.UpdatePluginSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/plugins/{pluginId}/settings</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdatePluginSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdatePluginSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdatePluginSettingsEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePluginSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string pluginId = Guid.NewGuid().ToString();
|
||||
UpdatePluginSettingsRequest request = new(
|
||||
PluginId: Guid.NewGuid(),
|
||||
Settings: new Dictionary<string, string> { ["Key"] = "Value" }
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/plugins/{pluginId}/settings", 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/plugins/{pluginId}/settings", 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 UpdatePluginSettings_WithSQLInjectionInSettings_ShouldNotLeakOrError(string maliciousValue)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
Guid pluginId = await SeedPluginAsync(userId);
|
||||
UpdatePluginSettingsRequest request = new(
|
||||
PluginId: pluginId,
|
||||
Settings: new Dictionary<string, string> { ["Key"] = maliciousValue }
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/plugins/{pluginId}/settings", request);
|
||||
|
||||
// Assert
|
||||
// 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("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
PluginEntity? storedPlugin = await dbContext.Plugins.FirstOrDefaultAsync(plugin => plugin.Id == pluginId);
|
||||
Assert.NotNull(storedPlugin);
|
||||
Assert.NotNull(storedPlugin!.SettingsJson);
|
||||
Dictionary<string, string>? storedSettings = JsonSerializer.Deserialize<Dictionary<string, string>>(storedPlugin.SettingsJson!);
|
||||
Assert.NotNull(storedSettings);
|
||||
Assert.Equal(maliciousValue, storedSettings!["Key"]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="PluginEntity"/> created by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the creator.</param>
|
||||
/// <returns>The Id of the seeded plugin.</returns>
|
||||
private async Task<Guid> SeedPluginAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
dbContext.Plugins.Add(new PluginEntity
|
||||
{
|
||||
Id = pluginId,
|
||||
Name = "Test Plugin",
|
||||
Author = "Test Author",
|
||||
Version = "1.0.0",
|
||||
Description = "A test plugin.",
|
||||
LoadStatus = PluginLoadStatus.Loaded,
|
||||
LoadError = null,
|
||||
SettingsJson = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
return pluginId;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user