#region ========================================================================= USING ===================================================================================== using Nemera.Application.Common.Infrastructure.Models.DTO.Themes; using Nemera.Domain.Common.Errors; using Nemera.Domain.Common.Primitives; using Nemera.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Nemera.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Nemera.Infrastructure.Common.Models.DTO.Configuration; using Nemera.Infrastructure.Core.Themes; using Nemera.Infrastructure.Fixtures.Common.Models.DTO.Configuration; using Nemera.Infrastructure.Fixtures.Core.Themes; 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.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; #endregion namespace Nemera.Infrastructure.IntegrationTests.Core.Themes; /// /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class ThemeServiceTests : IDisposable { private const string DEFAULT_TEMPLATE = "default template"; private const string HOME_TEMPLATE = "home template"; private const string LIBRARY_TEMPLATE = "library template"; private readonly string _testRootPath; private readonly ThemeEngineOptionsDto _options; private readonly ThemeService _sut; private readonly ThemePackFixture _themePackFixture = new(); private readonly ThemeEngineOptionsDtoFixture _themeEngineOptionsDtoFixture = new(); /// /// Initializes a new instance of the class. /// public ThemeServiceTests() { _testRootPath = Path.Combine(Path.GetTempPath(), $"nemera-themes-{Guid.NewGuid():N}"); Directory.CreateDirectory(_testRootPath); _options = _themeEngineOptionsDtoFixture.Create( storagePath: Path.Combine(_testRootPath, "themes"), bundledThemesPath: Path.Combine(_testRootPath, "bundled"), defaultThemeId: "nemera-default", maxArchiveBytes: 8 * 1024 * 1024, maxExpandedBytes: 24 * 1024 * 1024, maxSingleFileBytes: 6 * 1024 * 1024, maxEntries: 250); _sut = CreateSut(_options); } [Fact] public void GetBundledThemeArchivePaths_WhenBundledDirectoryDoesNotExist_ShouldReturnEmptyList() { // Arrange // The bundled directory of the default options never exists. // Act IReadOnlyList result = _sut.GetBundledThemeArchivePaths(); // Assert Assert.Empty(result); } [Fact] public void GetBundledThemeArchivePaths_WhenBundledDirectoryContainsZips_ShouldReturnSortedZipPaths() { // Arrange string bundledPath = Path.Combine(_testRootPath, "bundled"); Directory.CreateDirectory(bundledPath); File.WriteAllBytes(Path.Combine(bundledPath, "zeta.zip"), _themePackFixture.Create()); File.WriteAllBytes(Path.Combine(bundledPath, "alpha.zip"), _themePackFixture.Create()); File.WriteAllBytes(Path.Combine(bundledPath, "notes.txt"), Encoding.UTF8.GetBytes("not a theme archive")); // Act IReadOnlyList result = _sut.GetBundledThemeArchivePaths(); // Assert Assert.Equal(2, result.Count); Assert.Equal(Path.Combine(bundledPath, "alpha.zip"), result[0]); Assert.Equal(Path.Combine(bundledPath, "zeta.zip"), result[1]); } [Fact] public async Task HasThemePack_WhenThemeIsInstalled_ShouldReturnTrue() { // Arrange await InstallValidThemeAsync(_themePackFixture.Create()); // Act bool result = _sut.HasThemePack("test-theme"); // Assert Assert.True(result); } [Fact] public void HasThemePack_WhenThemeIsNotInstalled_ShouldReturnFalse() { // Arrange // Nothing is installed. // Act bool result = _sut.HasThemePack("test-theme"); // Assert Assert.False(result); } [Fact] public void HasThemePack_WhenThemeDirectoryExistsButManifestIsMissing_ShouldReturnFalse() { // Arrange Directory.CreateDirectory(Path.Combine(_options.StoragePath, "test-theme")); // Act bool result = _sut.HasThemePack("test-theme"); // Assert Assert.False(result); } [Fact] public async Task InstallAsync_WhenArchiveIsValid_ShouldExtractThemeAndReturnManifest() { // Arrange byte[] archive = _themePackFixture.Create(defaultTemplateContent: DEFAULT_TEMPLATE); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsSuccess); Assert.Equal("test-theme", result.Value.Id); Assert.Equal("Test Theme", result.Value.Name); Assert.True(File.Exists(Path.Combine(_options.StoragePath, "test-theme", "theme.json"))); Assert.True(File.Exists(Path.Combine(_options.StoragePath, "test-theme", "templates", "default.html"))); Assert.True(File.Exists(Path.Combine(_options.StoragePath, "test-theme", "assets", "preview.png"))); } [Fact] public async Task InstallAsync_WhenThemeIsAlreadyInstalled_ShouldReplaceExistingThemeFiles() { // Arrange byte[] firstArchive = _themePackFixture.Create(defaultTemplateContent: "first version"); byte[] secondArchive = _themePackFixture.Create(defaultTemplateContent: "second version"); // Act await InstallValidThemeAsync(firstArchive); await InstallValidThemeAsync(secondArchive); Result templateResult = await _sut.GetTemplateAsync("test-theme", "default", CancellationToken.None); // Assert Assert.True(templateResult.IsSuccess); Assert.Equal("second version", templateResult.Value); string[] themeDirectories = [.. Directory.GetDirectories(_options.StoragePath).Where(path => Path.GetFileName(path) != ".staging")]; Assert.Single(themeDirectories); Assert.Equal("test-theme", Path.GetFileName(themeDirectories[0])); } [Fact] public async Task InstallAsync_WhenThemeDestinationIsBlocked_ShouldReturnThemeFilesUnreadableInsteadOfThrowing() { // Arrange byte[] archive = _themePackFixture.Create(themeId: "test-theme"); // The destination path is blocked by an existing file, so the extracted pack cannot be moved into place. Directory.CreateDirectory(_options.StoragePath); File.WriteAllText(Path.Combine(_options.StoragePath, "test-theme"), "blocked"); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); } [Fact] public async Task InstallAsync_WhenArchiveExceedsMaxArchiveBytes_ShouldReturnArchiveTooLargeError() { // Arrange ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( storagePath: Path.Combine(_testRootPath, "themes"), bundledThemesPath: Path.Combine(_testRootPath, "bundled"), defaultThemeId: "nemera-default", maxArchiveBytes: 8 * 1024 * 1024, maxExpandedBytes: 24 * 1024 * 1024, maxSingleFileBytes: 6 * 1024 * 1024, maxEntries: 250); options.MaxArchiveBytes = 128; ThemeService sut = CreateSut(options); byte[] archive = _themePackFixture.Create(); // Act Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Archive.TooLarge", result.FirstError.Code); Assert.False(sut.HasThemePack("test-theme")); } [Fact] public async Task InstallAsync_WhenArchiveStreamIsEmpty_ShouldReturnPackageInvalidError() { // Arrange using MemoryStream emptyStream = new(); // Act Result result = await _sut.InstallAsync(emptyStream, CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); Assert.Contains("empty", result.FirstError.Description); } [Fact] public async Task InstallAsync_WhenArchiveContainsNoEntries_ShouldReturnPackageInvalidError() { // Arrange byte[] archive = _themePackFixture.CreateArchive(); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); Assert.Contains("no files", result.FirstError.Description); } [Fact] public async Task InstallAsync_WhenArchiveIsNotAZip_ShouldReturnThemeArchiveNotReadable() { // Arrange byte[] archive = Encoding.UTF8.GetBytes("this is not a valid zip archive"); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("ThemeArchiveNotReadable", result.FirstError.Description); Assert.False(_sut.HasThemePack("test-theme")); } [Fact] public async Task InstallAsync_WhenArchiveContainsPathTraversalEntry_ShouldReturnPackageInvalidError() { // Arrange string manifestJson = _themePackFixture.CreateManifestJson(); byte[] archive = _themePackFixture.CreateArchive( new("theme.json", manifestJson), new("templates/default.html", DEFAULT_TEMPLATE), new("../evil.txt", "should not escape the package")); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); Assert.False(_sut.HasThemePack("test-theme")); } [Fact] public async Task InstallAsync_WhenArchiveContainsBackslashPathEntry_ShouldReturnPackageInvalidError() { // Arrange string manifestJson = _themePackFixture.CreateManifestJson(); byte[] archive = _themePackFixture.CreateArchive( new("theme.json", manifestJson), new("templates/default.html", DEFAULT_TEMPLATE), new("assets\\..\\evil.txt", "should not escape the package")); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); } [Fact] public async Task InstallAsync_WhenArchiveEntryIsOutsideAllowedLocations_ShouldReturnPackageInvalidError() { // Arrange string manifestJson = _themePackFixture.CreateManifestJson(); byte[] archive = _themePackFixture.CreateArchive( new("theme.json", manifestJson), new("templates/default.html", DEFAULT_TEMPLATE), new("notes/readme.txt", "files must live under templates or assets")); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); Assert.Contains("outside the allowed", result.FirstError.Description); } [Fact] public async Task InstallAsync_WhenArchiveContainsSymbolicLinkEntry_ShouldReturnPackageInvalidError() { // Arrange string manifestJson = _themePackFixture.CreateManifestJson(); byte[] archive = _themePackFixture.CreateArchive( new("theme.json", manifestJson), new("templates/default.html", DEFAULT_TEMPLATE), new("assets/link.png", "symlink target", UnixFileType: 0xA000)); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); Assert.Contains("Symbolic links", result.FirstError.Description); } [Fact] public async Task InstallAsync_WhenArchiveContainsDuplicateEntryPaths_ShouldReturnPackageInvalidError() { // Arrange string manifestJson = _themePackFixture.CreateManifestJson(); byte[] archive = _themePackFixture.CreateArchive( new("theme.json", manifestJson), new("templates/default.html", DEFAULT_TEMPLATE), new("templates/default.html", "duplicate")); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); Assert.Contains("duplicate path", result.FirstError.Description); } [Fact] public async Task InstallAsync_WhenArchiveExceedsMaxEntries_ShouldReturnTooManyEntriesError() { // Arrange ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( storagePath: Path.Combine(_testRootPath, "themes"), bundledThemesPath: Path.Combine(_testRootPath, "bundled"), defaultThemeId: "nemera-default", maxArchiveBytes: 8 * 1024 * 1024, maxExpandedBytes: 24 * 1024 * 1024, maxSingleFileBytes: 6 * 1024 * 1024, maxEntries: 250); options.MaxEntries = 2; ThemeService sut = CreateSut(options); byte[] archive = _themePackFixture.Create(); // Act Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Archive.TooManyEntries", result.FirstError.Code); } [Fact] public async Task InstallAsync_WhenArchiveFileExceedsMaxSingleFileBytes_ShouldReturnFileTooLargeError() { // Arrange ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( storagePath: Path.Combine(_testRootPath, "themes"), bundledThemesPath: Path.Combine(_testRootPath, "bundled"), defaultThemeId: "nemera-default", maxArchiveBytes: 8 * 1024 * 1024, maxExpandedBytes: 24 * 1024 * 1024, maxSingleFileBytes: 6 * 1024 * 1024, maxEntries: 250); options.MaxSingleFileBytes = 10; ThemeService sut = CreateSut(options); string manifestJson = _themePackFixture.CreateManifestJson(); byte[] archive = _themePackFixture.CreateArchive( new("theme.json", manifestJson), new("templates/default.html", new string('a', 64))); // Act Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.File.TooLarge", result.FirstError.Code); } [Fact] public async Task InstallAsync_WhenExpandedSizeExceedsMaxExpandedBytes_ShouldReturnExpandedTooLargeError() { // Arrange ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( storagePath: Path.Combine(_testRootPath, "themes"), bundledThemesPath: Path.Combine(_testRootPath, "bundled"), defaultThemeId: "nemera-default", maxArchiveBytes: 8 * 1024 * 1024, maxExpandedBytes: 24 * 1024 * 1024, maxSingleFileBytes: 6 * 1024 * 1024, maxEntries: 250); options.MaxSingleFileBytes = 400; options.MaxExpandedBytes = 300; ThemeService sut = CreateSut(options); byte[] archive = _themePackFixture.CreateArchive( new("templates/default.html", new string('a', 200)), new("templates/other.html", new string('b', 200))); // Act Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Archive.ExpandedTooLarge", result.FirstError.Code); } [Fact] public async Task InstallAsync_WhenSchemaVersionIsUnsupported_ShouldReturnPackageInvalidError() { // Arrange byte[] archive = _themePackFixture.Create(schemaVersion: 2); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert AssertPackageInvalid(result, "schemaVersion"); } [Fact] public async Task InstallAsync_WhenThemeIdIsNotKebabCase_ShouldReturnPackageInvalidError() { // Arrange byte[] archive = _themePackFixture.Create(themeId: "Test_Theme"); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert AssertPackageInvalid(result, "kebab-case"); } [Fact] public async Task InstallAsync_WhenThemeIdIsTooLong_ShouldReturnPackageInvalidError() { // Arrange string longThemeId = string.Join('-', Enumerable.Repeat("a", 33)); byte[] archive = _themePackFixture.Create(themeId: longThemeId); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert AssertPackageInvalid(result, "kebab-case"); } [Fact] public async Task InstallAsync_WhenNameIsMissing_ShouldReturnPackageInvalidError() { // Arrange byte[] archive = _themePackFixture.Create(name: string.Empty); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert AssertPackageInvalid(result, "name"); } [Fact] public async Task InstallAsync_WhenDescriptionIsMissing_ShouldReturnPackageInvalidError() { // Arrange byte[] archive = _themePackFixture.Create(description: string.Empty); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert AssertPackageInvalid(result, "description"); } [Fact] public async Task InstallAsync_WhenAuthorIsMissing_ShouldReturnPackageInvalidError() { // Arrange byte[] archive = _themePackFixture.Create(author: string.Empty); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert AssertPackageInvalid(result, "author"); } [Fact] public async Task InstallAsync_WhenVersionIsMissing_ShouldReturnPackageInvalidError() { // Arrange byte[] archive = _themePackFixture.Create(version: string.Empty); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert AssertPackageInvalid(result, "version"); } [Fact] public async Task InstallAsync_WhenVersionIsNotSemanticVersion_ShouldReturnPackageInvalidError() { // Arrange byte[] archive = _themePackFixture.Create(version: "1.0"); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert AssertPackageInvalid(result, "semantic version"); } [Fact] public async Task InstallAsync_WhenManifestDeclaresNoTemplates_ShouldInstallSuccessfully() { // Arrange byte[] archive = _themePackFixture.Create(templates: new Dictionary(StringComparer.OrdinalIgnoreCase)); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsSuccess); } [Fact] public async Task InstallAsync_WhenManifestDeclaresTooManyTemplates_ShouldReturnPackageInvalidError() { // Arrange Dictionary manyTemplates = new(StringComparer.OrdinalIgnoreCase); for (int index = 0; index < 33; index++) manyTemplates[$"template-{index}"] = $"templates/template-{index}.html"; byte[] archive = _themePackFixture.Create(templates: manyTemplates); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert AssertPackageInvalid(result, "at most 32"); } [Fact] public async Task InstallAsync_WhenTemplateKeyIsInvalid_ShouldReturnPackageInvalidError() { // Arrange Dictionary templates = new(StringComparer.OrdinalIgnoreCase) { ["default"] = "templates/default.html", ["Bad Key"] = "templates/bad-key.html" }; byte[] archive = _themePackFixture.Create(templates: templates); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert AssertPackageInvalid(result, "Template key"); } [Fact] public async Task InstallAsync_WhenTemplatePathIsOutsideTemplatesDirectory_ShouldReturnPackageInvalidError() { // Arrange string manifestJson = _themePackFixture.CreateManifestJson(templates: new Dictionary(StringComparer.OrdinalIgnoreCase) { ["default"] = "assets/not-a-template.html" }); byte[] archive = _themePackFixture.CreateArchive( new("theme.json", manifestJson), new("assets/not-a-template.html", DEFAULT_TEMPLATE)); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert AssertPackageInvalid(result, "under templates"); } [Fact] public async Task InstallAsync_WhenTemplateFileIsMissing_ShouldReturnPackageInvalidError() { // Arrange string manifestJson = _themePackFixture.CreateManifestJson(templates: new Dictionary(StringComparer.OrdinalIgnoreCase) { ["default"] = "templates/missing.html" }); byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", manifestJson)); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert AssertPackageInvalid(result, "missing file"); } [Fact] public async Task InstallAsync_WhenManifestLacksDefaultTemplate_ShouldInstallSuccessfully() { // Arrange Dictionary templates = new(StringComparer.OrdinalIgnoreCase) { ["home"] = "templates/home.html" }; byte[] archive = _themePackFixture.Create(templates: templates); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsSuccess); } [Fact] public async Task InstallAsync_WhenPreviewIsOutsideAssetsDirectory_ShouldReturnPackageInvalidError() { // Arrange byte[] archive = _themePackFixture.Create(preview: "templates/default.html"); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert AssertPackageInvalid(result, "preview"); } [Fact] public async Task InstallAsync_WhenPreviewFileIsMissing_ShouldReturnPackageInvalidError() { // Arrange byte[] archive = _themePackFixture.Create(preview: "assets/missing.png", includePreviewAsset: false); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert AssertPackageInvalid(result, "preview"); } [Fact] public async Task InstallAsync_WhenManifestIsNotValidJson_ShouldReturnInvalidJsonError() { // Arrange byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", "this is not json")); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Manifest.InvalidJson", result.FirstError.Code); } [Fact] public async Task InstallAsync_WhenManifestExceedsMaximumSize_ShouldReturnManifestTooLargeError() { // Arrange byte[] archive = _themePackFixture.Create(description: new string('a', 70 * 1024)); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Manifest.TooLarge", result.FirstError.Code); } [Fact] public async Task ReadManifestFromArchiveAsync_WhenArchiveIsValid_ShouldReturnManifest() { // Arrange string archivePath = Path.Combine(_testRootPath, "valid-theme.zip"); File.WriteAllBytes(archivePath, _themePackFixture.Create(themeId: "manifest-theme")); // Act Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); // Assert Assert.True(result.IsSuccess); Assert.Equal("manifest-theme", result.Value.Id); } [Fact] public async Task ReadManifestFromArchiveAsync_WhenManifestEntryIsMissing_ShouldReturnPackageInvalidError() { // Arrange string archivePath = Path.Combine(_testRootPath, "no-manifest.zip"); File.WriteAllBytes(archivePath, _themePackFixture.CreateArchive(new ThemeArchiveEntry("templates/default.html", DEFAULT_TEMPLATE))); // Act Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); Assert.Contains("missing theme.json", result.FirstError.Description); } [Fact] public async Task ReadManifestFromArchiveAsync_WhenManifestIsNotValidJson_ShouldReturnInvalidJsonError() { // Arrange string archivePath = Path.Combine(_testRootPath, "invalid-json.zip"); File.WriteAllBytes(archivePath, _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", "not json"))); // Act Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Manifest.InvalidJson", result.FirstError.Code); } [Fact] public async Task ReadManifestFromArchiveAsync_WhenArchiveIsNotAZip_ShouldReturnThemeArchiveNotReadable() { // Arrange string archivePath = Path.Combine(_testRootPath, "not-a-zip.zip"); File.WriteAllBytes(archivePath, Encoding.UTF8.GetBytes("plain text file")); // Act Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("ThemeArchiveNotReadable", result.FirstError.Description); } [Fact] public async Task ReadManifestFromArchiveAsync_WhenArchiveFileDoesNotExist_ShouldReturnThemeFilesUnreadable() { // Arrange string archivePath = Path.Combine(_testRootPath, "does-not-exist.zip"); // Act Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); } [Fact] public async Task DeleteAsync_WhenThemeIsInstalled_ShouldRemoveThemePack() { // Arrange await InstallValidThemeAsync(_themePackFixture.Create()); // Act Result result = await _sut.DeleteAsync("test-theme", CancellationToken.None); // Assert Assert.True(result.IsSuccess); Assert.False(_sut.HasThemePack("test-theme")); Assert.False(Directory.Exists(Path.Combine(_options.StoragePath, "test-theme"))); } [Fact] public async Task DeleteAsync_WhenThemeIsNotInstalled_ShouldReturnSuccess() { // Arrange // Nothing is installed. // Act Result result = await _sut.DeleteAsync("test-theme", CancellationToken.None); // Assert Assert.True(result.IsSuccess); } [Fact] public async Task LoadManifestAsync_WhenThemeIsNotInstalled_ShouldReturnThemeFilesUnreadable() { // Arrange // Nothing is installed. // Act Result result = await _sut.LoadManifestAsync("test-theme", CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); } [Fact] public async Task LoadManifestAsync_WhenThemeIsInstalled_ShouldReturnManifest() { // Arrange await InstallValidThemeAsync(_themePackFixture.Create(themeId: "loaded-theme")); // Act Result result = await _sut.LoadManifestAsync("loaded-theme", CancellationToken.None); // Assert Assert.True(result.IsSuccess); Assert.Equal("loaded-theme", result.Value.Id); Assert.Equal("Test Theme", result.Value.Name); } [Fact] public async Task GetTemplateAsync_WhenPageKeyHasExplicitManifestTemplate_ShouldReturnExplicitTemplate() { // Arrange byte[] archive = CreateThemeWithTemplates(); await InstallValidThemeAsync(archive); // Act Result result = await _sut.GetTemplateAsync("test-theme", "home", CancellationToken.None); // Assert Assert.True(result.IsSuccess); Assert.Equal(HOME_TEMPLATE, result.Value); } [Fact] public async Task GetTemplateAsync_WhenPageKeyHasNoExplicitTemplate_ShouldUseMirroredTemplate() { // Arrange byte[] archive = CreateThemeWithTemplates(); await InstallValidThemeAsync(archive); // Act Result result = await _sut.GetTemplateAsync("test-theme", "library", CancellationToken.None); // Assert Assert.True(result.IsSuccess); Assert.Equal(LIBRARY_TEMPLATE, result.Value); } [Fact] public async Task GetTemplateAsync_WhenMirroredTemplateIsMissing_ShouldWalkUpToParentScope() { // Arrange byte[] archive = CreateThemeWithTemplates(); await InstallValidThemeAsync(archive); // Act Result result = await _sut.GetTemplateAsync("test-theme", "library/book", CancellationToken.None); // Assert Assert.True(result.IsSuccess); Assert.Equal(LIBRARY_TEMPLATE, result.Value); } [Fact] public async Task GetTemplateAsync_WhenNoTemplateResolves_ShouldReturnThemeTemplateNotFound() { // Arrange byte[] archive = CreateThemeWithTemplates(); await InstallValidThemeAsync(archive); // Act Result result = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError); } [Theory] [InlineData("../secret")] // Parent scope traversal attempt. [InlineData("/etc/passwd")] // Rooted path attempt. [InlineData("templates//nested")] // Empty segment attempt. public async Task GetTemplateAsync_WhenPageKeyAttemptsToEscapeTheThemePack_ShouldReturnThemeTemplateNotFound(string pageKey) { // Arrange byte[] archive = CreateThemeWithTemplates(); await InstallValidThemeAsync(archive); // Act Result result = await _sut.GetTemplateAsync("test-theme", pageKey, CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError); } [Fact] public async Task GetTemplateAsync_WhenSharedLayoutTemplateIsMissing_ShouldReturnThemeTemplateNotFound() { // Arrange byte[] archive = CreateThemeWithTemplates(); await InstallValidThemeAsync(archive); // Act Result result = await _sut.GetTemplateAsync("test-theme", "shared/layout", CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError); } [Fact] public async Task GetTemplateAsync_WhenSharedNavMenuTemplateIsMissing_ShouldReturnThemeTemplateNotFound() { // Arrange byte[] archive = CreateThemeWithTemplates(); await InstallValidThemeAsync(archive); // Act Result result = await _sut.GetTemplateAsync("test-theme", "shared/nav-menu", CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError); } [Fact] public async Task GetTemplateAsync_WhenSharedNavMenuMirrorExists_ShouldReturnTheMirroredTemplate() { // Arrange const string NAV_TEMPLATE = "nav menu"; byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary { ["templates/shared/nav-menu.html"] = NAV_TEMPLATE }); await InstallValidThemeAsync(archive); // Act Result result = await _sut.GetTemplateAsync("test-theme", "shared/nav-menu", CancellationToken.None); // Assert Assert.True(result.IsSuccess); Assert.Equal(NAV_TEMPLATE, result.Value); } [Fact] public async Task GetTemplateAsync_WhenThemeIsNotInstalled_ShouldReturnThemeFilesUnreadable() { // Arrange // Nothing is installed. // Act Result result = await _sut.GetTemplateAsync("test-theme", "home", CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); } [Fact] public async Task GetTemplateAsync_WhenManifestTemplateFileWasRemoved_ShouldReturnPackageInvalidError() { // Arrange byte[] archive = CreateThemeWithTemplates(); await InstallValidThemeAsync(archive); File.Delete(Path.Combine(_options.StoragePath, "test-theme", "templates", "default.html")); // Act Result result = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); Assert.Contains("missing file", result.FirstError.Description); } [Fact] public async Task GetTemplateAsync_WhenMirroredTemplateFileWasRemoved_ShouldReturnThemeTemplateNotFound() { // Arrange byte[] archive = CreateThemeWithTemplates(); await InstallValidThemeAsync(archive); File.Delete(Path.Combine(_options.StoragePath, "test-theme", "templates", "library.html")); // Act Result result = await _sut.GetTemplateAsync("test-theme", "library/book", CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError); } [Fact] public async Task GetAssetAsync_WhenAssetExists_ShouldReturnFileBytesAndContentType() { // Arrange byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary { ["assets/style.css"] = "body { color: red; }" }); await InstallValidThemeAsync(archive); // Act Result result = await _sut.GetAssetAsync("test-theme", "assets/style.css", CancellationToken.None); // Assert Assert.True(result.IsSuccess); Assert.Equal("text/css", result.Value.ContentType); Assert.Equal("body { color: red; }", Encoding.UTF8.GetString(result.Value.Bytes)); } [Fact] public async Task GetAssetAsync_WhenAssetPathIsOutsideAssetsDirectory_ShouldReturnPackageInvalidError() { // Arrange byte[] archive = CreateThemeWithTemplates(); await InstallValidThemeAsync(archive); // Act Result result = await _sut.GetAssetAsync("test-theme", "templates/default.html", CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); } [Fact] public async Task GetAssetAsync_WhenAssetPathAttemptsTraversal_ShouldReturnPackageInvalidError() { // Arrange byte[] archive = _themePackFixture.Create(); await InstallValidThemeAsync(archive); // Act Result result = await _sut.GetAssetAsync("test-theme", "../secret.txt", CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); } [Fact] public async Task GetAssetAsync_WhenAssetFileIsMissing_ShouldReturnThemeFilesUnreadable() { // Arrange byte[] archive = _themePackFixture.Create(); await InstallValidThemeAsync(archive); // Act Result result = await _sut.GetAssetAsync("test-theme", "assets/missing.png", CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); } [Fact] public async Task GetAssetAsync_WhenAssetIsJavaScript_ShouldReturnJavaScriptContentType() { // Arrange byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary { ["assets/app.js"] = "console.log('hello');" }); await InstallValidThemeAsync(archive); // Act Result result = await _sut.GetAssetAsync("test-theme", "assets/app.js", CancellationToken.None); // Assert Assert.True(result.IsSuccess); Assert.Equal("application/javascript", result.Value.ContentType); } [Fact] public async Task BuildArchiveAsync_WhenThemeIsInstalled_ShouldReturnDownloadableZipArchive() { // Arrange byte[] archive = _themePackFixture.Create(); await InstallValidThemeAsync(archive); // Act Result result = await _sut.BuildArchiveAsync("test-theme", CancellationToken.None); // Assert Assert.True(result.IsSuccess); Assert.Equal("test-theme.zip", result.Value.FileName); Assert.Equal("application/zip", result.Value.ContentType); using MemoryStream stream = new(result.Value.Bytes); using ZipArchive rebuiltArchive = new(stream, ZipArchiveMode.Read); Assert.Contains(rebuiltArchive.Entries, entry => entry.FullName == "theme.json"); Assert.Contains(rebuiltArchive.Entries, entry => entry.FullName == "templates/default.html"); } [Fact] public async Task BuildArchiveAsync_WhenThemeIsNotInstalled_ShouldReturnThemeFilesUnreadable() { // Arrange // Nothing is installed. // Act Result result = await _sut.BuildArchiveAsync("test-theme", CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); } [Fact] public async Task RestoreBundledThemeAsync_WhenBundledArchiveMatchesThemeId_ShouldInstallTheme() { // Arrange string bundledPath = Path.Combine(_testRootPath, "bundled"); Directory.CreateDirectory(bundledPath); File.WriteAllBytes(Path.Combine(bundledPath, "bundled-theme.zip"), _themePackFixture.Create(themeId: "bundled-theme")); // Act Result result = await _sut.RestoreBundledThemeAsync("bundled-theme", CancellationToken.None); // Assert Assert.True(result.IsSuccess); Assert.True(_sut.HasThemePack("bundled-theme")); } [Fact] public async Task RestoreBundledThemeAsync_WhenNoBundledArchiveMatches_ShouldReturnThemeFilesUnreadable() { // Arrange string bundledPath = Path.Combine(_testRootPath, "bundled"); Directory.CreateDirectory(bundledPath); File.WriteAllBytes(Path.Combine(bundledPath, "other-theme.zip"), _themePackFixture.Create(themeId: "other-theme")); // Act Result result = await _sut.RestoreBundledThemeAsync("bundled-theme", CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); } [Fact] public async Task RestoreBundledThemeAsync_WhenBundledArchiveManifestIsInvalid_ShouldSkipArchiveAndReturnThemeFilesUnreadable() { // Arrange string bundledPath = Path.Combine(_testRootPath, "bundled"); Directory.CreateDirectory(bundledPath); File.WriteAllBytes(Path.Combine(bundledPath, "broken.zip"), _themePackFixture.CreateArchive(new ThemeArchiveEntry("templates/default.html", DEFAULT_TEMPLATE))); // Act Result result = await _sut.RestoreBundledThemeAsync("bundled-theme", CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); Assert.False(_sut.HasThemePack("bundled-theme")); } [Fact] public async Task InstallAsync_WhenArchiveContainsAllowedDirectoryEntries_ShouldInstallSuccessfully() { // Arrange string manifestJson = _themePackFixture.CreateManifestJson(); byte[] archive = _themePackFixture.CreateArchive( new("templates/", string.Empty), new("theme.json", manifestJson), new("templates/default.html", DEFAULT_TEMPLATE), new("assets/preview.png", "preview-image-bytes")); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsSuccess); Assert.True(_sut.HasThemePack("test-theme")); } [Fact] public async Task InstallAsync_WhenArchiveContainsDisallowedDirectoryEntry_ShouldReturnPackageInvalidError() { // Arrange byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("notes/", string.Empty)); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); Assert.Contains("not allowed", result.FirstError.Description); } [Fact] public async Task InstallAsync_WhenArchiveDoesNotContainThemeJson_ShouldReturnPackageInvalidError() { // Arrange byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("templates/default.html", DEFAULT_TEMPLATE)); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); Assert.Contains("theme.json", result.FirstError.Description); } [Fact] public async Task InstallAsync_WhenTemplatePathFailsNormalization_ShouldReturnPackageInvalidError() { // Arrange string manifestJson = _themePackFixture.CreateManifestJson(templates: new Dictionary(StringComparer.OrdinalIgnoreCase) { ["default"] = "templates/../../escape.html" }); byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", manifestJson)); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert AssertPackageInvalid(result, "Theme path segment"); } [Fact] public async Task InstallAsync_WhenPreviewPathFailsNormalization_ShouldReturnPackageInvalidError() { // Arrange string manifestJson = _themePackFixture.CreateManifestJson(preview: "../../outside.png"); byte[] archive = _themePackFixture.CreateArchive( new("theme.json", manifestJson), new("templates/default.html", DEFAULT_TEMPLATE)); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert AssertPackageInvalid(result, "Theme path segment"); } [Fact] public async Task InstallAsync_WhenManifestContainsNullLiteral_ShouldReturnInvalidJsonError() { // Arrange byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", "null")); // Act Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Manifest.InvalidJson", result.FirstError.Code); Assert.Contains("no manifest object", result.FirstError.Description); } [Fact] public async Task InstallAsync_WhenStorageRootCannotBeCreated_ShouldReturnThemeFilesUnreadable() { // Arrange string blockedRootPath = Path.Combine(_testRootPath, "blocked-storage"); File.WriteAllText(blockedRootPath, "a file occupies the storage root path"); ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( storagePath: blockedRootPath, bundledThemesPath: Path.Combine(_testRootPath, "bundled"), defaultThemeId: "nemera-default", maxArchiveBytes: 8 * 1024 * 1024, maxExpandedBytes: 24 * 1024 * 1024, maxSingleFileBytes: 6 * 1024 * 1024, maxEntries: 250); ThemeService sut = CreateSut(options); byte[] archive = _themePackFixture.Create(); // Act Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); } [Fact] public async Task InstallAsync_WhenStagingDirectoryContainsStaleEntries_ShouldRemoveThemBeforeInstalling() { // Arrange Directory.CreateDirectory(_options.StoragePath); Directory.CreateDirectory(Path.Combine(_options.StoragePath, ".staging")); File.WriteAllText(Path.Combine(_options.StoragePath, ".staging", "stale.txt"), "stale"); Directory.CreateDirectory(Path.Combine(_options.StoragePath, ".staging", "old")); File.WriteAllText(Path.Combine(_options.StoragePath, ".staging", "old", "inner.txt"), "stale"); byte[] archive = _themePackFixture.Create(); // Act await InstallValidThemeAsync(archive); // Assert Assert.True(_sut.HasThemePack("test-theme")); Assert.False(File.Exists(Path.Combine(_options.StoragePath, ".staging", "stale.txt"))); Assert.False(Directory.Exists(Path.Combine(_options.StoragePath, ".staging", "old"))); } [Fact] public async Task LoadManifestAsync_WhenThemeDirectoryExistsButManifestWasRemoved_ShouldReturnMissingManifestError() { // Arrange await InstallValidThemeAsync(_themePackFixture.Create(themeId: "removed-manifest-theme")); File.Delete(Path.Combine(_options.StoragePath, "removed-manifest-theme", "theme.json")); // Act Result result = await _sut.LoadManifestAsync("removed-manifest-theme", CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); Assert.Contains("missing theme.json", result.FirstError.Description); } [Fact] public async Task ReadManifestFromArchiveAsync_WhenManifestContainsNullLiteral_ShouldReturnInvalidJsonError() { // Arrange string archivePath = Path.Combine(_testRootPath, "null-manifest.zip"); File.WriteAllBytes(archivePath, _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", "null"))); // Act Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("Theme.Manifest.InvalidJson", result.FirstError.Code); Assert.Contains("no manifest object", result.FirstError.Description); } [Fact] public async Task RestoreBundledThemeAsync_WhenThemeDestinationIsBlocked_ShouldReturnThemeFilesUnreadable() { // Arrange string bundledPath = Path.Combine(_testRootPath, "bundled"); Directory.CreateDirectory(bundledPath); File.WriteAllBytes(Path.Combine(bundledPath, "restore-blocked.zip"), _themePackFixture.Create(themeId: "restore-blocked")); Directory.CreateDirectory(_options.StoragePath); File.WriteAllText(Path.Combine(_options.StoragePath, "restore-blocked"), "blocked"); // Act Result result = await _sut.RestoreBundledThemeAsync("restore-blocked", CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); Assert.False(_sut.HasThemePack("restore-blocked")); } [Fact] public void Constructor_WhenConfiguredPathsAreRelative_ShouldResolveThemAgainstTheBaseDirectory() { // Arrange ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( storagePath: Path.Combine(_testRootPath, "themes"), bundledThemesPath: Path.Combine(_testRootPath, "bundled"), defaultThemeId: "nemera-default", maxArchiveBytes: 8 * 1024 * 1024, maxExpandedBytes: 24 * 1024 * 1024, maxSingleFileBytes: 6 * 1024 * 1024, maxEntries: 250); options.StoragePath = $"relative-themes-{Guid.NewGuid():N}"; options.BundledThemesPath = $"relative-bundled-{Guid.NewGuid():N}"; // Act ThemeService sut = CreateSut(options); // Assert Assert.False(sut.HasThemePack("not-installed")); } /// /// 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. /// /// The created theme pack ZIP archive. private byte[] CreateThemeWithTemplates() { Dictionary templates = new(StringComparer.OrdinalIgnoreCase) { ["default"] = "templates/default.html", ["home"] = "templates/home.html" }; return _themePackFixture.Create( templates: templates, additionalFiles: new Dictionary { ["templates/library.html"] = LIBRARY_TEMPLATE }); } /// /// Installs the provided theme archive using the provided service and asserts that the install succeeds. /// /// The theme pack ZIP archive to install. /// The service to install with, defaults to the shared system under test. /// The task representing the asynchronous operation. private async Task InstallValidThemeAsync(byte[] archive, ThemeService? service = null) { ThemeService themeService = service ?? _sut; using MemoryStream stream = new(archive); Result result = await themeService.InstallAsync(stream, CancellationToken.None); Assert.True(result.IsSuccess, result.Match( success => string.Empty, errors => $"Expected a successful install but got: {errors.First().Code}: {errors.First().Description}")); } /// /// Asserts that the result is a package invalid failure whose description contains the provided fragment. /// /// The result to assert on. /// The fragment the error description must contain. private static void AssertPackageInvalid(Result result, string expectedDescriptionFragment) { Assert.True(result.IsFailure); Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); Assert.Contains(expectedDescriptionFragment, result.FirstError.Description); } /// /// Creates a instance using the provided options. /// /// The theme engine options to configure the service with. /// The created service. private static ThemeService CreateSut(ThemeEngineOptionsDto options) { ILogger logger = Substitute.For>(); 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); } }