Routes the file browser thumbnail requests through the authenticated Web proxy

This commit is contained in:
BinaryAlley committed 2026-08-29 16:35:12 +03:00
1 parent a32f80337b
commit f694882b46
15 files changed
+299 -35

No files matched your search

@@ -7,14 +7,12 @@ namespace Lumina.Presentation.Web.Common.DTO.Themes;
/// <summary>
/// Data transfer object for the runtime configuration of the file system browser component.
/// </summary>
/// <param name="ServerBasePath">The base URL of the remote API used for thumbnail retrieval.</param>
/// <param name="ClientBasePath">The base URL of the Web application used for file system API calls.</param>
/// <param name="Path">The initial path displayed by the file system browser.</param>
/// <param name="ViewMode">The initial view mode of the file system browser.</param>
/// <param name="IconSize">The initial icon size of the file system browser.</param>
[DebuggerDisplay("Path: {Path}, ViewMode: {ViewMode}")]
public sealed record ThemeFileSystemBrowserConfigurationDto(
string ServerBasePath,
string ClientBasePath,
string Path,
string ViewMode,
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Thumbnails;
/// <summary>
/// Represents a request for retrieving the thumbnail of a file system file.
/// </summary>
/// <param name="Path">The path of the file for which the thumbnail is retrieved.</param>
/// <param name="Quality">The quality to use for the thumbnail.</param>
[DebuggerDisplay("Path: {Path}")]
public record GetThumbnailRequest(
string? Path,
int Quality
);
@@ -0,0 +1,15 @@
namespace Lumina.Presentation.Web.Common.Routes;
/// <summary>
/// Class for the collection of remote API routes called by this Web application.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the thumbnail endpoints of the remote API.
/// </summary>
public static class Thumbnails
{
public const string GET_THUMBNAIL = "thumbnails/get-thumbnail";
}
}
@@ -0,0 +1,15 @@
namespace Lumina.Presentation.Web.Common.Routes;
/// <summary>
/// Class for the collection of routes defined in the Web application.
/// </summary>
public static partial class WebRoutes
{
/// <summary>
/// Routes for the thumbnail endpoints.
/// </summary>
public static class Thumbnails
{
public const string GET_THUMBNAIL = "thumbnails/api-get-thumbnail";
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Thumbnails;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail;
/// <summary>
/// API endpoint for the <c>/thumbnails/api-get-thumbnail</c> route.
/// </summary>
public class GetThumbnailEndpoint : BaseEndpoint<GetThumbnailRequest, IResult>
{
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="GetThumbnailEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public GetThumbnailEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.GET);
Routes(WebRoutes.Thumbnails.GET_THUMBNAIL);
DontAutoTag();
Options(options => options.WithTags("Thumbnails"));
}
/// <summary>
/// Retrieves the thumbnail of the file located at the path identified by the request.
/// </summary>
/// <param name="request">The request containing the file system path of the file for which to get the thumbnail.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetThumbnailRequest request, CancellationToken cancellationToken)
{
// the thumbnail is proxied through the Web application, so that the request carries the authentication of the current user
BlobDataDto blob = await _apiHttpClient.GetBlobAsync($"{ApiRoutes.Thumbnails.GET_THUMBNAIL}?path={Uri.EscapeDataString(request.Path!)}&quality={request.Quality}", cancellationToken).ConfigureAwait(false);
return Results.File(blob.Data, blob.ContentType);
}
}
@@ -119,11 +119,10 @@ public class ThemeFileSystemBrowserRenderer
{
string initConfigJson = JsonSerializer.Serialize(new
{
configuration.ServerBasePath,
configuration.ClientBasePath,
configuration.Path,
configuration.ViewMode,
configuration.IconSize,
ClientBasePath = configuration.ClientBasePath,
Path = configuration.Path,
ViewMode = configuration.ViewMode,
IconSize = configuration.IconSize,
IconBaseUrl = $"{assetBase}/images/icons",
FileIconsUrl = $"{assetBase}/file-icons.json"
}, s_camelCaseJsonOptions);
@@ -1,11 +1,9 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Configuration;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Enums.FileSystem;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Core.Themes;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
@@ -19,17 +17,14 @@ namespace Lumina.Presentation.Web.Core.ViewComponents;
/// </summary>
public class FileSystemBrowserViewComponent : ViewComponent
{
private readonly ServerConfigurationDto _serverConfiguration;
private readonly ThemeFileSystemBrowserRenderer _renderer;
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemBrowserViewComponent"/> class.
/// </summary>
/// <param name="serverConfigurationOptions">Injected service for retrieving <see cref="ServerConfigurationDto"/>.</param>
/// <param name="renderer">Injected renderer of the themed file system browser component.</param>
public FileSystemBrowserViewComponent(IOptions<ServerConfigurationDto> serverConfigurationOptions, ThemeFileSystemBrowserRenderer renderer)
public FileSystemBrowserViewComponent(ThemeFileSystemBrowserRenderer renderer)
{
_serverConfiguration = serverConfigurationOptions.Value;
_renderer = renderer;
}
@@ -40,7 +35,6 @@ public class FileSystemBrowserViewComponent : ViewComponent
public async Task<IViewComponentResult> InvokeAsync()
{
ThemeFileSystemBrowserConfigurationDto configuration = new(
ServerBasePath: $"{_serverConfiguration.BaseAddress}:{_serverConfiguration.Port}/api/v{_serverConfiguration.ApiVersion}/",
ClientBasePath: "http://localhost:5012/", // TODO: take from appsettings or environment
Path: RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? @"/" : @"C:\Users\",
ViewMode: FileSystemViewMode.List.ToString().ToLower(),
@@ -53,7 +47,6 @@ public class FileSystemBrowserViewComponent : ViewComponent
return View(new
{
Path = configuration.Path,
ServerBasePath = configuration.ServerBasePath,
ClientBasePath = configuration.ClientBasePath,
ViewMode = configuration.ViewMode,
IconSize = configuration.IconSize
@@ -97,7 +97,6 @@
return;
}
await initFileSystemBrowser({
serverBasePath: '@Model.ServerBasePath',
clientBasePath: '@Model.ClientBasePath',
path: '@Model.Path.Replace(@"\", @"\\")',
viewMode: '@Model.ViewMode',
@@ -75,7 +75,6 @@
let explorerItemTemplate = null;
let pathSegmentTemplate = null;
let serverBasePath;
let clientBasePath;
let _path;
let pathSeparator = '/';
@@ -113,7 +112,6 @@
* @param {any} config The configuration of the file system browser, with the server and client base paths, the initial path, the initial view mode and icon size, and the optional theme asset URLs.
*/
async function initFileSystemBrowser(config) {
serverBasePath = config.serverBasePath;
clientBasePath = config.clientBasePath;
iconBaseUrl = config.iconBaseUrl || '';
fileIconsUrl = config.fileIconsUrl || '';
@@ -1468,8 +1466,8 @@
* @throws {Error} - Throws an error if the API call fails.
*/
async function getThumbnailApiCall(path, quality) {
// fetch the thumbnail for the given item from the server
const response = await fetch(`${serverBasePath}thumbnails/get-thumbnail?path=` + encodeURIComponent(path) + '&quality=' + quality, {
// fetch the thumbnail for the given item from the server, through the Web application, which proxies the request with the authentication of the current user
const response = await fetch(`${clientBasePath}thumbnails/api-get-thumbnail?path=` + encodeURIComponent(path) + '&quality=' + quality, {
signal: abortController.signal // use the abort signal
});
if (!response.ok)
@@ -19,21 +19,18 @@ public class ThemeFileSystemBrowserConfigurationDtoFixture
/// <summary>
/// Creates a new <see cref="ThemeFileSystemBrowserConfigurationDto"/> instance with randomized test data.
/// </summary>
/// <param name="serverBasePath">Optional base URL of the remote API.</param>
/// <param name="clientBasePath">Optional base URL of the Web application.</param>
/// <param name="path">Optional initial path displayed by the file system browser.</param>
/// <param name="viewMode">Optional initial view mode of the file system browser.</param>
/// <param name="iconSize">Optional initial icon size of the file system browser.</param>
/// <returns>A configured <see cref="ThemeFileSystemBrowserConfigurationDto"/> instance.</returns>
public ThemeFileSystemBrowserConfigurationDto Create(
string? serverBasePath = null,
string? clientBasePath = null,
string? path = null,
string? viewMode = null,
string? iconSize = null)
{
return new ThemeFileSystemBrowserConfigurationDto(
ServerBasePath: serverBasePath ?? $"http://localhost:{_faker.Random.UShort()}/api/v1/",
ClientBasePath: clientBasePath ?? $"http://localhost:{_faker.Random.UShort()}/",
Path: path ?? (_faker.Random.Bool() ? "/" : "C:\\Users\\"),
ViewMode: viewMode ?? _faker.Random.Word(),
@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Thumbnails;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Thumbnails;
/// <summary>
/// Fixture class for generating <see cref="GetThumbnailRequest"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThumbnailRequestFixture
{
/// <summary>
/// Creates a new <see cref="GetThumbnailRequest"/> instance with randomized test data.
/// </summary>
/// <param name="path">Optional file system path of the file whose thumbnail is retrieved.</param>
/// <param name="quality">Optional quality used for the thumbnail.</param>
/// <returns>A configured <see cref="GetThumbnailRequest"/> instance.</returns>
public GetThumbnailRequest Create(string? path = null, int? quality = null)
{
return new GetThumbnailRequest(
Path: path ?? $"/media/{System.Guid.NewGuid():N}.png",
Quality: quality ?? 70
);
}
/// <summary>
/// Creates multiple <see cref="GetThumbnailRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GetThumbnailRequest"/> instances.</returns>
public List<GetThumbnailRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,75 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail;
using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
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.FileSystemManagement.Thumbnails.GetThumbnail;
/// <summary>
/// Contains security tests for the <c>/thumbnails/api-get-thumbnail</c> route served by the <see cref="GetThumbnailEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThumbnailEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly BlobDataDtoFixture _blobDataDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetThumbnailEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public GetThumbnailEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetThumbnail_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
// Act
HttpResponseMessage response = await client.GetAsync("/thumbnails/api-get-thumbnail?path=%2Fmedia%2Fphoto.png&quality=70");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
}
[Theory]
[InlineData("'; DROP TABLE Thumbnails--")] // destructive SQL injection
[InlineData("..\\..\\appsettings.json")] // path traversal
[InlineData("' OR '1'='1")] // basic SQL injection
public async Task GetThumbnail_WhenCalledWithInjectionInPath_ShouldRemainSecure(string maliciousPath)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.RegisterBlobResponse(_blobDataDtoFixture.Create(data: [0x89, 0x50, 0x4E, 0x47], contentType: "image/png"));
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/thumbnails/api-get-thumbnail?path={Uri.EscapeDataString(maliciousPath)}&quality=70");
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.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
}
}
@@ -0,0 +1,75 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Thumbnails;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail;
using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement;
using Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Thumbnails;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail;
/// <summary>
/// Contains unit tests for the <see cref="GetThumbnailEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThumbnailEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly GetThumbnailEndpoint _sut;
private readonly GetThumbnailRequestFixture _getThumbnailRequestFixture = new();
private readonly BlobDataDtoFixture _blobDataDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetThumbnailEndpointTests"/> class.
/// </summary>
public GetThumbnailEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<GetThumbnailEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenApiReturnsThumbnail_ShouldReturnFileWithThumbnailBytes()
{
// Arrange
GetThumbnailRequest request = _getThumbnailRequestFixture.Create(path: "/media/photo.png", quality: 70);
byte[] expectedBytes = [0x89, 0x50, 0x4E, 0x47];
_mockApiHttpClient.GetBlobAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(_blobDataDtoFixture.Create(data: expectedBytes, contentType: "image/png"));
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
string expectedEndpoint = $"{ApiRoutes.Thumbnails.GET_THUMBNAIL}?path={Uri.EscapeDataString(request.Path!)}&quality={request.Quality}";
await _mockApiHttpClient.Received(1).GetBlobAsync(expectedEndpoint, Arg.Any<CancellationToken>());
FileContentHttpResult fileResult = Assert.IsType<FileContentHttpResult>(result);
Assert.Equal(expectedBytes, fileResult.FileContents);
Assert.Equal("image/png", fileResult.ContentType);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldRequestThumbnailAtTheSpecifiedQuality()
{
// Arrange
GetThumbnailRequest request = _getThumbnailRequestFixture.Create(path: "/media/photo.png", quality: 30);
_mockApiHttpClient.GetBlobAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(_blobDataDtoFixture.Create());
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
string expectedEndpoint = $"{ApiRoutes.Thumbnails.GET_THUMBNAIL}?path={Uri.EscapeDataString(request.Path!)}&quality=30";
await _mockApiHttpClient.Received(1).GetBlobAsync(expectedEndpoint, Arg.Any<CancellationToken>());
}
}
@@ -68,7 +68,6 @@ public class ThemeFileSystemBrowserRendererTests
Assert.Contains("/theme-assets/editorial/assets/images/icons", result.Value);
Assert.Contains("data-path=\"{{path}}\"", result.Value);
Assert.Contains("initFileSystemBrowser(", result.Value);
Assert.Contains("serverBasePath", result.Value);
}
[Fact]
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Configuration;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Core.Themes;
@@ -9,7 +8,6 @@ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewComponents;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -25,7 +23,6 @@ namespace Lumina.Presentation.Web.UnitTests.Core.ViewComponents;
[ExcludeFromCodeCoverage]
public class FileSystemBrowserViewComponentTests
{
private readonly IOptions<ServerConfigurationDto> _serverConfigurationOptions;
private readonly ThemeFileSystemBrowserRenderer _mockRenderer;
private readonly FileSystemBrowserViewComponent _sut;
@@ -34,16 +31,10 @@ public class FileSystemBrowserViewComponentTests
/// </summary>
public FileSystemBrowserViewComponentTests()
{
_serverConfigurationOptions = Options.Create(new ServerConfigurationDto
{
ApiVersion = '1',
BaseAddress = "http://localhost",
Port = 5214
});
ThemeService themeService = new(Substitute.For<IApiHttpClient>());
ThemeFileSystemBrowserBuilder builder = new(Substitute.For<IStringLocalizerFactory>(), Substitute.For<IHttpContextAccessor>());
_mockRenderer = Substitute.For<ThemeFileSystemBrowserRenderer>(themeService, new ThemeTemplateEngine(), builder);
_sut = new FileSystemBrowserViewComponent(_serverConfigurationOptions, _mockRenderer);
_sut = new FileSystemBrowserViewComponent(_mockRenderer);
}
[Fact]
@@ -95,7 +86,6 @@ public class FileSystemBrowserViewComponentTests
// Assert
await _mockRenderer.Received(1).RenderAsync(
Arg.Is<ThemeFileSystemBrowserConfigurationDto>(configuration =>
configuration.ServerBasePath == "http://localhost:5214/api/v1/" &&
configuration.ClientBasePath == "http://localhost:5012/" &&
configuration.ViewMode == "list" &&
configuration.IconSize == "large"),