mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 00:11:10 +00:00
Adds plugin upload from the web client
This commit is contained in:
1 parent
d84823f6d2
commit
b3ffb5dfab
57 files changed
+2774
-16
No files matched your search
+44
@@ -0,0 +1,44 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Core.Plugins.Commands.InstallPlugin;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Core.Plugins.Commands.InstallPlugin;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="InstallPluginCommand"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class InstallPluginCommandFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a valid <see cref="InstallPluginCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="archive">Optional. The archive stream of the uploaded plugin.</param>
|
||||
/// <param name="fileName">Optional. The file name of the uploaded plugin.</param>
|
||||
/// <returns>The created <see cref="InstallPluginCommand"/>.</returns>
|
||||
public InstallPluginCommand Create(
|
||||
Stream? archive = null,
|
||||
string? fileName = null)
|
||||
{
|
||||
return new InstallPluginCommand(
|
||||
archive ?? new MemoryStream(_faker.Random.Bytes(64)),
|
||||
fileName ?? $"{_faker.Hacker.Noun()}.dll");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="InstallPluginCommand"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="InstallPluginCommand"/> instances.</returns>
|
||||
public List<InstallPluginCommand> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Fixtures.Core.Endpoints.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for building plugin archives used by the plugin integration tests.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TestPluginArchiveFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Builds a ZIP archive in memory containing a single plugin assembly entry.
|
||||
/// </summary>
|
||||
/// <param name="dllName">Optional name of the plugin assembly entry; a unique name is generated when not supplied.</param>
|
||||
/// <returns>The bytes of the plugin ZIP archive.</returns>
|
||||
public byte[] CreateZip(string? dllName = null)
|
||||
{
|
||||
string resolvedDllName = dllName ?? $"test-plugin-{Guid.NewGuid():N}.dll";
|
||||
|
||||
using MemoryStream stream = new();
|
||||
using (ZipArchive archive = new(stream, ZipArchiveMode.Create, leaveOpen: true))
|
||||
{
|
||||
ZipArchiveEntry dllEntry = archive.CreateEntry(resolvedDllName);
|
||||
using Stream entryStream = dllEntry.Open();
|
||||
entryStream.Write(CreateAssemblyBytes());
|
||||
}
|
||||
|
||||
return stream.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a single plugin assembly file in memory.
|
||||
/// </summary>
|
||||
/// <returns>The bytes of the plugin assembly.</returns>
|
||||
public byte[] CreateDll()
|
||||
{
|
||||
return CreateAssemblyBytes();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the arbitrary bytes of a plugin assembly file.
|
||||
/// </summary>
|
||||
/// <returns>The plugin assembly bytes.</returns>
|
||||
private static byte[] CreateAssemblyBytes()
|
||||
{
|
||||
return [0x4D, 0x5A, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00];
|
||||
}
|
||||
}
|
||||
@@ -127,6 +127,16 @@ public class StubApiHttpClient : IApiHttpClient
|
||||
_getResponseFactories[endpoint] = () => throw exception;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the exception thrown when the specified PUT endpoint is called.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint for which to register the exception.</param>
|
||||
/// <param name="exception">The exception to throw.</param>
|
||||
public void RegisterPutException(string endpoint, ApiException exception)
|
||||
{
|
||||
_putResponseFactories[endpoint] = _ => throw exception;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the response returned when the specified PUT endpoint is called.
|
||||
/// </summary>
|
||||
@@ -138,6 +148,16 @@ public class StubApiHttpClient : IApiHttpClient
|
||||
_putResponseFactories[endpoint] = _ => response;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the response factory invoked when the specified PUT endpoint is called.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The API endpoint for which to register the response factory.</param>
|
||||
/// <param name="responseFactory">The factory that produces the response from the request payload.</param>
|
||||
public void RegisterPutResponseFactory(string endpoint, Func<object, object> responseFactory)
|
||||
{
|
||||
_putResponseFactories[endpoint] = responseFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the specified DELETE endpoint as succeeding.
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Common.Enums.Plugins;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for generating <see cref="PluginDto"/> test data.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PluginDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="PluginDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional identifier of the plugin.</param>
|
||||
/// <param name="name">Optional name of the plugin.</param>
|
||||
/// <param name="author">Optional author of the plugin.</param>
|
||||
/// <param name="version">Optional version of the plugin.</param>
|
||||
/// <param name="loadStatus">Optional load status of the plugin.</param>
|
||||
/// <returns>A configured <see cref="PluginDto"/> instance.</returns>
|
||||
public PluginDto Create(Guid? id = null, string? name = null, string? author = null, string? version = null, PluginLoadStatus? loadStatus = null)
|
||||
{
|
||||
return new PluginDto
|
||||
{
|
||||
Id = id ?? Guid.NewGuid(),
|
||||
Name = name ?? _faker.Hacker.Noun(),
|
||||
Author = author ?? _faker.Name.FullName(),
|
||||
Version = version ?? _faker.System.Semver(),
|
||||
Description = _faker.Lorem.Sentence(),
|
||||
LoadStatus = loadStatus ?? PluginLoadStatus.Loaded,
|
||||
LoadError = null,
|
||||
Settings = null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="PluginDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="PluginDto"/> instances.</returns>
|
||||
public List<PluginDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+288
@@ -0,0 +1,288 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Plugins.InstallPlugin;
|
||||
using Lumina.Presentation.Api.Fixtures.Core.Endpoints.Plugins;
|
||||
using Lumina.Presentation.Api.IntegrationTests.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.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.InstallPlugin;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="InstallPluginEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class InstallPluginEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly TestPluginArchiveFixture _pluginArchiveFixture = new();
|
||||
private readonly List<string> _installedPluginFileNames = [];
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InstallPluginEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public InstallPluginEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes an authenticated admin API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPlugin_WhenCalledWithValidZipArchive_ShouldInstallPlugin()
|
||||
{
|
||||
// Arrange
|
||||
string dllName = $"test-plugin-{Guid.NewGuid():N}.dll";
|
||||
byte[] archiveBytes = _pluginArchiveFixture.CreateZip(dllName);
|
||||
using MultipartFormDataContent multipartContent = [];
|
||||
using ByteArrayContent fileContent = new(archiveBytes);
|
||||
multipartContent.Add(fileContent, "archive", "plugin.zip");
|
||||
_installedPluginFileNames.Add(dllName);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync("/api/v1/plugins", multipartContent);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.True(File.Exists(Path.Combine(AppContext.BaseDirectory, "plugins", dllName)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPlugin_WhenCalledWithSingleDll_ShouldInstallPlugin()
|
||||
{
|
||||
// Arrange
|
||||
string dllName = $"test-plugin-{Guid.NewGuid():N}.dll";
|
||||
using MultipartFormDataContent multipartContent = [];
|
||||
using ByteArrayContent fileContent = new(_pluginArchiveFixture.CreateDll());
|
||||
multipartContent.Add(fileContent, "archive", dllName);
|
||||
_installedPluginFileNames.Add(dllName);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync("/api/v1/plugins", multipartContent);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.True(File.Exists(Path.Combine(AppContext.BaseDirectory, "plugins", dllName)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPlugin_WhenCalledWithInvalidArchive_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
byte[] invalidArchive = Encoding.UTF8.GetBytes("this is not a valid zip archive");
|
||||
using MultipartFormDataContent multipartContent = [];
|
||||
using ByteArrayContent fileContent = new(invalidArchive);
|
||||
multipartContent.Add(fileContent, "archive", "plugin.zip");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync("/api/v1/plugins", multipartContent);
|
||||
|
||||
// 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("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Failure", problemDetails["title"].GetString());
|
||||
Assert.Equal("PluginArchiveNotReadable", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/plugins", problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPlugin_WhenCalledWithZipWithoutAssemblies_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
using MultipartFormDataContent multipartContent = [];
|
||||
using ByteArrayContent fileContent = new(CreateZipWithEntry("readme.txt", "not an assembly"));
|
||||
multipartContent.Add(fileContent, "archive", "plugin.zip");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync("/api/v1/plugins", multipartContent);
|
||||
|
||||
// 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("General.Failure", problemDetails["title"].GetString());
|
||||
Assert.Equal("PluginArchiveContainsNoAssemblies", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPlugin_WhenCalledWithUnsupportedFileType_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
using MultipartFormDataContent multipartContent = [];
|
||||
using ByteArrayContent fileContent = new(_pluginArchiveFixture.CreateDll());
|
||||
multipartContent.Add(fileContent, "archive", "plugin.txt");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync("/api/v1/plugins", multipartContent);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
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("General.Validation", errors.Keys);
|
||||
Assert.Contains("UnsupportedPluginFileType", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPlugin_WhenCalledWithoutArchive_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
// a multipart form without any file part, only a regular form field, so the archive is missing
|
||||
using MultipartFormDataContent multipartContent = [];
|
||||
multipartContent.Add(new StringContent("value"), "field");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync("/api/v1/plugins", multipartContent);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
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("General.Validation", errors.Keys);
|
||||
Assert.Contains("PluginArchiveCannotBeNull", errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPlugin_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient nonAdminClient = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
byte[] archiveBytes = _pluginArchiveFixture.CreateZip();
|
||||
using MultipartFormDataContent multipartContent = [];
|
||||
using ByteArrayContent fileContent = new(archiveBytes);
|
||||
multipartContent.Add(fileContent, "archive", "plugin.zip");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await nonAdminClient.PostAsync("/api/v1/plugins", multipartContent);
|
||||
|
||||
// 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("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPlugin_WhenCalledWithoutAuthentication_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient anonymousClient = _apiFactory.CreateClient();
|
||||
byte[] archiveBytes = _pluginArchiveFixture.CreateZip();
|
||||
using MultipartFormDataContent multipartContent = [];
|
||||
using ByteArrayContent fileContent = new(archiveBytes);
|
||||
multipartContent.Add(fileContent, "archive", "plugin.zip");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.PostAsync("/api/v1/plugins", multipartContent);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds an in-memory ZIP archive containing the provided entry.
|
||||
/// </summary>
|
||||
/// <param name="entryName">The name of the archive entry.</param>
|
||||
/// <param name="content">The content of the archive entry.</param>
|
||||
/// <returns>The ZIP archive bytes.</returns>
|
||||
private static byte[] CreateZipWithEntry(string entryName, string content)
|
||||
{
|
||||
using MemoryStream memoryStream = new();
|
||||
using (System.IO.Compression.ZipArchive zipArchive = new(memoryStream, System.IO.Compression.ZipArchiveMode.Create, leaveOpen: true))
|
||||
{
|
||||
System.IO.Compression.ZipArchiveEntry entry = zipArchive.CreateEntry(entryName);
|
||||
using StreamWriter writer = new(entry.Open());
|
||||
writer.Write(content);
|
||||
}
|
||||
|
||||
return memoryStream.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources, removing the installed test plugins and the authorization seed data of the admin test user.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
foreach (string fileName in _installedPluginFileNames)
|
||||
{
|
||||
string pluginPath = Path.Combine(AppContext.BaseDirectory, "plugins", fileName);
|
||||
if (File.Exists(pluginPath))
|
||||
File.Delete(pluginPath);
|
||||
}
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// the admin seeding performed by the factory is not idempotent, so the seed data must be cleared between tests
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPlugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Plugins.GetPlugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <c>/{culture}/admin/manage-plugins/api-get-plugins</c> route served by the <see cref="GetPluginsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPluginsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PluginDtoFixture _pluginDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPluginsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetPluginsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlugins_WhenCalledByAuthenticatedAdmin_ShouldReturnPluginsFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
PluginDto[] expectedPlugins = [_pluginDtoFixture.Create(name: "OpenLibrary")];
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("plugins", expectedPlugins);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/manage-plugins/api-get-plugins");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Equal(expectedPlugins.Length, json.RootElement.GetProperty("data").GetArrayLength());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "plugins");
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Plugins.InstallPlugin;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Plugins.InstallPlugin;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <c>/{culture}/admin/manage-plugins/api-install-plugin</c> route served by the <see cref="InstallPluginEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class InstallPluginEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PluginDtoFixture _pluginDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InstallPluginEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public InstallPluginEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPlugin_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldForwardUploadAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string fileName = "plugin.zip";
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse("plugins", _pluginDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage installRequest = new(HttpMethod.Post, "/en-us/admin/manage-plugins/api-install-plugin")
|
||||
{
|
||||
Content = CreateMultipartContent(fileName)
|
||||
};
|
||||
installRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
installRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(installRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "plugins" && postRequest.Data as string == fileName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPlugin_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage installRequest = new(HttpMethod.Post, "/en-us/admin/manage-plugins/api-install-plugin")
|
||||
{
|
||||
Content = CreateMultipartContent("plugin.zip")
|
||||
};
|
||||
installRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(installRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "plugins");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a multipart form content carrying a single file part.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
/// <returns>The multipart form content.</returns>
|
||||
private static MultipartFormDataContent CreateMultipartContent(string fileName)
|
||||
{
|
||||
MultipartFormDataContent form = [];
|
||||
ByteArrayContent fileContent = new([0x4D, 0x5A, 0x90, 0x00]);
|
||||
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
||||
form.Add(fileContent, "archive", fileName);
|
||||
return form;
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Requests.Plugins;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Plugins.UpdatePluginSettings;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Plugins.UpdatePluginSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <c>/{culture}/admin/manage-plugins/api-update-plugin-settings</c> route served by the <see cref="UpdatePluginSettingsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdatePluginSettingsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdatePluginSettingsRequestFixture _updatePluginSettingsRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdatePluginSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public UpdatePluginSettingsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePluginSettings_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldForwardUpdateAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create();
|
||||
string expectedEndpoint = $"plugins/{request.PluginId}/settings";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/manage-plugins/api-update-plugin-settings")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePluginSettings_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/manage-plugins/api-update-plugin-settings")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"plugins/{request.PluginId}/settings");
|
||||
}
|
||||
}
|
||||
+254
@@ -0,0 +1,254 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.InstallPlugin;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>POST /api/v1/plugins</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class InstallPluginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly List<string> _installedPluginFileNames = [];
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InstallPluginEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public InstallPluginEndpointTests(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 InstallPlugin_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync("/api/v1/plugins", new ByteArrayContent([]));
|
||||
|
||||
// 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());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPlugin_WhenAuthenticatedNonAdmin_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
using MultipartFormDataContent form = CreateMultipartForm(CreateZipWithAssembly(), "plugin.zip");
|
||||
HttpResponseMessage response = await client.PostAsync("/api/v1/plugins", form);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPlugin_WithNonZipBody_ShouldReturnCleanProblemDetails()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
|
||||
// Act
|
||||
using MultipartFormDataContent form = CreateMultipartForm(Encoding.UTF8.GetBytes("this is not a zip archive"), "plugin.zip");
|
||||
HttpResponseMessage response = await client.PostAsync("/api/v1/plugins", form);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Failure", problemDetails["title"].GetString());
|
||||
Assert.Equal("PluginArchiveNotReadable", problemDetails["detail"].GetString());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPlugin_WithZipContainingTraversalEntry_ShouldNotEscapePluginsDirectory()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
byte[] zipBytes = CreateZipWithEntries(new Dictionary<string, string>
|
||||
{
|
||||
[@"..\evil.dll"] = "evil" // path traversal entry inside the archive
|
||||
});
|
||||
_installedPluginFileNames.Add("evil.dll");
|
||||
|
||||
// Act
|
||||
using MultipartFormDataContent form = CreateMultipartForm(zipBytes, "plugin.zip");
|
||||
HttpResponseMessage response = await client.PostAsync("/api/v1/plugins", form);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
// the entry is flattened, so it cannot escape the plugins directory
|
||||
Assert.False(File.Exists(Path.Combine(AppContext.BaseDirectory, "evil.dll")));
|
||||
Assert.True(File.Exists(Path.Combine(AppContext.BaseDirectory, "plugins", "evil.dll")));
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPlugin_WithUnsupportedFileType_ShouldReturnCleanProblemDetails()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
|
||||
// Act
|
||||
using MultipartFormDataContent form = CreateMultipartForm([0x4D, 0x5A, 0x90, 0x00], "plugin.exe");
|
||||
HttpResponseMessage response = await client.PostAsync("/api/v1/plugins", form);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
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("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPlugin_WithEmptyMultipartBody_ShouldReturnCleanValidationProblemDetails()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
using MultipartFormDataContent emptyForm = [];
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsync("/api/v1/plugins", emptyForm);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
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("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a multipart form containing a single file part.
|
||||
/// </summary>
|
||||
/// <param name="fileBytes">The file content bytes.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
/// <returns>The multipart form content.</returns>
|
||||
private static MultipartFormDataContent CreateMultipartForm(byte[] fileBytes, string fileName)
|
||||
{
|
||||
MultipartFormDataContent form = [];
|
||||
ByteArrayContent fileContent = new(fileBytes);
|
||||
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
||||
form.Add(fileContent, "archive", fileName);
|
||||
return form;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds an in-memory ZIP archive containing a single plugin assembly entry.
|
||||
/// </summary>
|
||||
/// <returns>The ZIP archive bytes.</returns>
|
||||
private static byte[] CreateZipWithAssembly()
|
||||
{
|
||||
return CreateZipWithEntries(new Dictionary<string, string>
|
||||
{
|
||||
["test-plugin.dll"] = "not a real assembly, but the installer only checks the file extension"
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds an in-memory ZIP archive from the given entry paths and contents.
|
||||
/// </summary>
|
||||
/// <param name="entries">The entry paths mapped to their contents.</param>
|
||||
/// <returns>The ZIP archive bytes.</returns>
|
||||
private static byte[] CreateZipWithEntries(IReadOnlyDictionary<string, string> entries)
|
||||
{
|
||||
using MemoryStream memoryStream = new();
|
||||
using (ZipArchive zipArchive = new(memoryStream, ZipArchiveMode.Create, leaveOpen: true))
|
||||
{
|
||||
foreach ((string path, string content) in entries)
|
||||
{
|
||||
ZipArchiveEntry entry = zipArchive.CreateEntry(path);
|
||||
using StreamWriter writer = new(entry.Open());
|
||||
writer.Write(content);
|
||||
}
|
||||
}
|
||||
|
||||
return memoryStream.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the API factory resources and removes the plugin files written by the tests.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (string fileName in _installedPluginFileNames)
|
||||
{
|
||||
string pluginPath = Path.Combine(AppContext.BaseDirectory, "plugins", fileName);
|
||||
if (File.Exists(pluginPath))
|
||||
File.Delete(pluginPath);
|
||||
}
|
||||
|
||||
_client.Dispose();
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPlugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.GetPlugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/{culture}/admin/manage-plugins/api-get-plugins</c> route served by the <see cref="GetPluginsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPluginsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPluginsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetPluginsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlugins_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/manage-plugins/api-get-plugins");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "plugins");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlugins_WhenApiReturnsError_ShouldReturnCleanError()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterGetException("plugins", new ApiException(
|
||||
new ProblemDetailsDto { Title = "General.Failure", Detail = "PluginNotFound" },
|
||||
HttpStatusCode.NotFound));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/manage-plugins/api-get-plugins");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(response.IsSuccessStatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Plugins.InstallPlugin;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.InstallPlugin;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/{culture}/admin/manage-plugins/api-install-plugin</c> route served by the <see cref="InstallPluginEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class InstallPluginEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InstallPluginEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public InstallPluginEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPlugin_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage installRequest = new(HttpMethod.Post, "/en-us/admin/manage-plugins/api-install-plugin")
|
||||
{
|
||||
Content = CreateMultipartContent("plugin.zip")
|
||||
};
|
||||
installRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(installRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "plugins");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPlugin_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage installRequest = new(HttpMethod.Post, "/en-us/admin/manage-plugins/api-install-plugin")
|
||||
{
|
||||
Content = CreateMultipartContent("plugin.zip")
|
||||
};
|
||||
installRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(installRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "plugins");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPlugin_WhenCalledWithoutFilePart_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage installRequest = new(HttpMethod.Post, "/en-us/admin/manage-plugins/api-install-plugin")
|
||||
{
|
||||
Content = CreateEmptyMultipartContent()
|
||||
};
|
||||
installRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
installRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(installRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "plugins");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPlugin_WhenApiRejectsUpload_ShouldReturnCleanError()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPostException("plugins", new ApiException(
|
||||
new ProblemDetailsDto { Title = "General.Failure", Detail = "PluginArchiveNotReadable" },
|
||||
HttpStatusCode.Forbidden));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage installRequest = new(HttpMethod.Post, "/en-us/admin/manage-plugins/api-install-plugin")
|
||||
{
|
||||
Content = CreateMultipartContent("plugin.zip")
|
||||
};
|
||||
installRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
installRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(installRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a multipart form content carrying a single file part.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
/// <returns>The multipart form content.</returns>
|
||||
private static MultipartFormDataContent CreateMultipartContent(string fileName)
|
||||
{
|
||||
MultipartFormDataContent form = [];
|
||||
ByteArrayContent fileContent = new([0x4D, 0x5A, 0x90, 0x00]);
|
||||
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
|
||||
form.Add(fileContent, "archive", fileName);
|
||||
return form;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a multipart form content without any file part.
|
||||
/// </summary>
|
||||
/// <returns>The multipart form content.</returns>
|
||||
private static MultipartFormDataContent CreateEmptyMultipartContent()
|
||||
{
|
||||
MultipartFormDataContent form = [];
|
||||
form.Add(new StringContent("value"), "field");
|
||||
return form;
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Plugins;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Plugins.UpdatePluginSettings;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.UpdatePluginSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/{culture}/admin/manage-plugins/api-update-plugin-settings</c> route served by the <see cref="UpdatePluginSettingsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdatePluginSettingsEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdatePluginSettingsRequestFixture _updatePluginSettingsRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdatePluginSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public UpdatePluginSettingsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePluginSettings_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/manage-plugins/api-update-plugin-settings")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"plugins/{request.PluginId}/settings");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePluginSettings_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create();
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/manage-plugins/api-update-plugin-settings")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(updateRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"plugins/{request.PluginId}/settings");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePluginSettings_WhenApiRejectsUpdate_ShouldReturnCleanError()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create();
|
||||
string endpoint = $"plugins/{request.PluginId}/settings";
|
||||
_apiFactory.ApiClientStub.RegisterPutException(endpoint, new ApiException(
|
||||
new ProblemDetailsDto { Title = "General.Failure", Detail = "PluginNotFound" },
|
||||
HttpStatusCode.NotFound));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/manage-plugins/api-update-plugin-settings")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(response.IsSuccessStatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Plugins;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.Plugins.Commands.InstallPlugin;
|
||||
using Lumina.Application.Fixtures.Core.Plugins.Commands.InstallPlugin;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.InstallPlugin;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="InstallPluginCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class InstallPluginCommandHandlerTests
|
||||
{
|
||||
private readonly IPluginInstaller _mockPluginInstaller;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly IValidator<InstallPluginCommand> _mockValidator;
|
||||
private readonly InstallPluginCommandHandler _sut;
|
||||
private readonly InstallPluginCommandFixture _installPluginCommandFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InstallPluginCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public InstallPluginCommandHandlerTests()
|
||||
{
|
||||
_mockPluginInstaller = Substitute.For<IPluginInstaller>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockValidator = Substitute.For<IValidator<InstallPluginCommand>>();
|
||||
_mockValidator.Validate(Arg.Any<InstallPluginCommand>()).Returns([]);
|
||||
_mockCurrentUserService.UserId.Returns(Guid.NewGuid());
|
||||
_mockAuthorizationService.IsInRoleAsync(Arg.Any<Guid>(), "Admin", Arg.Any<CancellationToken>()).Returns(true);
|
||||
_sut = new InstallPluginCommandHandler(_mockPluginInstaller, _mockCurrentUserService, _mockAuthorizationService, _mockValidator);
|
||||
_installPluginCommandFixture = new InstallPluginCommandFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalled_ShouldInstallThePlugin()
|
||||
{
|
||||
// Arrange
|
||||
InstallPluginCommand command = _installPluginCommandFixture.Create();
|
||||
_mockPluginInstaller.InstallAsync(Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Success);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
await _mockPluginInstaller.Received(1).InstallAsync(command.Archive!, command.FileName!, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutInstalling()
|
||||
{
|
||||
// Arrange
|
||||
InstallPluginCommand command = _installPluginCommandFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<InstallPluginCommand>()).Returns([Errors.Plugins.PluginArchiveCannotBeNull]);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Plugins.PluginArchiveCannotBeNull, result.FirstError);
|
||||
await _mockPluginInstaller.DidNotReceiveWithAnyArgs().InstallAsync(default!, default!, default);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCurrentUserIsMissing_ShouldReturnNotAuthorizedWithoutInstalling()
|
||||
{
|
||||
// Arrange
|
||||
InstallPluginCommand command = _installPluginCommandFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockPluginInstaller.DidNotReceiveWithAnyArgs().InstallAsync(default!, default!, default);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedWithoutInstalling()
|
||||
{
|
||||
// Arrange
|
||||
InstallPluginCommand command = _installPluginCommandFixture.Create();
|
||||
_mockAuthorizationService.IsInRoleAsync(Arg.Any<Guid>(), "Admin", Arg.Any<CancellationToken>()).Returns(false);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockPluginInstaller.DidNotReceiveWithAnyArgs().InstallAsync(default!, default!, default);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenInstallationFails_ShouldReturnTheInstallationError()
|
||||
{
|
||||
// Arrange
|
||||
InstallPluginCommand command = _installPluginCommandFixture.Create();
|
||||
_mockPluginInstaller.InstallAsync(Arg.Any<System.IO.Stream>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Errors.Plugins.PluginArchiveNotReadable);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Plugins.PluginArchiveNotReadable, result.FirstError);
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Plugins.Commands.InstallPlugin;
|
||||
using Lumina.Application.Fixtures.Core.Plugins.Commands.InstallPlugin;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.InstallPlugin;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="InstallPluginCommandValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class InstallPluginCommandValidatorTests
|
||||
{
|
||||
private readonly InstallPluginCommandValidator _validator = new();
|
||||
private readonly InstallPluginCommandFixture _installPluginCommandFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenArchiveIsNull_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
InstallPluginCommand command = _installPluginCommandFixture.Create() with { Archive = null };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Plugins.PluginArchiveCannotBeNull);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenFileNameIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
InstallPluginCommand command = _installPluginCommandFixture.Create() with { FileName = string.Empty };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Plugins.PluginFileNameCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
InstallPluginCommand command = _installPluginCommandFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
|
||||
using Lumina.Application.Common.Infrastructure.Plugins;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Infrastructure.Core.Plugins;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PluginInstaller"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PluginInstallerTests : IDisposable
|
||||
{
|
||||
private readonly string _pluginsDirectory;
|
||||
private readonly PluginInstaller _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PluginInstallerTests"/> class.
|
||||
/// </summary>
|
||||
public PluginInstallerTests()
|
||||
{
|
||||
_pluginsDirectory = Path.Combine(AppContext.BaseDirectory, $".test-plugins-{Guid.NewGuid():N}");
|
||||
ILogger<PluginInstaller> mockLogger = Substitute.For<ILogger<PluginInstaller>>();
|
||||
IOptions<PluginsSettingsDto> mockOptions = Substitute.For<IOptions<PluginsSettingsDto>>();
|
||||
mockOptions.Value.Returns(new PluginsSettingsDto { Directory = Path.GetFileName(_pluginsDirectory) });
|
||||
_sut = new PluginInstaller(mockOptions, mockLogger);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallAsync_WhenUploadingSingleAssembly_ShouldCopyAssemblyToPluginsDirectory()
|
||||
{
|
||||
// Arrange
|
||||
string assemblyName = "Lumina.TestPlugin.dll";
|
||||
await using FileStream stream = File.OpenRead(Path.Combine(AppContext.BaseDirectory, assemblyName));
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.InstallAsync(stream, assemblyName, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.True(File.Exists(Path.Combine(_pluginsDirectory, assemblyName)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallAsync_WhenUploadingZipWithAssemblies_ShouldExtractAssembliesFlattenedToPluginsDirectory()
|
||||
{
|
||||
// Arrange
|
||||
await using MemoryStream zipStream = new();
|
||||
CreateZipArchive(zipStream, [("nested/plugin/Lumina.TestPlugin.dll", ReadTestAssembly()), ("readme.txt", Encoding.UTF8.GetBytes("not an assembly"))]);
|
||||
zipStream.Position = 0;
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.InstallAsync(zipStream, "plugin.zip", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.True(File.Exists(Path.Combine(_pluginsDirectory, "Lumina.TestPlugin.dll")));
|
||||
Assert.False(File.Exists(Path.Combine(_pluginsDirectory, "readme.txt")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallAsync_WhenUploadingUnsupportedFileType_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
await using MemoryStream stream = new([.. new byte[] { 1, 2, 3, 4 }]);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.InstallAsync(stream, "plugin.txt", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Plugins.UnsupportedPluginFileType, result.FirstError);
|
||||
Assert.False(Directory.Exists(_pluginsDirectory));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallAsync_WhenUploadingZipWithoutAssemblies_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
await using MemoryStream zipStream = new();
|
||||
CreateZipArchive(zipStream, [("readme.txt", Encoding.UTF8.GetBytes("not an assembly"))]);
|
||||
zipStream.Position = 0;
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.InstallAsync(zipStream, "plugin.zip", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Plugins.PluginArchiveContainsNoAssemblies, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallAsync_WhenUploadingCorruptZip_ShouldReturnNotReadableError()
|
||||
{
|
||||
// Arrange
|
||||
await using MemoryStream stream = new([.. new byte[] { 1, 2, 3, 4 }]);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.InstallAsync(stream, "plugin.zip", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Plugins.PluginArchiveNotReadable, result.FirstError);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the temporary plugins directory created by the tests.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (Directory.Exists(_pluginsDirectory))
|
||||
Directory.Delete(_pluginsDirectory, recursive: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an in-memory ZIP archive containing the provided entries.
|
||||
/// </summary>
|
||||
/// <param name="zipStream">The stream to write the archive into.</param>
|
||||
/// <param name="entries">The entries to add, as pairs of entry name and content.</param>
|
||||
private static void CreateZipArchive(MemoryStream zipStream, IEnumerable<(string Name, byte[] Content)> entries)
|
||||
{
|
||||
using ZipArchive zipArchive = new(zipStream, ZipArchiveMode.Create, leaveOpen: true);
|
||||
foreach ((string name, byte[] content) in entries)
|
||||
{
|
||||
ZipArchiveEntry entry = zipArchive.CreateEntry(name);
|
||||
using Stream entryStream = entry.Open();
|
||||
entryStream.Write(content);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the bytes of the <c>Lumina.TestPlugin.dll</c> assembly from the test output directory.
|
||||
/// </summary>
|
||||
/// <returns>The assembly bytes.</returns>
|
||||
private static byte[] ReadTestAssembly()
|
||||
{
|
||||
return File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "Lumina.TestPlugin.dll"));
|
||||
}
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Core.Plugins.Commands.InstallPlugin;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Plugins.InstallPlugin;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.InstallPlugin;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="InstallPluginEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class InstallPluginEndpointTests
|
||||
{
|
||||
private readonly Application.Common.CQRS.ICommandHandler<InstallPluginCommand, Result<Success>> _mockHandler;
|
||||
private readonly InstallPluginEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InstallPluginEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public InstallPluginEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<Application.Common.CQRS.ICommandHandler<InstallPluginCommand, Result<Success>>>();
|
||||
_sut = Factory.Create<InstallPluginEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArchiveUploaded_ShouldReturnOkResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<InstallPluginCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Success));
|
||||
ConfigureFormWithArchive([1, 2, 3, 4], "plugin.zip");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<Ok>(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArchiveUploaded_ShouldSendInstallPluginCommandWithUploadedStreamAndFileName()
|
||||
{
|
||||
// Arrange
|
||||
byte[] content = [1, 2, 3, 4];
|
||||
string fileName = "plugin.zip";
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<InstallPluginCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Success));
|
||||
ConfigureFormWithArchive(content, fileName);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<InstallPluginCommand>(command =>
|
||||
command.FileName == fileName &&
|
||||
command.Archive != null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoArchiveUploaded_ShouldSendInstallPluginCommandWithNullArchiveAndFileName()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<InstallPluginCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Success));
|
||||
ConfigureFormWithoutFiles();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<Ok>(result);
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<InstallPluginCommand>(command =>
|
||||
command.Archive == null &&
|
||||
command.FileName == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<InstallPluginCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
ConfigureFormWithArchive([1, 2, 3, 4], "plugin.zip");
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemDetails.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
|
||||
Assert.Equal("General.Unauthorized", problemDetailsBody.Title);
|
||||
Assert.Equal("NotAuthorized", problemDetailsBody.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type);
|
||||
Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<InstallPluginCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(Result.Success);
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
ConfigureFormWithArchive([1, 2, 3, 4], "plugin.zip");
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
|
||||
private void ConfigureFormWithArchive(byte[] content, string fileName)
|
||||
{
|
||||
// the stream stays open for the duration of the test, since the endpoint reads it through the form file during execution
|
||||
MemoryStream archiveStream = new(content);
|
||||
IFormFile formFile = new FormFile(archiveStream, 0, content.Length, "archive", fileName);
|
||||
FormFileCollection files = [formFile];
|
||||
IFormCollection form = new FormCollection([], files);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
// a real FormFeature is used instead of a substitute, because the endpoint execution reads the form through the
|
||||
// request machinery, which would bypass a mocked feature and parse the (empty) request body
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
|
||||
private void ConfigureFormWithoutFiles()
|
||||
{
|
||||
IFormCollection form = new FormCollection([]);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -4,10 +4,10 @@ using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPlugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
@@ -25,6 +25,7 @@ public class GetPluginsEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetPluginsEndpoint _sut;
|
||||
private readonly PluginDtoFixture _pluginDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
@@ -40,7 +41,7 @@ public class GetPluginsEndpointTests
|
||||
public async Task ExecuteAsync_WhenApiReturnsPlugins_ShouldReturnSuccessJsonWithPlugins()
|
||||
{
|
||||
// Arrange
|
||||
PluginDto[] expectedPlugins = [new PluginDto { Id = Guid.NewGuid(), Name = "OpenLibrary", Author = "Test Author", Version = "1.0.0" }];
|
||||
PluginDto[] expectedPlugins = [_pluginDtoFixture.Create(name: "OpenLibrary")];
|
||||
_mockApiHttpClient.GetAsync<PluginDto[]>(ApiRoutes.Plugins.GET_PLUGINS, Arg.Any<CancellationToken>())
|
||||
.Returns(expectedPlugins);
|
||||
|
||||
@@ -60,7 +61,7 @@ public class GetPluginsEndpointTests
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<PluginDto[]>(ApiRoutes.Plugins.GET_PLUGINS, Arg.Any<CancellationToken>())
|
||||
.Returns([new PluginDto { Id = Guid.NewGuid(), Name = "OpenLibrary" }]);
|
||||
.Returns([_pluginDtoFixture.Create(name: "OpenLibrary")]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Plugins.InstallPlugin;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Plugins.InstallPlugin;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="InstallPluginEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class InstallPluginEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly InstallPluginEndpoint _sut;
|
||||
private readonly PluginDtoFixture _pluginDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InstallPluginEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public InstallPluginEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<InstallPluginEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArchiveUploaded_ShouldInstallPluginViaApiAndReturnSuccess()
|
||||
{
|
||||
// Arrange
|
||||
byte[] content = [1, 2, 3, 4];
|
||||
string fileName = "plugin.zip";
|
||||
_mockApiHttpClient.PostMultipartAsync<PluginDto>(Arg.Any<string>(), Arg.Any<Stream>(), fileName, "archive", Arg.Any<CancellationToken>())
|
||||
.Returns(_pluginDtoFixture.Create());
|
||||
ConfigureFormWithArchive(content, fileName);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).PostMultipartAsync<PluginDto>(
|
||||
ApiRoutes.Plugins.INSTALL_PLUGIN,
|
||||
Arg.Any<Stream>(),
|
||||
fileName,
|
||||
"archive",
|
||||
Arg.Any<CancellationToken>());
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
}
|
||||
|
||||
private void ConfigureFormWithArchive(byte[] content, string fileName)
|
||||
{
|
||||
// the stream stays open for the duration of the test, since the endpoint reads it through the form file during execution
|
||||
MemoryStream archiveStream = new(content);
|
||||
IFormFile formFile = new FormFile(archiveStream, 0, content.Length, "archive", fileName);
|
||||
FormFileCollection files = [formFile];
|
||||
IFormCollection form = new FormCollection([], files);
|
||||
_sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test";
|
||||
_sut.HttpContext.Features.Set<IFormFeature>(new FormFeature(form));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user