mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Fixes path segment sanitization allowing path separators
This commit is contained in:
1 parent
c82fadc7a2
commit
942db4c90e
12 files changed
+442
-45
No files matched your search
@@ -35,16 +35,16 @@ public static class DomainLayerServices
|
||||
services.AddScoped<IDirectoryProviderService, DirectoryProviderService>();
|
||||
services.AddScoped<IFileProviderService, FileProviderService>();
|
||||
services.AddScoped<IThumbnailService, ThumbnailService>();
|
||||
services.AddScoped<IPathService, PathService>();
|
||||
services.AddSingleton<IPathService, PathService>();
|
||||
services.AddScoped<IFileTypeService, FileTypeService>();
|
||||
services.AddScoped<IEnvironmentContext, EnvironmentContext>();
|
||||
services.AddScoped<IPlatformContextFactory, PlatformContextFactory>();
|
||||
services.AddScoped<IUnixPlatformContext, UnixPlatformContext>();
|
||||
services.AddScoped<IWindowsPlatformContext, WindowsPlatformContext>();
|
||||
services.AddScoped<IPlatformContextManager, PlatformContextManager>();
|
||||
services.AddScoped<IUnixPathStrategy, UnixPathStrategy>();
|
||||
services.AddScoped<IWindowsPathStrategy, WindowsPathStrategy>();
|
||||
services.AddScoped<IOperatingSystemInfo, OperatingSystemInfo>();
|
||||
services.AddSingleton<IPlatformContextFactory, PlatformContextFactory>();
|
||||
services.AddSingleton<IUnixPlatformContext, UnixPlatformContext>();
|
||||
services.AddSingleton<IWindowsPlatformContext, WindowsPlatformContext>();
|
||||
services.AddSingleton<IPlatformContextManager, PlatformContextManager>();
|
||||
services.AddSingleton<IUnixPathStrategy, UnixPathStrategy>();
|
||||
services.AddSingleton<IWindowsPathStrategy, WindowsPathStrategy>();
|
||||
services.AddSingleton<IOperatingSystemInfo, OperatingSystemInfo>();
|
||||
services.AddScoped<IFileSystemStructureSeedService, FileSystemStructureSeedService>();
|
||||
services.AddScoped<IMediaLibraryScanJobFactory, MediaLibraryScanJobFactory>();
|
||||
services.AddScoped<IMediaLibraryScanningService, MediaLibraryScanningService>();
|
||||
|
||||
@@ -29,5 +29,6 @@ public static partial class Errors
|
||||
public static Error FileAlreadyExists => Error.Conflict(description: nameof(FileAlreadyExists));
|
||||
public static Error DirectoryNotFound => Error.NotFound(description: nameof(DirectoryNotFound));
|
||||
public static Error DirectoryAlreadyExists => Error.Conflict(description: nameof(DirectoryAlreadyExists));
|
||||
public static Error FileTooLarge => Error.Validation(description: nameof(FileTooLarge));
|
||||
}
|
||||
}
|
||||
+7
@@ -59,6 +59,13 @@ public interface IPathService
|
||||
/// <returns>A collection of characters that are invalid in the context of paths.</returns>
|
||||
char[] GetInvalidPathCharsForPlatform();
|
||||
|
||||
/// <summary>
|
||||
/// Sanitizes a human-readable <paramref name="name"/> into a safe path segment.
|
||||
/// </summary>
|
||||
/// <param name="name">The human-readable name to sanitize.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing the sanitized path segment, or an error.</returns>
|
||||
Result<PathSegment> SanitizeSegment(string name);
|
||||
|
||||
/// <summary>
|
||||
/// Returns the root portion of the given path.
|
||||
/// </summary>
|
||||
|
||||
+49
@@ -3,7 +3,9 @@ using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
@@ -13,6 +15,8 @@ namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.
|
||||
/// </summary>
|
||||
public class PathService : IPathService
|
||||
{
|
||||
private const int MAX_DIRECTORY_SEGMENT_LENGTH = 100;
|
||||
|
||||
private readonly IPlatformContext _platformContext;
|
||||
|
||||
/// <summary>
|
||||
@@ -110,6 +114,51 @@ public class PathService : IPathService
|
||||
return _platformContext.PathStrategy.GetInvalidPathCharsForPlatform();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sanitizes a human-readable <paramref name="name"/> into a safe path segment, replacing the characters that are invalid for the current platform, and rejecting the segments that could escape the directory.
|
||||
/// </summary>
|
||||
/// <param name="name">The human-readable name to sanitize.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing the sanitized path segment, or an error.</returns>
|
||||
public Result<PathSegment> SanitizeSegment(string name)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
return Errors.FileSystemManagement.NameCannotBeEmpty;
|
||||
|
||||
char[] invalidChars = _platformContext.PathStrategy.GetInvalidPathSegmentCharsForPlatform();
|
||||
char[] sanitizedChars = [.. name.Trim().Select(character => Array.IndexOf(invalidChars, character) >= 0 ? ' ' : character)];
|
||||
|
||||
// collapse the consecutive whitespace into a single space, so that the segment does not contain ragged spacing
|
||||
List<char> collapsedChars = [];
|
||||
bool previousWasWhitespace = false;
|
||||
foreach (char character in sanitizedChars)
|
||||
{
|
||||
if (char.IsWhiteSpace(character))
|
||||
{
|
||||
if (!previousWasWhitespace)
|
||||
collapsedChars.Add(' ');
|
||||
previousWasWhitespace = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
collapsedChars.Add(character);
|
||||
previousWasWhitespace = false;
|
||||
}
|
||||
}
|
||||
|
||||
string sanitized = new string([.. collapsedChars]).Trim();
|
||||
if (string.Equals(sanitized, ".", StringComparison.Ordinal) || string.Equals(sanitized, "..", StringComparison.Ordinal))
|
||||
return Errors.FileSystemManagement.InvalidPath;
|
||||
// a segment must never contain a path separator, otherwise the segment could escape its directory or nest additional directories
|
||||
if (sanitized.Contains('/') || sanitized.Contains('\\'))
|
||||
return Errors.FileSystemManagement.InvalidPath;
|
||||
if (sanitized.Length > MAX_DIRECTORY_SEGMENT_LENGTH)
|
||||
sanitized = sanitized[..MAX_DIRECTORY_SEGMENT_LENGTH].TrimEnd();
|
||||
if (sanitized.Length == 0)
|
||||
return Errors.FileSystemManagement.InvalidPath;
|
||||
|
||||
return PathSegment.Create(sanitized, isDirectory: true, isDrive: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the root portion of the given path.
|
||||
/// </summary>
|
||||
|
||||
+7
-1
@@ -11,7 +11,7 @@ namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.
|
||||
/// </summary>
|
||||
public interface IPathStrategy
|
||||
{
|
||||
public char PathSeparator { get; }
|
||||
char PathSeparator { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Checks if <paramref name="path"/> is a valid path.
|
||||
@@ -56,6 +56,12 @@ public interface IPathStrategy
|
||||
/// <returns>A collection of characters that are invalid in the context of paths</returns>
|
||||
char[] GetInvalidPathCharsForPlatform();
|
||||
|
||||
/// <summary>
|
||||
/// Returns a collection of characters that are invalid for a single path segment.
|
||||
/// </summary>
|
||||
/// <returns>A collection of characters that are invalid in the context of a single path segment.</returns>
|
||||
char[] GetInvalidPathSegmentCharsForPlatform();
|
||||
|
||||
/// <summary>
|
||||
/// Returns the root portion of the given path.
|
||||
/// </summary>
|
||||
|
||||
+9
@@ -154,6 +154,15 @@ public class UnixPathStrategy : IUnixPathStrategy
|
||||
return ['\0'];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a collection of characters that are invalid for a single path segment.
|
||||
/// </summary>
|
||||
/// <returns>A collection of characters that are invalid in the context of a single path segment.</returns>
|
||||
public char[] GetInvalidPathSegmentCharsForPlatform()
|
||||
{
|
||||
return ['\0'];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the root portion of the given path.
|
||||
/// </summary>
|
||||
|
||||
+11
-2
@@ -113,7 +113,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy
|
||||
// handle UNC path
|
||||
yield return PathSegment.Create(@"\\", isDirectory: false, isDrive: true);
|
||||
|
||||
string[] segments = path.Path[2..].Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries);
|
||||
string[] segments = path.Path[2..].Split([PathSeparator], StringSplitOptions.RemoveEmptyEntries);
|
||||
for (int i = 0; i < segments.Length; i++)
|
||||
yield return CreatePathSegment(segments[i], i, segments.Length);
|
||||
}
|
||||
@@ -122,7 +122,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy
|
||||
// the drive segment
|
||||
yield return PathSegment.Create(path.Path[..2], isDirectory: false, isDrive: true);
|
||||
// extract the other segments
|
||||
string[] segments = path.Path[3..].Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries);
|
||||
string[] segments = path.Path[3..].Split([PathSeparator], StringSplitOptions.RemoveEmptyEntries);
|
||||
for (int i = 0; i < segments.Length; i++)
|
||||
{
|
||||
string segment = segments[i];
|
||||
@@ -190,6 +190,15 @@ public class WindowsPathStrategy : IWindowsPathStrategy
|
||||
return ['<', '>', '"', '/', '|', '?', '*'];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a collection of characters that are invalid for a single path segment.
|
||||
/// </summary>
|
||||
/// <returns>A collection of characters that are invalid in the context of a single path segment.</returns>
|
||||
public char[] GetInvalidPathSegmentCharsForPlatform()
|
||||
{
|
||||
return ['<', '>', '"', '/', '|', '?', '*', ':'];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the root portion of the given path.
|
||||
/// </summary>
|
||||
|
||||
@@ -3,6 +3,8 @@ using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
|
||||
using Lumina.Application.Common.Infrastructure.Themes;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
@@ -12,7 +14,6 @@ using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
@@ -41,10 +42,6 @@ public sealed class ThemeService : IThemeService
|
||||
"^[0-9]+\\.[0-9]+\\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$",
|
||||
RegexOptions.Compiled | RegexOptions.CultureInvariant);
|
||||
|
||||
private static readonly Regex s_pathSegmentPattern = new(
|
||||
"^[A-Za-z0-9][A-Za-z0-9._ -]*$",
|
||||
RegexOptions.Compiled | RegexOptions.CultureInvariant);
|
||||
|
||||
private static readonly JsonSerializerOptions s_manifestJsonOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
@@ -64,16 +61,19 @@ public sealed class ThemeService : IThemeService
|
||||
// resolved storage root.
|
||||
private static readonly ConcurrentDictionary<string, SemaphoreSlim> s_storageGates = new(StringComparer.Ordinal);
|
||||
private readonly SemaphoreSlim _mutationGate;
|
||||
private readonly IPathService _pathService;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThemeService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="options">The theme engine configuration options.</param>
|
||||
/// <param name="logger">The logger for this service.</param>
|
||||
public ThemeService(IOptions<ThemeEngineOptionsDto> options, ILogger<ThemeService> logger)
|
||||
/// <param name="pathService">The service used to validate the path segments of the theme packages.</param>
|
||||
public ThemeService(IOptions<ThemeEngineOptionsDto> options, ILogger<ThemeService> logger, IPathService pathService)
|
||||
{
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
_pathService = pathService;
|
||||
string basePath = AppContext.BaseDirectory;
|
||||
_storageRoot = ResolvePath(basePath, _options.StoragePath);
|
||||
_stagingRoot = Path.Combine(_storageRoot, ".staging");
|
||||
@@ -279,7 +279,7 @@ public sealed class ThemeService : IThemeService
|
||||
/// <param name="themePath">The absolute path of the theme pack directory.</param>
|
||||
/// <param name="pageKey">The page key that selects the template.</param>
|
||||
/// <returns>The mirrored template path, or <see langword="null"/> when no mirrored template exists.</returns>
|
||||
private static string? ResolveMirroredTemplatePath(string themePath, string pageKey)
|
||||
private string? ResolveMirroredTemplatePath(string themePath, string pageKey)
|
||||
{
|
||||
string? candidate = pageKey;
|
||||
while (candidate is not null)
|
||||
@@ -516,7 +516,7 @@ public sealed class ThemeService : IThemeService
|
||||
/// </summary>
|
||||
/// <param name="themeRoot">The absolute path of the theme pack directory.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the parsed manifest, or an error.</returns>
|
||||
private static Result<ThemeManifestDto> LoadManifestFromDirectory(string themeRoot)
|
||||
private Result<ThemeManifestDto> LoadManifestFromDirectory(string themeRoot)
|
||||
{
|
||||
string manifestPath = Path.Combine(themeRoot, MANIFEST_FILE_NAME);
|
||||
if (!File.Exists(manifestPath))
|
||||
@@ -580,7 +580,7 @@ public sealed class ThemeService : IThemeService
|
||||
/// <param name="themeRoot">The absolute path of the theme pack directory.</param>
|
||||
/// <param name="manifest">The manifest to validate.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private static Result<Success> ValidateManifest(string themeRoot, ThemeManifestDto manifest)
|
||||
private Result<Success> ValidateManifest(string themeRoot, ThemeManifestDto manifest)
|
||||
{
|
||||
if (manifest.SchemaVersion != 1)
|
||||
return PackageInvalid("Only theme schemaVersion 1 is supported.");
|
||||
@@ -700,7 +700,7 @@ public sealed class ThemeService : IThemeService
|
||||
/// <param name="path">The package-relative path to normalize.</param>
|
||||
/// <param name="allowTrailingSlash">Whether a trailing slash, used for directory entries, is permitted.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the normalized path, or an error.</returns>
|
||||
private static Result<string> NormalizeRelativePath(string path, bool allowTrailingSlash = false)
|
||||
private Result<string> NormalizeRelativePath(string path, bool allowTrailingSlash = false)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path) || path.Length > 240 || path.Contains('\\') || path.Contains('\0') || path.StartsWith('/') || path.Contains("//"))
|
||||
return PackageInvalid("The theme contains an invalid path.");
|
||||
@@ -714,9 +714,16 @@ public sealed class ThemeService : IThemeService
|
||||
return PackageInvalid("A theme path is nested too deeply.");
|
||||
|
||||
foreach (string segment in segments)
|
||||
if (segment is "." or ".." || segment.Length > 80 || segment.EndsWith(' ') || segment.EndsWith('.') || !s_pathSegmentPattern.IsMatch(segment))
|
||||
{
|
||||
if (segment is "." or ".." || segment.Length > 80 || segment.EndsWith(' ') || segment.EndsWith('.'))
|
||||
return PackageInvalid($"Theme path segment '{segment}' is invalid.");
|
||||
|
||||
// a theme path segment must be already safe, meaning that sanitizing it would leave it unchanged
|
||||
Result<PathSegment> sanitizeResult = _pathService.SanitizeSegment(segment);
|
||||
if (sanitizeResult.IsFailure || !string.Equals(sanitizeResult.Value.Name, segment, StringComparison.Ordinal))
|
||||
return PackageInvalid($"Theme path segment '{segment}' is invalid.");
|
||||
}
|
||||
|
||||
return string.Join('/', segments);
|
||||
}
|
||||
|
||||
@@ -811,7 +818,7 @@ public sealed class ThemeService : IThemeService
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private static async Task SwapIntoDestinationAsync(string extractionPath, string destination, CancellationToken cancellationToken)
|
||||
{
|
||||
const int maxAttempts = 10;
|
||||
const int MAX_ATTEMPTS = 10;
|
||||
for (int attempt = 1; ; attempt++)
|
||||
{
|
||||
try
|
||||
@@ -822,7 +829,7 @@ public sealed class ThemeService : IThemeService
|
||||
Directory.Move(extractionPath, destination);
|
||||
return;
|
||||
}
|
||||
catch (IOException) when (attempt < maxAttempts)
|
||||
catch (IOException) when (attempt < MAX_ATTEMPTS)
|
||||
{
|
||||
await Task.Delay(100 * attempt, cancellationToken);
|
||||
}
|
||||
|
||||
+237
@@ -520,4 +520,241 @@ public class PathServiceTests
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
_mockPathStrategy.DidNotReceive().GetPathRoot(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithValidName_ShouldReturnTheNameAsASegment()
|
||||
{
|
||||
// Arrange
|
||||
char[] invalidChars = ['<', '>', ':', '"', '|', '?', '*'];
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(invalidChars);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment("Valid Name");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Valid Name", result.Value.Name);
|
||||
_mockPathStrategy.Received(1).GetInvalidPathSegmentCharsForPlatform();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithLeadingAndTrailingWhitespace_ShouldTrimTheName()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment(" Valid Name ");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Valid Name", result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithInvalidCharacters_ShouldReplaceThemWithSpaces()
|
||||
{
|
||||
// Arrange
|
||||
char[] invalidChars = ['<', '>', ':', '"', '|', '?', '*'];
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(invalidChars);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment("Bad<Name>");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Bad Name", result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithConsecutiveWhitespace_ShouldCollapseItIntoASingleSpace()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment("Name with spaces");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Name with spaces", result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithDotSegment_ShouldReturnInvalidPath()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment(".");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithDotDotSegment_ShouldReturnInvalidPath()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment("..");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithForwardSlash_ShouldReturnInvalidPath()
|
||||
{
|
||||
// Arrange
|
||||
// the forward slash is not an invalid character for a segment on Unix-like platforms, so only the path service can reject it
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['\0']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment("a/b");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithBackslash_ShouldReturnInvalidPath()
|
||||
{
|
||||
// Arrange
|
||||
// the backslash is not an invalid character for a segment on Windows platforms, so only the path service can reject it
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', '"', '|', '?', '*', ':']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment("a\\b");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("../..")] // parent directory escape
|
||||
[InlineData("a/../b")] // embedded parent directory escape
|
||||
[InlineData("..\\..")] // Windows parent directory escape
|
||||
[InlineData("a\\..\\b")] // embedded Windows parent directory escape
|
||||
public void SanitizeSegment_WithPathTraversal_ShouldReturnInvalidPath(string name)
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['\0']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment(name);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithAColon_WhenTheColonIsValidForThePlatform_ShouldKeepTheColon()
|
||||
{
|
||||
// Arrange
|
||||
// the colon is not an invalid character for a segment on Unix-like platforms, so it must be preserved
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['\0']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment("Name:WithColon");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Name:WithColon", result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithAColon_WhenTheColonIsInvalidForThePlatform_ShouldReplaceItWithASpace()
|
||||
{
|
||||
// Arrange
|
||||
// the colon is an invalid character for a segment on Windows platforms, so it must be replaced
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', '"', '|', '?', '*', ':']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment("Name:WithColon");
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal("Name WithColon", result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithEmptyName_ShouldReturnNameCannotBeEmpty()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment(string.Empty);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError);
|
||||
_mockPathStrategy.DidNotReceive().GetInvalidPathSegmentCharsForPlatform();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithWhitespaceOnlyName_ShouldReturnNameCannotBeEmpty()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment(" ");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithNameMadeOnlyOfInvalidCharacters_ShouldReturnInvalidPath()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment("***");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithNameLongerThanTheMaximumLength_ShouldCapTheSegment()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment(new string('a', 150));
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(100, result.Value.Name.Length);
|
||||
Assert.Equal(new string('a', 100), result.Value.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeSegment_WithNameLongerThanTheMaximumLengthAndTrailingWhitespace_ShouldTrimAfterCapping()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']);
|
||||
|
||||
// Act
|
||||
Result<PathSegment> result = _sut.SanitizeSegment(new string('a', 110) + new string(' ', 50));
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(100, result.Value.Name.Length);
|
||||
}
|
||||
}
|
||||
+34
@@ -507,6 +507,40 @@ public class UnixPathStrategyTests
|
||||
Assert.Equal(result1, result2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathSegmentCharsForPlatform_WhenCalled_ShouldReturnOnlyNullCharacter()
|
||||
{
|
||||
// Act
|
||||
char[] result = _sut.GetInvalidPathSegmentCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.Single(result);
|
||||
Assert.Contains('\0', result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathSegmentCharsForPlatform_WhenCalled_ShouldNotContainTheColon()
|
||||
{
|
||||
// Act
|
||||
char[] result = _sut.GetInvalidPathSegmentCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.DoesNotContain(':', result);
|
||||
Assert.DoesNotContain('/', result);
|
||||
Assert.DoesNotContain('\\', result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathSegmentCharsForPlatform_WhenCalled_ShouldReturnSameResultOnMultipleCalls()
|
||||
{
|
||||
// Act
|
||||
char[] result1 = _sut.GetInvalidPathSegmentCharsForPlatform();
|
||||
char[] result2 = _sut.GetInvalidPathSegmentCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(result1, result2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPathRoot_WithValidUnixPath_ShouldReturnRootSegment()
|
||||
{
|
||||
|
||||
+33
@@ -625,6 +625,39 @@ public class WindowsPathStrategyTests
|
||||
Assert.Equal(result1, result2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathSegmentCharsForPlatform_WhenCalled_ShouldReturnExpectedCharacters()
|
||||
{
|
||||
// Act
|
||||
char[] result = _sut.GetInvalidPathSegmentCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(['<', '>', '"', '/', '|', '?', '*', ':'], result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathSegmentCharsForPlatform_WhenCalled_ShouldContainTheColon()
|
||||
{
|
||||
// Act
|
||||
char[] result = _sut.GetInvalidPathSegmentCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.Contains(':', result);
|
||||
Assert.DoesNotContain('\\', result);
|
||||
Assert.DoesNotContain('\0', result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetInvalidPathSegmentCharsForPlatform_WhenCalled_ShouldReturnSameResultOnMultipleCalls()
|
||||
{
|
||||
// Act
|
||||
char[] result1 = _sut.GetInvalidPathSegmentCharsForPlatform();
|
||||
char[] result2 = _sut.GetInvalidPathSegmentCharsForPlatform();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(result1, result2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPathRoot_WithValidWindowsPath_ShouldReturnRootSegment()
|
||||
{
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
|
||||
using Lumina.Infrastructure.Core.Themes;
|
||||
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
|
||||
@@ -55,26 +57,6 @@ public class ThemeServiceTests : IDisposable
|
||||
_sut = CreateSut(_options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cleans up the temporary storage used by the tests.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(_testRootPath))
|
||||
Directory.Delete(_testRootPath, recursive: true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// best effort cleanup of the per-test temp directory
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
// best effort cleanup of the per-test temp directory
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MaxArchiveBytes_WhenConfigured_ShouldReturnConfiguredValue()
|
||||
{
|
||||
@@ -1151,6 +1133,26 @@ public class ThemeServiceTests : IDisposable
|
||||
Assert.False(_sut.HasThemePack("bundled-theme"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cleans up the temporary storage used by the tests.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(_testRootPath))
|
||||
Directory.Delete(_testRootPath, recursive: true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// best effort cleanup of the per-test temp directory
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
// best effort cleanup of the per-test temp directory
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a valid theme pack that declares the default, home and library templates and their files.
|
||||
/// </summary>
|
||||
@@ -1207,6 +1209,9 @@ public class ThemeServiceTests : IDisposable
|
||||
private static ThemeService CreateSut(ThemeEngineOptionsDto options)
|
||||
{
|
||||
ILogger<ThemeService> logger = Substitute.For<ILogger<ThemeService>>();
|
||||
return new ThemeService(Options.Create(options), logger);
|
||||
IPathService pathService = Substitute.For<IPathService>();
|
||||
pathService.SanitizeSegment(Arg.Any<string>())
|
||||
.Returns(callInfo => PathSegment.Create(callInfo.Arg<string>(), isDirectory: true, isDrive: false));
|
||||
return new ThemeService(Options.Create(options), logger, pathService);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user