diff --git a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs index e8d2dfaa..a12a72a1 100644 --- a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs +++ b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs @@ -35,16 +35,16 @@ public static class DomainLayerServices services.AddScoped(); services.AddScoped(); services.AddScoped(); - services.AddScoped(); + services.AddSingleton(); services.AddScoped(); services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs b/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs index 6b099e31..33a9737d 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs @@ -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)); } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs index 93a314a4..34a03dab 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs @@ -59,6 +59,13 @@ public interface IPathService /// A collection of characters that are invalid in the context of paths. char[] GetInvalidPathCharsForPlatform(); + /// + /// Sanitizes a human-readable into a safe path segment. + /// + /// The human-readable name to sanitize. + /// An containing the sanitized path segment, or an error. + Result SanitizeSegment(string name); + /// /// Returns the root portion of the given path. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs index d36e1873..02dadc41 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs @@ -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. /// public class PathService : IPathService { + private const int MAX_DIRECTORY_SEGMENT_LENGTH = 100; + private readonly IPlatformContext _platformContext; /// @@ -110,6 +114,51 @@ public class PathService : IPathService return _platformContext.PathStrategy.GetInvalidPathCharsForPlatform(); } + /// + /// Sanitizes a human-readable into a safe path segment, replacing the characters that are invalid for the current platform, and rejecting the segments that could escape the directory. + /// + /// The human-readable name to sanitize. + /// An containing the sanitized path segment, or an error. + public Result 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 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); + } + /// /// Returns the root portion of the given path. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs index ffd4e584..2d36653b 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs @@ -11,7 +11,7 @@ namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext. /// public interface IPathStrategy { - public char PathSeparator { get; } + char PathSeparator { get; } /// /// Checks if is a valid path. @@ -56,6 +56,12 @@ public interface IPathStrategy /// A collection of characters that are invalid in the context of paths char[] GetInvalidPathCharsForPlatform(); + /// + /// Returns a collection of characters that are invalid for a single path segment. + /// + /// A collection of characters that are invalid in the context of a single path segment. + char[] GetInvalidPathSegmentCharsForPlatform(); + /// /// Returns the root portion of the given path. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs index 1aa7dacc..2b6039e5 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs @@ -154,6 +154,15 @@ public class UnixPathStrategy : IUnixPathStrategy return ['\0']; } + /// + /// Returns a collection of characters that are invalid for a single path segment. + /// + /// A collection of characters that are invalid in the context of a single path segment. + public char[] GetInvalidPathSegmentCharsForPlatform() + { + return ['\0']; + } + /// /// Returns the root portion of the given path. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs index 6639883c..396dee6f 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs @@ -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 ['<', '>', '"', '/', '|', '?', '*']; } + /// + /// Returns a collection of characters that are invalid for a single path segment. + /// + /// A collection of characters that are invalid in the context of a single path segment. + public char[] GetInvalidPathSegmentCharsForPlatform() + { + return ['<', '>', '"', '/', '|', '?', '*', ':']; + } + /// /// Returns the root portion of the given path. /// diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs index 0a471cde..11c3a0e1 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs @@ -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 s_storageGates = new(StringComparer.Ordinal); private readonly SemaphoreSlim _mutationGate; + private readonly IPathService _pathService; /// /// Initializes a new instance of the class. /// /// The theme engine configuration options. /// The logger for this service. - public ThemeService(IOptions options, ILogger logger) + /// The service used to validate the path segments of the theme packages. + public ThemeService(IOptions options, ILogger 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 /// The absolute path of the theme pack directory. /// The page key that selects the template. /// The mirrored template path, or when no mirrored template exists. - 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 /// /// The absolute path of the theme pack directory. /// An containing either the parsed manifest, or an error. - private static Result LoadManifestFromDirectory(string themeRoot) + private Result LoadManifestFromDirectory(string themeRoot) { string manifestPath = Path.Combine(themeRoot, MANIFEST_FILE_NAME); if (!File.Exists(manifestPath)) @@ -580,7 +580,7 @@ public sealed class ThemeService : IThemeService /// The absolute path of the theme pack directory. /// The manifest to validate. /// An representing either a successful operation, or an error. - private static Result ValidateManifest(string themeRoot, ThemeManifestDto manifest) + private Result 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 /// The package-relative path to normalize. /// Whether a trailing slash, used for directory entries, is permitted. /// An containing either the normalized path, or an error. - private static Result NormalizeRelativePath(string path, bool allowTrailingSlash = false) + private Result 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 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 /// A task representing the asynchronous operation. 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); } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs index ba9710aa..cf0803aa 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs @@ -520,4 +520,241 @@ public class PathServiceTests Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); _mockPathStrategy.DidNotReceive().GetPathRoot(Arg.Any()); } + + [Fact] + public void SanitizeSegment_WithValidName_ShouldReturnTheNameAsASegment() + { + // Arrange + char[] invalidChars = ['<', '>', ':', '"', '|', '?', '*']; + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(invalidChars); + + // Act + Result 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 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 result = _sut.SanitizeSegment("Bad"); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Bad Name", result.Value.Name); + } + + [Fact] + public void SanitizeSegment_WithConsecutiveWhitespace_ShouldCollapseItIntoASingleSpace() + { + // Arrange + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']); + + // Act + Result 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 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 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 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 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 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 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 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 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 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 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 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 result = _sut.SanitizeSegment(new string('a', 110) + new string(' ', 50)); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(100, result.Value.Name.Length); + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs index 715a5434..c79f6fc3 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs @@ -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() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs index 48d903a4..a01a5f9b 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs @@ -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() { diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs index 204d80d3..f8ec2512 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs @@ -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); } - /// - /// Cleans up the temporary storage used by the tests. - /// - 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")); } + /// + /// Cleans up the temporary storage used by the tests. + /// + 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 + } + } + /// /// Creates a valid theme pack that declares the default, home and library templates and their files. /// @@ -1207,6 +1209,9 @@ public class ThemeServiceTests : IDisposable private static ThemeService CreateSut(ThemeEngineOptionsDto options) { ILogger logger = Substitute.For>(); - return new ThemeService(Options.Create(options), logger); + IPathService pathService = Substitute.For(); + pathService.SanitizeSegment(Arg.Any()) + .Returns(callInfo => PathSegment.Create(callInfo.Arg(), isDirectory: true, isDrive: false)); + return new ThemeService(Options.Create(options), logger, pathService); } }