mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Merge pull request #170 from BinaryAlley/bugfix/fix-plugin-upload-path-traversal-on-unix
Bugfix/fix plugin upload path traversal on unix
This commit is contained in:
57 files changed
+2826
-16
No files matched your search
@@ -2,6 +2,9 @@
|
|||||||
|
|
||||||
- [Lumina API](#lumina-api)
|
- [Lumina API](#lumina-api)
|
||||||
- [Plugins](#plugins)
|
- [Plugins](#plugins)
|
||||||
|
- [Install Plugin](#install-plugin)
|
||||||
|
- [Install Plugin Request](#install-plugin-request)
|
||||||
|
- [Install Plugin Response](#install-plugin-response)
|
||||||
- [Get Plugins](#get-plugins)
|
- [Get Plugins](#get-plugins)
|
||||||
- [Get Plugins Request](#get-plugins-request)
|
- [Get Plugins Request](#get-plugins-request)
|
||||||
- [Get Plugins Response](#get-plugins-response)
|
- [Get Plugins Response](#get-plugins-response)
|
||||||
@@ -23,6 +26,22 @@
|
|||||||
|
|
||||||
## Plugins
|
## Plugins
|
||||||
|
|
||||||
|
### Install Plugin
|
||||||
|
|
||||||
|
#### Install Plugin Request
|
||||||
|
|
||||||
|
```js
|
||||||
|
POST api/v1/plugins
|
||||||
|
```
|
||||||
|
|
||||||
|
Uploads the plugin as a `multipart/form-data` request. The first file part of the form is used as the plugin archive, which can be either a single `.dll` assembly or a `.zip` archive containing the plugin assembly and its dependencies. The assemblies are placed into the plugin storage directory of the API and are loaded at the next API startup.
|
||||||
|
|
||||||
|
#### Install Plugin Response
|
||||||
|
|
||||||
|
```js
|
||||||
|
200 Ok
|
||||||
|
```
|
||||||
|
|
||||||
### Get Plugins
|
### Get Plugins
|
||||||
|
|
||||||
#### Get Plugins Request
|
#### Get Plugins Request
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
POST {{host}}/api/v1/plugins
|
||||||
|
Authorization: Bearer {{ACCESS_TOKEN}}
|
||||||
|
Content-Type: multipart/form-data; boundary=----LuminaBoundary
|
||||||
|
|
||||||
|
------LuminaBoundary
|
||||||
|
Content-Disposition: form-data; name="archive"; filename="my-plugin.zip"
|
||||||
|
Content-Type: application/octet-stream
|
||||||
|
|
||||||
|
< ./my-plugin.zip
|
||||||
|
------LuminaBoundary--
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Domain.Common.Primitives;
|
||||||
|
using System.IO;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.Common.Infrastructure.Plugins;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Service for installing plugins from an uploaded archive into the plugin storage directory.
|
||||||
|
/// </summary>
|
||||||
|
public interface IPluginInstaller
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Installs the plugin from the provided archive, placing its assemblies into the plugin storage directory.
|
||||||
|
/// The installed plugin is loaded by the host application at the next startup.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="archive">The archive stream of the uploaded plugin.</param>
|
||||||
|
/// <param name="fileName">The file name of the uploaded plugin.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
|
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||||
|
Task<Result<Success>> InstallAsync(Stream archive, string fileName, CancellationToken cancellationToken);
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Application.Common.CQRS;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.IO;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.Core.Plugins.Commands.InstallPlugin;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Command for installing a plugin from an uploaded archive, placing its assemblies into the plugin storage directory.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="Archive">The archive stream of the uploaded plugin.</param>
|
||||||
|
/// <param name="FileName">The file name of the uploaded plugin.</param>
|
||||||
|
[DebuggerDisplay("FileName: {FileName}")]
|
||||||
|
public record InstallPluginCommand(
|
||||||
|
Stream? Archive,
|
||||||
|
string? FileName
|
||||||
|
) : ICommand;
|
||||||
+75
@@ -0,0 +1,75 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Application.Common.CQRS;
|
||||||
|
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.Domain.Common.Primitives;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.Core.Plugins.Commands.InstallPlugin;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handler for the command to install a plugin from an uploaded archive.
|
||||||
|
/// </summary>
|
||||||
|
public class InstallPluginCommandHandler : ICommandHandler<InstallPluginCommand, Result<Success>>
|
||||||
|
{
|
||||||
|
private readonly IPluginInstaller _pluginInstaller;
|
||||||
|
private readonly ICurrentUserService _currentUserService;
|
||||||
|
private readonly IAuthorizationService _authorizationService;
|
||||||
|
private readonly IValidator<InstallPluginCommand> _validator;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="InstallPluginCommandHandler"/> class.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="pluginInstaller">Injected service for installing plugins into the plugin storage directory.</param>
|
||||||
|
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||||
|
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||||
|
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||||
|
public InstallPluginCommandHandler(
|
||||||
|
IPluginInstaller pluginInstaller,
|
||||||
|
ICurrentUserService currentUserService,
|
||||||
|
IAuthorizationService authorizationService,
|
||||||
|
IValidator<InstallPluginCommand> validator)
|
||||||
|
{
|
||||||
|
_pluginInstaller = pluginInstaller;
|
||||||
|
_currentUserService = currentUserService;
|
||||||
|
_authorizationService = authorizationService;
|
||||||
|
_validator = validator;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handles the command to install a plugin from an uploaded archive.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="command">The command to be handled.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
|
/// <returns>
|
||||||
|
/// An <see cref="Result{TValue}"/> representing either a successful operation, or an error.
|
||||||
|
/// </returns>
|
||||||
|
public async Task<Result<Success>> HandleAsync(InstallPluginCommand command, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
List<Error> validationResult = _validator.Validate(command);
|
||||||
|
if (validationResult.Count > 0)
|
||||||
|
return validationResult;
|
||||||
|
|
||||||
|
Guid? currentUserId = _currentUserService.UserId;
|
||||||
|
if (currentUserId is null)
|
||||||
|
return ApplicationErrors.Authorization.NotAuthorized;
|
||||||
|
Guid userId = currentUserId.Value;
|
||||||
|
|
||||||
|
// only admins can install plugins
|
||||||
|
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
|
||||||
|
return ApplicationErrors.Authorization.NotAuthorized;
|
||||||
|
|
||||||
|
Result<Success> installResult = await _pluginInstaller.InstallAsync(command.Archive!, command.FileName!, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (installResult.IsFailure)
|
||||||
|
return installResult.Errors;
|
||||||
|
|
||||||
|
return Result.Success;
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Application.Common.Infrastructure.Validation;
|
||||||
|
using Lumina.Application.Common.Utilities;
|
||||||
|
using Lumina.Domain.Common.Errors;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.Core.Plugins.Commands.InstallPlugin;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Validates the needed validation rules for <see cref="InstallPluginCommand"/>.
|
||||||
|
/// </summary>
|
||||||
|
public class InstallPluginCommandValidator : AbstractValidator<InstallPluginCommand>
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="InstallPluginCommandValidator"/> class.
|
||||||
|
/// </summary>
|
||||||
|
public InstallPluginCommandValidator()
|
||||||
|
{
|
||||||
|
RuleFor(command => command.Archive)
|
||||||
|
.NotNull()
|
||||||
|
.WithError(Errors.Plugins.PluginArchiveCannotBeNull);
|
||||||
|
|
||||||
|
RuleFor(command => command.FileName)
|
||||||
|
.NotEmpty()
|
||||||
|
.WithError(Errors.Plugins.PluginFileNameCannotBeEmpty);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,5 +18,10 @@ public static partial class Errors
|
|||||||
public static Error PluginIdsListCannotBeNull => Error.Validation(description: nameof(PluginIdsListCannotBeNull));
|
public static Error PluginIdsListCannotBeNull => Error.Validation(description: nameof(PluginIdsListCannotBeNull));
|
||||||
public static Error PluginIdsListCannotBeEmpty => Error.Validation(description: nameof(PluginIdsListCannotBeEmpty));
|
public static Error PluginIdsListCannotBeEmpty => Error.Validation(description: nameof(PluginIdsListCannotBeEmpty));
|
||||||
public static Error LibraryMetadataProviderConfigurationNotFound => Error.NotFound(description: nameof(LibraryMetadataProviderConfigurationNotFound));
|
public static Error LibraryMetadataProviderConfigurationNotFound => Error.NotFound(description: nameof(LibraryMetadataProviderConfigurationNotFound));
|
||||||
|
public static Error PluginArchiveCannotBeNull => Error.Validation(description: nameof(PluginArchiveCannotBeNull));
|
||||||
|
public static Error PluginFileNameCannotBeEmpty => Error.Validation(description: nameof(PluginFileNameCannotBeEmpty));
|
||||||
|
public static Error UnsupportedPluginFileType => Error.Validation(description: nameof(UnsupportedPluginFileType));
|
||||||
|
public static Error PluginArchiveNotReadable => Error.Failure(description: nameof(PluginArchiveNotReadable));
|
||||||
|
public static Error PluginArchiveContainsNoAssemblies => Error.Failure(description: nameof(PluginArchiveContainsNoAssemblies));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -108,6 +108,7 @@ public static class InfrastructureLayerServices
|
|||||||
PluginLoadResultDto pluginLoadResult = PluginLoader.LoadPlugins(pluginsDirectory, services);
|
PluginLoadResultDto pluginLoadResult = PluginLoader.LoadPlugins(pluginsDirectory, services);
|
||||||
services.AddSingleton<IPluginManager>(new PluginManager(pluginLoadResult.Plugins));
|
services.AddSingleton<IPluginManager>(new PluginManager(pluginLoadResult.Plugins));
|
||||||
services.AddScoped<IPluginSettingsStore, PluginSettingsStore>();
|
services.AddScoped<IPluginSettingsStore, PluginSettingsStore>();
|
||||||
|
services.AddScoped<IPluginInstaller, PluginInstaller>();
|
||||||
services.AddSingleton(serviceProvider => new PluginDetectionSyncJob(
|
services.AddSingleton(serviceProvider => new PluginDetectionSyncJob(
|
||||||
serviceProvider.GetRequiredService<IServiceScopeFactory>(),
|
serviceProvider.GetRequiredService<IServiceScopeFactory>(),
|
||||||
serviceProvider.GetRequiredService<IPluginManager>(),
|
serviceProvider.GetRequiredService<IPluginManager>(),
|
||||||
|
|||||||
@@ -0,0 +1,143 @@
|
|||||||
|
#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 Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.IO;
|
||||||
|
using System.IO.Compression;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Infrastructure.Core.Plugins;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Service for installing plugins from an uploaded archive into the plugin storage directory. The installed plugin assemblies are loaded by the host application at the next startup.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class PluginInstaller : IPluginInstaller
|
||||||
|
{
|
||||||
|
// the install mutates the shared plugins directory, so the operations are serialized per resolved directory.
|
||||||
|
// A per-instance gate is NOT enough: several hosts can run against the same plugins directory at once (for
|
||||||
|
// example the parallel in-memory hosts started by the test factories), so the gate is keyed on the directory.
|
||||||
|
private static readonly ConcurrentDictionary<string, SemaphoreSlim> s_pluginDirectoryGates = new(StringComparer.Ordinal);
|
||||||
|
private readonly string _pluginsDirectory;
|
||||||
|
private readonly SemaphoreSlim _mutationGate;
|
||||||
|
private readonly ILogger<PluginInstaller> _logger;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="PluginInstaller"/> class.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="pluginsSettings">The injected plugins configuration options.</param>
|
||||||
|
/// <param name="logger">The logger for this service.</param>
|
||||||
|
public PluginInstaller(IOptions<PluginsSettingsDto> pluginsSettings, ILogger<PluginInstaller> logger)
|
||||||
|
{
|
||||||
|
_pluginsDirectory = Path.Combine(AppContext.BaseDirectory, pluginsSettings.Value.Directory);
|
||||||
|
_mutationGate = s_pluginDirectoryGates.GetOrAdd(_pluginsDirectory, static _ => new SemaphoreSlim(1, 1));
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Installs the plugin from the provided archive, placing its assemblies into the plugin storage directory.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="archive">The archive stream of the uploaded plugin.</param>
|
||||||
|
/// <param name="fileName">The file name of the uploaded plugin.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
|
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||||
|
public async Task<Result<Success>> InstallAsync(Stream archive, string fileName, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
await _mutationGate.WaitAsync(cancellationToken);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string extension = Path.GetExtension(fileName);
|
||||||
|
if (string.Equals(extension, ".dll", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
string? safeFileName = GetSafeFileName(fileName);
|
||||||
|
if (safeFileName is null)
|
||||||
|
return Errors.Plugins.PluginFileNameCannotBeEmpty;
|
||||||
|
await CopySingleAssemblyAsync(archive, safeFileName, cancellationToken).ConfigureAwait(false);
|
||||||
|
return Result.Success;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await ExtractZipArchiveAsync(archive, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (InvalidDataException exception)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(exception, "An uploaded plugin archive could not be read.");
|
||||||
|
return Errors.Plugins.PluginArchiveNotReadable;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Errors.Plugins.UnsupportedPluginFileType;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_mutationGate.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Copies a single plugin assembly into the plugin storage directory.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="assemblyStream">The stream of the plugin assembly.</param>
|
||||||
|
/// <param name="assemblyFileName">The file name of the plugin assembly.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
|
private async Task CopySingleAssemblyAsync(Stream assemblyStream, string assemblyFileName, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(_pluginsDirectory);
|
||||||
|
string destinationPath = Path.Combine(_pluginsDirectory, assemblyFileName);
|
||||||
|
await using FileStream outputStream = new(destinationPath, FileMode.Create, FileAccess.Write, FileShare.None);
|
||||||
|
await assemblyStream.CopyToAsync(outputStream, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extracts the plugin assemblies from a ZIP archive into the plugin storage directory, flattening the archive
|
||||||
|
/// structure, since the plugin loader scans the storage directory root for assemblies.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="archive">The stream of the uploaded ZIP archive.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
|
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||||
|
private async Task<Result<Success>> ExtractZipArchiveAsync(Stream archive, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
using ZipArchive zipArchive = new(archive);
|
||||||
|
Directory.CreateDirectory(_pluginsDirectory);
|
||||||
|
bool foundAssembly = false;
|
||||||
|
foreach (ZipArchiveEntry entry in zipArchive.Entries)
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
string? safeFileName = GetSafeFileName(entry.FullName);
|
||||||
|
if (safeFileName is null || !string.Equals(Path.GetExtension(safeFileName), ".dll", StringComparison.OrdinalIgnoreCase))
|
||||||
|
continue;
|
||||||
|
foundAssembly = true;
|
||||||
|
string destinationPath = Path.Combine(_pluginsDirectory, safeFileName);
|
||||||
|
await using Stream entryStream = entry.Open();
|
||||||
|
await using FileStream outputStream = new(destinationPath, FileMode.Create, FileAccess.Write, FileShare.None);
|
||||||
|
await entryStream.CopyToAsync(outputStream, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!foundAssembly)
|
||||||
|
return Errors.Plugins.PluginArchiveContainsNoAssemblies;
|
||||||
|
return Result.Success;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extracts the bare file name of an uploaded plugin file or archive entry, stripping every directory component,
|
||||||
|
/// so that a path traversal attempt cannot write outside the plugin storage directory on any platform.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="path">The file path to sanitize.</param>
|
||||||
|
/// <returns>The bare file name, or <see langword="null"/> when the path contains no usable file name.</returns>
|
||||||
|
private static string? GetSafeFileName(string path)
|
||||||
|
{
|
||||||
|
// a backslash is not a directory separator on non-Windows platforms, so it is normalized to '/' first,
|
||||||
|
// after which Path.GetFileName can strip any directory component on every platform
|
||||||
|
string fileName = Path.GetFileName(path.Replace('\\', '/'));
|
||||||
|
return fileName is "" or "." or ".." ? null : fileName;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,5 +13,6 @@ public static partial class ApiRoutes
|
|||||||
public const string GET_PLUGINS = "/plugins";
|
public const string GET_PLUGINS = "/plugins";
|
||||||
public const string GET_PLUGIN_SETTINGS = "/plugins/{pluginId}/settings";
|
public const string GET_PLUGIN_SETTINGS = "/plugins/{pluginId}/settings";
|
||||||
public const string UPDATE_PLUGIN_SETTINGS = "/plugins/{pluginId}/settings";
|
public const string UPDATE_PLUGIN_SETTINGS = "/plugins/{pluginId}/settings";
|
||||||
|
public const string INSTALL_PLUGIN = "/plugins";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+68
@@ -0,0 +1,68 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Application.Common.CQRS;
|
||||||
|
using Lumina.Application.Core.Plugins.Commands.InstallPlugin;
|
||||||
|
using Lumina.Domain.Common.Primitives;
|
||||||
|
using Lumina.Presentation.Api.Common.Routes.Plugins;
|
||||||
|
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.InstallPlugin;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// API endpoint for the <c>/plugins</c> route.
|
||||||
|
/// </summary>
|
||||||
|
public class InstallPluginEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
|
||||||
|
{
|
||||||
|
private readonly ICommandHandler<InstallPluginCommand, Result<Success>> _installPluginCommandHandler;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="InstallPluginEndpoint"/> class.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="installPluginCommandHandler">Injected service for handling install plugin commands.</param>
|
||||||
|
public InstallPluginEndpoint(ICommandHandler<InstallPluginCommand, Result<Success>> installPluginCommandHandler)
|
||||||
|
{
|
||||||
|
_installPluginCommandHandler = installPluginCommandHandler;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Configures the API endpoint.
|
||||||
|
/// </summary>
|
||||||
|
public override void Configure()
|
||||||
|
{
|
||||||
|
Verbs(FastEndpoints.Http.POST);
|
||||||
|
Routes(ApiRoutes.Plugins.INSTALL_PLUGIN);
|
||||||
|
Version(1);
|
||||||
|
DontCatchExceptions();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Installs the plugin uploaded in the multipart form of the request, placing its assemblies into the plugin storage directory.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The request object.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
|
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
// a multipart body without any part cannot be parsed as a form, so a malformed upload is treated as a missing archive
|
||||||
|
IFormFile? archive = null;
|
||||||
|
if (HttpContext.Request.HasFormContentType)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
archive = HttpContext.Request.Form.Files.FirstOrDefault();
|
||||||
|
}
|
||||||
|
catch (InvalidDataException)
|
||||||
|
{
|
||||||
|
archive = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
InstallPluginCommand command = new(archive?.OpenReadStream(), archive?.FileName);
|
||||||
|
Result<Success> result = await _installPluginCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false);
|
||||||
|
return result.Match(success => TypedResults.Ok(), Problem);
|
||||||
|
}
|
||||||
|
}
|
||||||
+110
@@ -0,0 +1,110 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using FastEndpoints;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.InstallPlugin;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Class used for providing a textual description for the <see cref="InstallPluginEndpoint"/> API endpoint, for OpenAPI.
|
||||||
|
/// </summary>
|
||||||
|
[ExcludeFromCodeCoverage]
|
||||||
|
public class InstallPluginEndpointSummary : Summary<InstallPluginEndpoint, EmptyRequest>
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="InstallPluginEndpointSummary"/> class.
|
||||||
|
/// </summary>
|
||||||
|
public InstallPluginEndpointSummary()
|
||||||
|
{
|
||||||
|
Summary = "Installs a plugin.";
|
||||||
|
Description = "Installs the plugin uploaded in the multipart form of the request, placing its assemblies into the plugin storage directory. The plugin is loaded by the host application at the next startup.";
|
||||||
|
|
||||||
|
Response(200, "The plugin was successfully installed.");
|
||||||
|
|
||||||
|
Response(401, "Authentication required.", "application/problem+json",
|
||||||
|
example: new[]
|
||||||
|
{
|
||||||
|
new
|
||||||
|
{
|
||||||
|
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||||
|
status = 401,
|
||||||
|
title = "Unauthorized",
|
||||||
|
detail = "You are not authorized",
|
||||||
|
instance = "/api/v1/plugins"
|
||||||
|
},
|
||||||
|
new
|
||||||
|
{
|
||||||
|
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||||
|
status = 401,
|
||||||
|
title = "Unauthorized",
|
||||||
|
detail = "Invalid token: The token expired at '01/01/2024 01:00:00'",
|
||||||
|
instance = "/api/v1/plugins"
|
||||||
|
},
|
||||||
|
new
|
||||||
|
{
|
||||||
|
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||||
|
status = 401,
|
||||||
|
title = "Unauthorized",
|
||||||
|
detail = "The token is invalid",
|
||||||
|
instance = "/api/v1/plugins"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
Response(403, "The request failed because the user is not an Admin, or the uploaded plugin archive is not readable.", "application/problem+json",
|
||||||
|
example: new[]
|
||||||
|
{
|
||||||
|
new
|
||||||
|
{
|
||||||
|
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
|
||||||
|
title = "General.Failure",
|
||||||
|
status = 403,
|
||||||
|
detail = "NotAuthorized",
|
||||||
|
instance = "/api/v1/plugins",
|
||||||
|
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||||
|
},
|
||||||
|
new
|
||||||
|
{
|
||||||
|
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
|
||||||
|
title = "General.Failure",
|
||||||
|
status = 403,
|
||||||
|
detail = "PluginArchiveNotReadable",
|
||||||
|
instance = "/api/v1/plugins",
|
||||||
|
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||||
|
},
|
||||||
|
new
|
||||||
|
{
|
||||||
|
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
|
||||||
|
title = "General.Failure",
|
||||||
|
status = 403,
|
||||||
|
detail = "PluginArchiveContainsNoAssemblies",
|
||||||
|
instance = "/api/v1/plugins",
|
||||||
|
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
Response(422, "The request did not pass validation checks.", "application/problem+json",
|
||||||
|
example: new
|
||||||
|
{
|
||||||
|
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
|
||||||
|
title = "General.Validation",
|
||||||
|
status = 422,
|
||||||
|
detail = "OneOrMoreValidationErrorsOccurred",
|
||||||
|
instance = "/api/v1/plugins",
|
||||||
|
errors = new Dictionary<string, string[]>
|
||||||
|
{
|
||||||
|
{
|
||||||
|
"General.Validation", new[]
|
||||||
|
{
|
||||||
|
"PluginArchiveCannotBeNull"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,5 +13,6 @@ public static partial class ApiRoutes
|
|||||||
public const string GET_PLUGINS = "plugins";
|
public const string GET_PLUGINS = "plugins";
|
||||||
public const string GET_PLUGIN_SETTINGS = "plugins/{pluginId}/settings";
|
public const string GET_PLUGIN_SETTINGS = "plugins/{pluginId}/settings";
|
||||||
public const string UPDATE_PLUGIN_SETTINGS = "plugins/{pluginId}/settings";
|
public const string UPDATE_PLUGIN_SETTINGS = "plugins/{pluginId}/settings";
|
||||||
|
public const string INSTALL_PLUGIN = "plugins";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,5 +14,6 @@ public static partial class WebRoutes
|
|||||||
public const string GET_PLUGINS = "{culture}/admin/manage-plugins/api-get-plugins";
|
public const string GET_PLUGINS = "{culture}/admin/manage-plugins/api-get-plugins";
|
||||||
public const string GET_PLUGIN_SETTINGS = "{culture}/admin/manage-plugins/api-get-plugin-settings/{pluginId}";
|
public const string GET_PLUGIN_SETTINGS = "{culture}/admin/manage-plugins/api-get-plugin-settings/{pluginId}";
|
||||||
public const string UPDATE_PLUGIN_SETTINGS = "{culture}/admin/manage-plugins/api-update-plugin-settings";
|
public const string UPDATE_PLUGIN_SETTINGS = "{culture}/admin/manage-plugins/api-update-plugin-settings";
|
||||||
|
public const string INSTALL_PLUGIN = "{culture}/admin/manage-plugins/api-install-plugin";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+63
@@ -0,0 +1,63 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using FastEndpoints;
|
||||||
|
using Lumina.Presentation.Web.Common.Api;
|
||||||
|
using Lumina.Presentation.Web.Common.Authorization;
|
||||||
|
using Lumina.Presentation.Web.Common.DTO.Plugins;
|
||||||
|
using Lumina.Presentation.Web.Common.Routes;
|
||||||
|
using Lumina.Presentation.Web.Core.Endpoints.Common;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Presentation.Web.Core.Endpoints.Plugins.InstallPlugin;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// API endpoint for the <c>/{culture}/admin/manage-plugins/api-install-plugin</c> route.
|
||||||
|
/// </summary>
|
||||||
|
public class InstallPluginEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||||
|
{
|
||||||
|
private readonly IApiHttpClient _apiHttpClient;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="InstallPluginEndpoint"/> class.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
|
||||||
|
public InstallPluginEndpoint(IApiHttpClient apiHttpClient)
|
||||||
|
{
|
||||||
|
_apiHttpClient = apiHttpClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Configures the endpoint.
|
||||||
|
/// </summary>
|
||||||
|
public override void Configure()
|
||||||
|
{
|
||||||
|
base.Configure();
|
||||||
|
Verbs(Http.POST);
|
||||||
|
Routes(WebRoutes.Plugins.INSTALL_PLUGIN);
|
||||||
|
DontAutoTag();
|
||||||
|
Options(options => options.WithTags("Plugins"));
|
||||||
|
Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
|
||||||
|
EnableAntiforgery();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Installs the plugin uploaded in the multipart form of the request.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The request object.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
|
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
IFormFile? archive = HttpContext.Request.Form.Files.FirstOrDefault();
|
||||||
|
if (archive is null)
|
||||||
|
return Results.Problem(statusCode: StatusCodes.Status400BadRequest, detail: "The uploaded plugin archive is missing.");
|
||||||
|
|
||||||
|
await using Stream archiveStream = archive.OpenReadStream();
|
||||||
|
await _apiHttpClient.PostMultipartAsync<PluginDto>(ApiRoutes.Plugins.INSTALL_PLUGIN, archiveStream, archive.FileName, "archive", cancellationToken).ConfigureAwait(false);
|
||||||
|
return JsonSuccess();
|
||||||
|
}
|
||||||
|
}
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using FastEndpoints;
|
||||||
|
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Presentation.Web.Core.Endpoints.Plugins.InstallPlugin;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Class used for providing a textual description for the <see cref="InstallPluginEndpoint"/> endpoint, for OpenAPI.
|
||||||
|
/// </summary>
|
||||||
|
[ExcludeFromCodeCoverage]
|
||||||
|
public class InstallPluginEndpointSummary : Summary<InstallPluginEndpoint, EmptyRequest>
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="InstallPluginEndpointSummary"/> class.
|
||||||
|
/// </summary>
|
||||||
|
public InstallPluginEndpointSummary()
|
||||||
|
{
|
||||||
|
Summary = "Installs a plugin.";
|
||||||
|
Description = "Installs the plugin uploaded in the multipart form of the request, placing its assemblies into the plugin storage directory of the API. The plugin is loaded by the API at its next startup.";
|
||||||
|
|
||||||
|
Response(200, "The plugin was successfully installed.", example: new SuccessResponse(true));
|
||||||
|
}
|
||||||
|
}
|
||||||
+16
-1
@@ -1,4 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<root>
|
<root>
|
||||||
<!--
|
<!--
|
||||||
Microsoft ResX Schema
|
Microsoft ResX Schema
|
||||||
@@ -723,4 +723,19 @@
|
|||||||
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
||||||
<value>يجب أن يكون رقم المجلد أكبر من الصفر!</value>
|
<value>يجب أن يكون رقم المجلد أكبر من الصفر!</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginArchiveContainsNoAssemblies" xml:space="preserve">
|
||||||
|
<value>أرشيف المكوّن الإضافي المرفوع لا يحتوي على تجميعات!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveCannotBeNull" xml:space="preserve">
|
||||||
|
<value>لا يمكن أن يكون أرشيف المكوّن الإضافي فارغاً!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginFileNameCannotBeEmpty" xml:space="preserve">
|
||||||
|
<value>لا يمكن أن يكون اسم ملف المكوّن الإضافي فارغاً!</value>
|
||||||
|
</data>
|
||||||
|
<data name="UnsupportedPluginFileType" xml:space="preserve">
|
||||||
|
<value>نوع ملف المكوّن الإضافي المرفوع غير مدعوم!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveNotReadable" xml:space="preserve">
|
||||||
|
<value>تعذّرت قراءة أرشيف المكوّن الإضافي المرفوع!</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
+16
-1
@@ -1,4 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<root>
|
<root>
|
||||||
<!--
|
<!--
|
||||||
Microsoft ResX Schema
|
Microsoft ResX Schema
|
||||||
@@ -723,4 +723,19 @@
|
|||||||
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
||||||
<value>Bandnummer muss größer als null sein!</value>
|
<value>Bandnummer muss größer als null sein!</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginArchiveContainsNoAssemblies" xml:space="preserve">
|
||||||
|
<value>Das hochgeladene Plugin-Archiv enthält keine Assemblys!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveCannotBeNull" xml:space="preserve">
|
||||||
|
<value>Das Plugin-Archiv darf nicht null sein!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginFileNameCannotBeEmpty" xml:space="preserve">
|
||||||
|
<value>Der Dateiname des Plugins darf nicht leer sein!</value>
|
||||||
|
</data>
|
||||||
|
<data name="UnsupportedPluginFileType" xml:space="preserve">
|
||||||
|
<value>Der Dateityp des hochgeladenen Plugins wird nicht unterstützt!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveNotReadable" xml:space="preserve">
|
||||||
|
<value>Das hochgeladene Plugin-Archiv konnte nicht gelesen werden!</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
+16
-1
@@ -1,4 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<root>
|
<root>
|
||||||
<!--
|
<!--
|
||||||
Microsoft ResX Schema
|
Microsoft ResX Schema
|
||||||
@@ -723,4 +723,19 @@
|
|||||||
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
||||||
<value>Volume number must be greater than zero!</value>
|
<value>Volume number must be greater than zero!</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginArchiveContainsNoAssemblies" xml:space="preserve">
|
||||||
|
<value>The uploaded plugin archive contains no assemblies!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveCannotBeNull" xml:space="preserve">
|
||||||
|
<value>The plugin archive cannot be null!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginFileNameCannotBeEmpty" xml:space="preserve">
|
||||||
|
<value>The plugin file name cannot be empty!</value>
|
||||||
|
</data>
|
||||||
|
<data name="UnsupportedPluginFileType" xml:space="preserve">
|
||||||
|
<value>The uploaded plugin file type is not supported!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveNotReadable" xml:space="preserve">
|
||||||
|
<value>The plugin archive could not be read!</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
+16
-1
@@ -1,4 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<root>
|
<root>
|
||||||
<!--
|
<!--
|
||||||
Microsoft ResX Schema
|
Microsoft ResX Schema
|
||||||
@@ -723,4 +723,19 @@
|
|||||||
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
||||||
<value>¡El número de volumen debe ser mayor que cero!</value>
|
<value>¡El número de volumen debe ser mayor que cero!</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginArchiveContainsNoAssemblies" xml:space="preserve">
|
||||||
|
<value>El archivo del plugin subido no contiene ensamblados!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveCannotBeNull" xml:space="preserve">
|
||||||
|
<value>El archivo del plugin no puede ser nulo!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginFileNameCannotBeEmpty" xml:space="preserve">
|
||||||
|
<value>El nombre del archivo del plugin no puede estar vacío!</value>
|
||||||
|
</data>
|
||||||
|
<data name="UnsupportedPluginFileType" xml:space="preserve">
|
||||||
|
<value>El tipo de archivo del plugin subido no es compatible!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveNotReadable" xml:space="preserve">
|
||||||
|
<value>No se pudo leer el archivo del plugin subido!</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
+16
-1
@@ -1,4 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<root>
|
<root>
|
||||||
<!--
|
<!--
|
||||||
Microsoft ResX Schema
|
Microsoft ResX Schema
|
||||||
@@ -723,4 +723,19 @@
|
|||||||
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
||||||
<value>Le numéro de volume doit être supérieur à zéro !</value>
|
<value>Le numéro de volume doit être supérieur à zéro !</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginArchiveContainsNoAssemblies" xml:space="preserve">
|
||||||
|
<value>L'archive du plugin téléversé ne contient aucun assembly !</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveCannotBeNull" xml:space="preserve">
|
||||||
|
<value>L'archive du plugin ne peut pas etre nulle !</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginFileNameCannotBeEmpty" xml:space="preserve">
|
||||||
|
<value>Le nom du fichier du plugin ne peut pas etre vide !</value>
|
||||||
|
</data>
|
||||||
|
<data name="UnsupportedPluginFileType" xml:space="preserve">
|
||||||
|
<value>Le type de fichier du plugin téléversé n est pas pris en charge !</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveNotReadable" xml:space="preserve">
|
||||||
|
<value>L'archive du plugin téléversé n a pas pu être lue !</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
+16
-1
@@ -1,4 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<root>
|
<root>
|
||||||
<!--
|
<!--
|
||||||
Microsoft ResX Schema
|
Microsoft ResX Schema
|
||||||
@@ -723,4 +723,19 @@
|
|||||||
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
||||||
<value>Il numero del volume deve essere maggiore di zero!</value>
|
<value>Il numero del volume deve essere maggiore di zero!</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginArchiveContainsNoAssemblies" xml:space="preserve">
|
||||||
|
<value>L'archivio del plugin caricato non contiene assembly!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveCannotBeNull" xml:space="preserve">
|
||||||
|
<value>L'archivio del plugin non può essere nullo!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginFileNameCannotBeEmpty" xml:space="preserve">
|
||||||
|
<value>Il nome del file del plugin non può essere vuoto!</value>
|
||||||
|
</data>
|
||||||
|
<data name="UnsupportedPluginFileType" xml:space="preserve">
|
||||||
|
<value>Il tipo di file del plugin caricato non è supportato!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveNotReadable" xml:space="preserve">
|
||||||
|
<value>Non è stato possibile leggere l archivio del plugin caricato!</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
+16
-1
@@ -1,4 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<root>
|
<root>
|
||||||
<!--
|
<!--
|
||||||
Microsoft ResX Schema
|
Microsoft ResX Schema
|
||||||
@@ -723,4 +723,19 @@
|
|||||||
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
||||||
<value>巻数は0より大きくなければなりません!</value>
|
<value>巻数は0より大きくなければなりません!</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginArchiveContainsNoAssemblies" xml:space="preserve">
|
||||||
|
<value>アップロードされたプラグインアーカイブにアセンブリが含まれていません!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveCannotBeNull" xml:space="preserve">
|
||||||
|
<value>プラグインアーカイブを null にすることはできません!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginFileNameCannotBeEmpty" xml:space="preserve">
|
||||||
|
<value>プラグインのファイル名を空にすることはできません!</value>
|
||||||
|
</data>
|
||||||
|
<data name="UnsupportedPluginFileType" xml:space="preserve">
|
||||||
|
<value>アップロードされたプラグインのファイルタイプはサポートされていません!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveNotReadable" xml:space="preserve">
|
||||||
|
<value>アップロードされたプラグインアーカイブを読み取れませんでした!</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
+16
-1
@@ -1,4 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<root>
|
<root>
|
||||||
<!--
|
<!--
|
||||||
Microsoft ResX Schema
|
Microsoft ResX Schema
|
||||||
@@ -723,4 +723,19 @@
|
|||||||
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
||||||
<value>Volume number must be greater than zero!</value>
|
<value>Volume number must be greater than zero!</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginArchiveContainsNoAssemblies" xml:space="preserve">
|
||||||
|
<value>The uploaded plugin archive contains no assemblies!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveCannotBeNull" xml:space="preserve">
|
||||||
|
<value>The plugin archive cannot be null!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginFileNameCannotBeEmpty" xml:space="preserve">
|
||||||
|
<value>The plugin file name cannot be empty!</value>
|
||||||
|
</data>
|
||||||
|
<data name="UnsupportedPluginFileType" xml:space="preserve">
|
||||||
|
<value>The uploaded plugin file type is not supported!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveNotReadable" xml:space="preserve">
|
||||||
|
<value>The plugin archive could not be read!</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
+16
-1
@@ -1,4 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<root>
|
<root>
|
||||||
<!--
|
<!--
|
||||||
Microsoft ResX Schema
|
Microsoft ResX Schema
|
||||||
@@ -723,4 +723,19 @@
|
|||||||
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
||||||
<value>Numărul volumului trebuie să fie mai mare decât zero!</value>
|
<value>Numărul volumului trebuie să fie mai mare decât zero!</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginArchiveContainsNoAssemblies" xml:space="preserve">
|
||||||
|
<value>Arhiva pluginului încărcat nu conține niciun assembly!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveCannotBeNull" xml:space="preserve">
|
||||||
|
<value>Arhiva pluginului nu poate fi nulă!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginFileNameCannotBeEmpty" xml:space="preserve">
|
||||||
|
<value>Numele fișierului pluginului nu poate fi gol!</value>
|
||||||
|
</data>
|
||||||
|
<data name="UnsupportedPluginFileType" xml:space="preserve">
|
||||||
|
<value>Tipul de fișier al pluginului încărcat nu este acceptat!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveNotReadable" xml:space="preserve">
|
||||||
|
<value>Arhiva pluginului încărcat nu a putut fi citită!</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
+16
-1
@@ -1,4 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<root>
|
<root>
|
||||||
<!--
|
<!--
|
||||||
Microsoft ResX Schema
|
Microsoft ResX Schema
|
||||||
@@ -723,4 +723,19 @@
|
|||||||
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
||||||
<value>Номер тому має бути більшим за нуль!</value>
|
<value>Номер тому має бути більшим за нуль!</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginArchiveContainsNoAssemblies" xml:space="preserve">
|
||||||
|
<value>Архів завантаженого плагіна не містить збірок!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveCannotBeNull" xml:space="preserve">
|
||||||
|
<value>Архів плагіна не може бути null!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginFileNameCannotBeEmpty" xml:space="preserve">
|
||||||
|
<value>Ім'я файлу плагіна не може бути порожнім!</value>
|
||||||
|
</data>
|
||||||
|
<data name="UnsupportedPluginFileType" xml:space="preserve">
|
||||||
|
<value>Тип файлу завантаженого плагіна не підтримується!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveNotReadable" xml:space="preserve">
|
||||||
|
<value>Не вдалося прочитати архів завантаженого плагіна!</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
+16
-1
@@ -1,4 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<root>
|
<root>
|
||||||
<!--
|
<!--
|
||||||
Microsoft ResX Schema
|
Microsoft ResX Schema
|
||||||
@@ -723,4 +723,19 @@
|
|||||||
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
|
||||||
<value>卷号必须大于零!</value>
|
<value>卷号必须大于零!</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginArchiveContainsNoAssemblies" xml:space="preserve">
|
||||||
|
<value>上传的插件存档中不包含程序集!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveCannotBeNull" xml:space="preserve">
|
||||||
|
<value>插件存档不能为空!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginFileNameCannotBeEmpty" xml:space="preserve">
|
||||||
|
<value>插件文件名不能为空!</value>
|
||||||
|
</data>
|
||||||
|
<data name="UnsupportedPluginFileType" xml:space="preserve">
|
||||||
|
<value>不支持上传的插件文件类型!</value>
|
||||||
|
</data>
|
||||||
|
<data name="PluginArchiveNotReadable" xml:space="preserve">
|
||||||
|
<value>无法读取上传的插件存档!</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<root>
|
<root>
|
||||||
<!--
|
<!--
|
||||||
Microsoft ResX Schema
|
Microsoft ResX Schema
|
||||||
@@ -156,4 +156,13 @@
|
|||||||
<data name="SettingsSaved" xml:space="preserve">
|
<data name="SettingsSaved" xml:space="preserve">
|
||||||
<value>تم حفظ الإعدادات</value>
|
<value>تم حفظ الإعدادات</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginUploadedRestartRequired" xml:space="preserve">
|
||||||
|
<value>تم رفع المكوّن الإضافي. سيقوم API بتحميله عند إعادة التشغيل التالية.</value>
|
||||||
|
</data>
|
||||||
|
<data name="Upload" xml:space="preserve">
|
||||||
|
<value>رفع</value>
|
||||||
|
</data>
|
||||||
|
<data name="UploadFailed" xml:space="preserve">
|
||||||
|
<value>فشل الرفع</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
@@ -156,4 +156,13 @@
|
|||||||
<data name="SettingsSaved" xml:space="preserve">
|
<data name="SettingsSaved" xml:space="preserve">
|
||||||
<value>Einstellungen gespeichert</value>
|
<value>Einstellungen gespeichert</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginUploadedRestartRequired" xml:space="preserve">
|
||||||
|
<value>Plugin hochgeladen. Die API lädt es beim nächsten Neustart.</value>
|
||||||
|
</data>
|
||||||
|
<data name="Upload" xml:space="preserve">
|
||||||
|
<value>Hochladen</value>
|
||||||
|
</data>
|
||||||
|
<data name="UploadFailed" xml:space="preserve">
|
||||||
|
<value>Upload fehlgeschlagen</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
@@ -156,4 +156,13 @@
|
|||||||
<data name="SettingsSaved" xml:space="preserve">
|
<data name="SettingsSaved" xml:space="preserve">
|
||||||
<value>Settings saved</value>
|
<value>Settings saved</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginUploadedRestartRequired" xml:space="preserve">
|
||||||
|
<value>Plugin uploaded. The API will load it on its next restart.</value>
|
||||||
|
</data>
|
||||||
|
<data name="Upload" xml:space="preserve">
|
||||||
|
<value>Upload</value>
|
||||||
|
</data>
|
||||||
|
<data name="UploadFailed" xml:space="preserve">
|
||||||
|
<value>Upload failed</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
@@ -156,4 +156,13 @@
|
|||||||
<data name="SettingsSaved" xml:space="preserve">
|
<data name="SettingsSaved" xml:space="preserve">
|
||||||
<value>Configuración guardada</value>
|
<value>Configuración guardada</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginUploadedRestartRequired" xml:space="preserve">
|
||||||
|
<value>Plugin subido. La API lo cargará en su próximo reinicio.</value>
|
||||||
|
</data>
|
||||||
|
<data name="Upload" xml:space="preserve">
|
||||||
|
<value>Subir</value>
|
||||||
|
</data>
|
||||||
|
<data name="UploadFailed" xml:space="preserve">
|
||||||
|
<value>Error al subir</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
@@ -156,4 +156,13 @@
|
|||||||
<data name="SettingsSaved" xml:space="preserve">
|
<data name="SettingsSaved" xml:space="preserve">
|
||||||
<value>Paramètres enregistrés</value>
|
<value>Paramètres enregistrés</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginUploadedRestartRequired" xml:space="preserve">
|
||||||
|
<value>Plugin téléversé. L API le chargera à son prochain redémarrage.</value>
|
||||||
|
</data>
|
||||||
|
<data name="Upload" xml:space="preserve">
|
||||||
|
<value>Téléverser</value>
|
||||||
|
</data>
|
||||||
|
<data name="UploadFailed" xml:space="preserve">
|
||||||
|
<value>Échec du téléversement</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
@@ -156,4 +156,13 @@
|
|||||||
<data name="SettingsSaved" xml:space="preserve">
|
<data name="SettingsSaved" xml:space="preserve">
|
||||||
<value>Impostazioni salvate</value>
|
<value>Impostazioni salvate</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginUploadedRestartRequired" xml:space="preserve">
|
||||||
|
<value>Plugin caricato. L API lo caricherà al prossimo riavvio.</value>
|
||||||
|
</data>
|
||||||
|
<data name="Upload" xml:space="preserve">
|
||||||
|
<value>Carica</value>
|
||||||
|
</data>
|
||||||
|
<data name="UploadFailed" xml:space="preserve">
|
||||||
|
<value>Caricamento non riuscito</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
@@ -156,4 +156,13 @@
|
|||||||
<data name="SettingsSaved" xml:space="preserve">
|
<data name="SettingsSaved" xml:space="preserve">
|
||||||
<value>設定を保存しました</value>
|
<value>設定を保存しました</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginUploadedRestartRequired" xml:space="preserve">
|
||||||
|
<value>プラグインがアップロードされました。APIは次回再起動時に読み込みます。</value>
|
||||||
|
</data>
|
||||||
|
<data name="Upload" xml:space="preserve">
|
||||||
|
<value>アップロード</value>
|
||||||
|
</data>
|
||||||
|
<data name="UploadFailed" xml:space="preserve">
|
||||||
|
<value>アップロードに失敗しました</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
@@ -156,4 +156,13 @@
|
|||||||
<data name="SettingsSaved" xml:space="preserve">
|
<data name="SettingsSaved" xml:space="preserve">
|
||||||
<value>Settings saved</value>
|
<value>Settings saved</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginUploadedRestartRequired" xml:space="preserve">
|
||||||
|
<value>Plugin uploaded. The API will load it on its next restart.</value>
|
||||||
|
</data>
|
||||||
|
<data name="Upload" xml:space="preserve">
|
||||||
|
<value>Upload</value>
|
||||||
|
</data>
|
||||||
|
<data name="UploadFailed" xml:space="preserve">
|
||||||
|
<value>Upload failed</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
@@ -156,4 +156,13 @@
|
|||||||
<data name="SettingsSaved" xml:space="preserve">
|
<data name="SettingsSaved" xml:space="preserve">
|
||||||
<value>Setări salvate</value>
|
<value>Setări salvate</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginUploadedRestartRequired" xml:space="preserve">
|
||||||
|
<value>Plugin încărcat. API-ul îl va încărca la următoarea repornire.</value>
|
||||||
|
</data>
|
||||||
|
<data name="Upload" xml:space="preserve">
|
||||||
|
<value>Încarcă</value>
|
||||||
|
</data>
|
||||||
|
<data name="UploadFailed" xml:space="preserve">
|
||||||
|
<value>Încărcarea a eșuat</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<root>
|
<root>
|
||||||
<!--
|
<!--
|
||||||
Microsoft ResX Schema
|
Microsoft ResX Schema
|
||||||
@@ -156,4 +156,13 @@
|
|||||||
<data name="SettingsSaved" xml:space="preserve">
|
<data name="SettingsSaved" xml:space="preserve">
|
||||||
<value>Налаштування збережено</value>
|
<value>Налаштування збережено</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginUploadedRestartRequired" xml:space="preserve">
|
||||||
|
<value>Плагін завантажено. API завантажить його під час наступного перезапуску.</value>
|
||||||
|
</data>
|
||||||
|
<data name="Upload" xml:space="preserve">
|
||||||
|
<value>Завантажити</value>
|
||||||
|
</data>
|
||||||
|
<data name="UploadFailed" xml:space="preserve">
|
||||||
|
<value>Не вдалося завантажити</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
@@ -156,4 +156,13 @@
|
|||||||
<data name="SettingsSaved" xml:space="preserve">
|
<data name="SettingsSaved" xml:space="preserve">
|
||||||
<value>设置已保存</value>
|
<value>设置已保存</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="PluginUploadedRestartRequired" xml:space="preserve">
|
||||||
|
<value>插件已上传。API将在下次重启时加载它。</value>
|
||||||
|
</data>
|
||||||
|
<data name="Upload" xml:space="preserve">
|
||||||
|
<value>上传</value>
|
||||||
|
</data>
|
||||||
|
<data name="UploadFailed" xml:space="preserve">
|
||||||
|
<value>上传失败</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
@@ -27,6 +27,10 @@
|
|||||||
@_localizer["Plugins"]
|
@_localizer["Plugins"]
|
||||||
</h1>
|
</h1>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="form-row" style="margin-bottom: 0.75rem;">
|
||||||
|
<button id="btn-upload-plugin" type="button" class="confirm-button">@_localizer["Upload"]</button>
|
||||||
|
<input id="plugin-upload-input" type="file" accept=".zip,.dll" hidden />
|
||||||
|
</div>
|
||||||
@if (Model.Length > 0)
|
@if (Model.Length > 0)
|
||||||
{
|
{
|
||||||
<table class="w-100 text-light-two">
|
<table class="w-100 text-light-two">
|
||||||
@@ -179,14 +183,48 @@
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const uploadButton = document.getElementById('btn-upload-plugin');
|
||||||
|
const uploadInput = document.getElementById('plugin-upload-input');
|
||||||
|
const installUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Plugins.INSTALL_PLUGIN)';
|
||||||
|
|
||||||
|
// uploads the selected plugin archive as a multipart request, keeping the antiforgery token
|
||||||
|
async function handleUploadInputChange() {
|
||||||
|
const file = uploadInput.files[0];
|
||||||
|
if (!file)
|
||||||
|
return;
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('archive', file);
|
||||||
|
formData.append('__RequestVerificationToken', document.querySelector('input[name="__RequestVerificationToken"]')?.value ?? '');
|
||||||
|
const response = await fetch(installUrl, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'X-Requested-With': 'XMLHttpRequest' },
|
||||||
|
body: formData
|
||||||
|
});
|
||||||
|
if (response.ok) {
|
||||||
|
notificationService.show('@_localizer["PluginUploadedRestartRequired"]', NotificationType.SUCCESS);
|
||||||
|
uploadInput.value = '';
|
||||||
|
} else {
|
||||||
|
notificationService.show('@_localizer["UploadFailed"]', NotificationType.ERROR);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// opens the file picker when the upload button is clicked
|
||||||
|
function handleUploadButtonClick() {
|
||||||
|
uploadInput.click();
|
||||||
|
}
|
||||||
|
|
||||||
// add listeners
|
// add listeners
|
||||||
document.addEventListener('click', handleSettingsToggleClick);
|
document.addEventListener('click', handleSettingsToggleClick);
|
||||||
document.addEventListener('click', handleSavePluginSettingsClick);
|
document.addEventListener('click', handleSavePluginSettingsClick);
|
||||||
|
uploadButton.addEventListener('click', handleUploadButtonClick);
|
||||||
|
uploadInput.addEventListener('change', handleUploadInputChange);
|
||||||
|
|
||||||
// register cleanup for these listeners
|
// register cleanup for these listeners
|
||||||
cleanupFunctions.push(() => {
|
cleanupFunctions.push(() => {
|
||||||
document.removeEventListener('click', handleSettingsToggleClick);
|
document.removeEventListener('click', handleSettingsToggleClick);
|
||||||
document.removeEventListener('click', handleSavePluginSettingsClick);
|
document.removeEventListener('click', handleSavePluginSettingsClick);
|
||||||
|
uploadButton.removeEventListener('click', handleUploadButtonClick);
|
||||||
|
uploadInput.removeEventListener('change', handleUploadInputChange);
|
||||||
});
|
});
|
||||||
|
|
||||||
// store all cleanups for this view on window object using the scriptId
|
// store all cleanups for this view on window object using the scriptId
|
||||||
|
|||||||
+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;
|
_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>
|
/// <summary>
|
||||||
/// Registers the response returned when the specified PUT endpoint is called.
|
/// Registers the response returned when the specified PUT endpoint is called.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -138,6 +148,16 @@ public class StubApiHttpClient : IApiHttpClient
|
|||||||
_putResponseFactories[endpoint] = _ => response;
|
_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>
|
/// <summary>
|
||||||
/// Registers the specified DELETE endpoint as succeeding.
|
/// Registers the specified DELETE endpoint as succeeding.
|
||||||
/// </summary>
|
/// </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,187 @@
|
|||||||
|
#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_WhenUploadingZipWithBackslashTraversalEntry_ShouldFlattenItInsidePluginsDirectory()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
await using MemoryStream zipStream = new();
|
||||||
|
// a backslash is not a directory separator on non-Windows platforms, so it must be neutralized explicitly
|
||||||
|
CreateZipArchive(zipStream, [(@"..\evil.dll", ReadTestAssembly())]);
|
||||||
|
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, "evil.dll")));
|
||||||
|
Assert.False(File.Exists(Path.Combine(AppContext.BaseDirectory, "evil.dll")));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task InstallAsync_WhenUploadingSingleAssemblyWithTraversalFileName_ShouldFlattenItInsidePluginsDirectory()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
const string TRAVERSAL_FILE_NAME = "traversal-test-plugin.dll";
|
||||||
|
await using FileStream stream = File.OpenRead(Path.Combine(AppContext.BaseDirectory, "Lumina.TestPlugin.dll"));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
Result<Success> result = await _sut.InstallAsync(stream, $@"..\{TRAVERSAL_FILE_NAME}", CancellationToken.None);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.False(result.IsFailure);
|
||||||
|
Assert.True(File.Exists(Path.Combine(_pluginsDirectory, TRAVERSAL_FILE_NAME)));
|
||||||
|
Assert.False(File.Exists(Path.Combine(AppContext.BaseDirectory, TRAVERSAL_FILE_NAME)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[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.DTO.Plugins;
|
||||||
using Lumina.Presentation.Web.Common.Routes;
|
using Lumina.Presentation.Web.Common.Routes;
|
||||||
using Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPlugins;
|
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.Fixtures.Common.TestHelpers;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using NSubstitute;
|
using NSubstitute;
|
||||||
using System;
|
|
||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
@@ -25,6 +25,7 @@ public class GetPluginsEndpointTests
|
|||||||
{
|
{
|
||||||
private readonly IApiHttpClient _mockApiHttpClient;
|
private readonly IApiHttpClient _mockApiHttpClient;
|
||||||
private readonly GetPluginsEndpoint _sut;
|
private readonly GetPluginsEndpoint _sut;
|
||||||
|
private readonly PluginDtoFixture _pluginDtoFixture = new();
|
||||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -40,7 +41,7 @@ public class GetPluginsEndpointTests
|
|||||||
public async Task ExecuteAsync_WhenApiReturnsPlugins_ShouldReturnSuccessJsonWithPlugins()
|
public async Task ExecuteAsync_WhenApiReturnsPlugins_ShouldReturnSuccessJsonWithPlugins()
|
||||||
{
|
{
|
||||||
// Arrange
|
// 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>())
|
_mockApiHttpClient.GetAsync<PluginDto[]>(ApiRoutes.Plugins.GET_PLUGINS, Arg.Any<CancellationToken>())
|
||||||
.Returns(expectedPlugins);
|
.Returns(expectedPlugins);
|
||||||
|
|
||||||
@@ -60,7 +61,7 @@ public class GetPluginsEndpointTests
|
|||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
_mockApiHttpClient.GetAsync<PluginDto[]>(ApiRoutes.Plugins.GET_PLUGINS, Arg.Any<CancellationToken>())
|
_mockApiHttpClient.GetAsync<PluginDto[]>(ApiRoutes.Plugins.GET_PLUGINS, Arg.Any<CancellationToken>())
|
||||||
.Returns([new PluginDto { Id = Guid.NewGuid(), Name = "OpenLibrary" }]);
|
.Returns([_pluginDtoFixture.Create(name: "OpenLibrary")]);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
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