diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/Management/LibraryProviderSelectionDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/Management/LibraryProviderSelectionDtoFixture.cs
new file mode 100644
index 00000000..e4181a9c
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/Management/LibraryProviderSelectionDtoFixture.cs
@@ -0,0 +1,43 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DTO.MediaLibrary.Management;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class LibraryProviderSelectionDtoFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the plugin providing the provider or reader.
+ /// Whether the provider or reader is enabled.
+ /// Whether the choice carries an enabled state. When , the enabled state is .
+ /// The created .
+ public LibraryProviderSelectionDto Create(
+ Guid? pluginId = null,
+ bool isEnabled = true,
+ bool includeIsEnabled = true)
+ {
+ return new LibraryProviderSelectionDto(
+ pluginId ?? Guid.NewGuid(),
+ includeIsEnabled ? isEnabled : null);
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// The number of elements to create.
+ /// The created list.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs
index f773e3b5..239fb080 100644
--- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs
@@ -32,6 +32,9 @@ public class AddLibraryCommandFixture
/// Optional. Whether the consumption progress of the media library items should be tracked, or not.
/// Optional. The percentage of a media library item that must be consumed for its session to be considered completed.
/// Optional. The ordered parts of the path template of the media library.
+ /// Optional. The choices made for the metadata providers of the media library.
+ /// Optional. The choices made for the artwork providers of the media library.
+ /// Optional. The choices made for the book readers of the media library.
/// The created command.
public AddLibraryCommand Create(
string? title = null,
@@ -46,7 +49,10 @@ public class AddLibraryCommandFixture
bool isContentOnSsd = false,
bool? shouldTrackConsumptionProgress = null,
int? completionThresholdPercentage = null,
- LibraryPathTemplatePartDto[]? pathTemplateParts = null)
+ LibraryPathTemplatePartDto[]? pathTemplateParts = null,
+ LibraryProviderSelectionDto[]? metadataProviders = null,
+ LibraryProviderSelectionDto[]? artworkProviders = null,
+ LibraryProviderSelectionDto[]? bookReaders = null)
{
return new Faker()
.CustomInstantiator(f => new AddLibraryCommand(
@@ -62,6 +68,9 @@ public class AddLibraryCommandFixture
false,
shouldTrackConsumptionProgress,
completionThresholdPercentage,
+ null,
+ null,
+ null,
null
))
.RuleFor(x => x.Title, f => title ?? f.Lorem.Word())
@@ -75,6 +84,9 @@ public class AddLibraryCommandFixture
.RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan)
.RuleFor(x => x.IsContentOnSsd, isContentOnSsd)
.RuleFor(x => x.PathTemplateParts, pathTemplateParts)
+ .RuleFor(x => x.MetadataProviders, metadataProviders)
+ .RuleFor(x => x.ArtworkProviders, artworkProviders)
+ .RuleFor(x => x.BookReaders, bookReaders)
.Generate();
}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs
index 84bb39e0..510acaea 100644
--- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs
@@ -21,7 +21,6 @@ public class UpdateLibraryCommandFixture
/// Creates a random valid command to update a media library.
///
/// Optional. The Id of the media library.
- /// Optional. The Id of the user owning the media library.
/// Optional. The title of the media library.
/// Optional. The type of the media library.
/// Optional. The content locations of the media library.
@@ -35,10 +34,12 @@ public class UpdateLibraryCommandFixture
/// Optional. Whether the consumption progress of the media library items should be tracked, or not.
/// Optional. The percentage of a media library item that must be consumed for its session to be considered completed.
/// Optional. The ordered parts of the path template of the media library.
+ /// Optional. The choices made for the metadata providers of the media library.
+ /// Optional. The choices made for the artwork providers of the media library.
+ /// Optional. The choices made for the book readers of the media library.
/// The created command.
public UpdateLibraryCommand Create(
Guid? id = null,
- Guid? ownerId = null,
string? title = null,
string? libraryType = null,
string[]? contentLocations = null,
@@ -51,11 +52,13 @@ public class UpdateLibraryCommandFixture
bool isContentOnSsd = false,
bool? shouldTrackConsumptionProgress = null,
int? completionThresholdPercentage = null,
- LibraryPathTemplatePartDto[]? pathTemplateParts = null)
+ LibraryPathTemplatePartDto[]? pathTemplateParts = null,
+ LibraryProviderSelectionDto[]? metadataProviders = null,
+ LibraryProviderSelectionDto[]? artworkProviders = null,
+ LibraryProviderSelectionDto[]? bookReaders = null)
{
return new Faker()
.CustomInstantiator(f => new UpdateLibraryCommand(
- default,
default,
default!,
default!,
@@ -69,10 +72,12 @@ public class UpdateLibraryCommandFixture
false,
shouldTrackConsumptionProgress,
completionThresholdPercentage,
+ null,
+ null,
+ null,
null
))
.RuleFor(x => x.Id, id ?? Guid.NewGuid())
- .RuleFor(x => x.OwnerId, ownerId ?? Guid.NewGuid())
.RuleFor(x => x.Title, f => title ?? f.Lorem.Word())
.RuleFor(x => x.LibraryType, f => libraryType ?? f.Random.Enum().ToString())
.RuleFor(x => x.ContentLocations, f => contentLocations ?? [f.System.DirectoryPath(), f.System.DirectoryPath(), f.System.DirectoryPath()])
@@ -84,6 +89,9 @@ public class UpdateLibraryCommandFixture
.RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan)
.RuleFor(x => x.IsContentOnSsd, isContentOnSsd)
.RuleFor(x => x.PathTemplateParts, pathTemplateParts)
+ .RuleFor(x => x.MetadataProviders, metadataProviders)
+ .RuleFor(x => x.ArtworkProviders, artworkProviders)
+ .RuleFor(x => x.BookReaders, bookReaders)
.Generate();
}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandFixture.cs
deleted file mode 100644
index 42ecdbc6..00000000
--- a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandFixture.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Bogus;
-using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-#endregion
-
-namespace Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
-
-///
-/// Fixture class for the class.
-///
-[ExcludeFromCodeCoverage]
-public class ReorderLibraryArtworkProvidersCommandFixture
-{
- ///
- /// Creates a random valid command to reorder the artwork providers of a media library.
- ///
- /// Optional. The Id of the media library whose artwork providers are reordered.
- /// Optional. The plugin Ids in the new order.
- /// The created command.
- public ReorderLibraryArtworkProvidersCommand Create(
- Guid? libraryId = null,
- IReadOnlyList? pluginIds = null)
- {
- return new Faker()
- .CustomInstantiator(f => new ReorderLibraryArtworkProvidersCommand(
- default,
- default!))
- .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid())
- .RuleFor(x => x.PluginIds, f => pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()])
- .Generate();
- }
-
- ///
- /// Creates a list of .
- ///
- /// The number of elements to create.
- /// The created list.
- public List CreateMany(int count = 3)
- {
- return [.. Enumerable.Range(0, count).Select(_ => Create())];
- }
-}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandFixture.cs
deleted file mode 100644
index 6855acd8..00000000
--- a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandFixture.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Bogus;
-using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-#endregion
-
-namespace Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
-
-///
-/// Fixture class for the class.
-///
-[ExcludeFromCodeCoverage]
-public class ReorderLibraryMetadataProvidersCommandFixture
-{
- ///
- /// Creates a random valid command to reorder the metadata providers of a media library.
- ///
- /// Optional. The Id of the media library whose metadata providers are reordered.
- /// Optional. The plugin Ids in the new order.
- /// The created command.
- public ReorderLibraryMetadataProvidersCommand Create(Guid? libraryId = null, IReadOnlyList? pluginIds = null)
- {
- return new Faker()
- .CustomInstantiator(f => new ReorderLibraryMetadataProvidersCommand(
- default,
- default!))
- .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid())
- .RuleFor(x => x.PluginIds, f => pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()])
- .Generate();
- }
-
- ///
- /// Creates a list of .
- ///
- /// The number of elements to create.
- /// The created list.
- public List CreateMany(int count = 3)
- {
- return [.. Enumerable.Range(0, count).Select(_ => Create())];
- }
-}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandFixture.cs
deleted file mode 100644
index db917fec..00000000
--- a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandFixture.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Bogus;
-using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-#endregion
-
-namespace Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
-
-///
-/// Fixture class for the class.
-///
-[ExcludeFromCodeCoverage]
-public class SetLibraryArtworkProviderEnabledCommandFixture
-{
- ///
- /// Creates a random valid command to enable or disable an artwork provider for a media library.
- ///
- /// Optional. The Id of the media library whose artwork provider is enabled or disabled.
- /// Optional. The Id of the plugin providing the artwork.
- /// Whether the artwork provider should be enabled for the media library.
- /// The created command.
- public SetLibraryArtworkProviderEnabledCommand Create(
- Guid? libraryId = null,
- Guid? pluginId = null,
- bool isEnabled = true)
- {
- return new Faker()
- .CustomInstantiator(f => new SetLibraryArtworkProviderEnabledCommand(
- default,
- default,
- true))
- .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid())
- .RuleFor(x => x.PluginId, pluginId ?? Guid.NewGuid())
- .RuleFor(x => x.IsEnabled, isEnabled)
- .Generate();
- }
-
- ///
- /// Creates a list of .
- ///
- /// The number of elements to create.
- /// The created list.
- public List CreateMany(int count = 3)
- {
- return [.. Enumerable.Range(0, count).Select(_ => Create())];
- }
-}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandFixture.cs
deleted file mode 100644
index ef39d0f1..00000000
--- a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandFixture.cs
+++ /dev/null
@@ -1,41 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-#endregion
-
-namespace Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
-
-///
-/// Fixture class for the class.
-///
-[ExcludeFromCodeCoverage]
-public class SetLibraryBookReaderEnabledCommandFixture
-{
- ///
- /// Creates a random valid command to enable or disable a book reader for a media library.
- ///
- /// Optional. The Id of the media library whose book reader is enabled or disabled.
- /// Optional. The unique identifier of the plugin providing the book reader.
- /// Optional. Whether the book reader should be enabled for the media library.
- /// The created .
- public SetLibraryBookReaderEnabledCommand Create(
- Guid? libraryId = null,
- Guid? pluginId = null,
- bool? isEnabled = null)
- {
- return new SetLibraryBookReaderEnabledCommand(libraryId ?? Guid.NewGuid(), pluginId ?? Guid.NewGuid(), isEnabled ?? true);
- }
-
- ///
- /// Creates a list of .
- ///
- /// The number of elements to create.
- /// The created list.
- public List CreateMany(int count = 3)
- {
- return [.. Enumerable.Range(0, count).Select(_ => Create())];
- }
-}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandFixture.cs
deleted file mode 100644
index c640fb2c..00000000
--- a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandFixture.cs
+++ /dev/null
@@ -1,47 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Bogus;
-using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-#endregion
-
-namespace Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
-
-///
-/// Fixture class for the class.
-///
-[ExcludeFromCodeCoverage]
-public class SetLibraryMetadataProviderEnabledCommandFixture
-{
- ///
- /// Creates a random valid command to enable or disable a metadata provider for a media library.
- ///
- /// Optional. The Id of the media library whose metadata provider is enabled or disabled.
- /// Optional. The Id of the plugin providing the metadata.
- /// Whether the metadata provider should be enabled for the media library.
- /// The created command.
- public SetLibraryMetadataProviderEnabledCommand Create(Guid? libraryId = null, Guid? pluginId = null, bool isEnabled = true)
- {
- return new Faker()
- .CustomInstantiator(f => new SetLibraryMetadataProviderEnabledCommand(
- default,
- default,
- true))
- .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid())
- .RuleFor(x => x.PluginId, pluginId ?? Guid.NewGuid())
- .RuleFor(x => x.IsEnabled, isEnabled)
- .Generate();
- }
-
- ///
- /// Creates a list of .
- ///
- /// The number of elements to create.
- /// The created list.
- public List CreateMany(int count = 3)
- {
- return [.. Enumerable.Range(0, count).Select(_ => Create())];
- }
-}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryFixture.cs
new file mode 100644
index 00000000..85c9fb5d
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersQueryFixture.cs
@@ -0,0 +1,35 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeArtworkProviders;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeArtworkProvidersQueryFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The media library type whose available artwork providers are retrieved.
+ /// The created .
+ public GetLibraryTypeArtworkProvidersQuery Create(string? libraryType = null)
+ {
+ return new GetLibraryTypeArtworkProvidersQuery(libraryType ?? "Book");
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// The number of elements to create.
+ /// The created list.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryFixture.cs
new file mode 100644
index 00000000..55779a76
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersQueryFixture.cs
@@ -0,0 +1,35 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeBookReaders;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeBookReadersQueryFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The media library type whose available book readers are retrieved.
+ /// The created .
+ public GetLibraryTypeBookReadersQuery Create(string? libraryType = null)
+ {
+ return new GetLibraryTypeBookReadersQuery(libraryType ?? "Book");
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// The number of elements to create.
+ /// The created list.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryFixture.cs
new file mode 100644
index 00000000..50624d95
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersQueryFixture.cs
@@ -0,0 +1,35 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeMetadataProviders;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeMetadataProvidersQueryFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The media library type whose available metadata providers are retrieved.
+ /// The created .
+ public GetLibraryTypeMetadataProvidersQuery Create(string? libraryType = null)
+ {
+ return new GetLibraryTypeMetadataProvidersQuery(libraryType ?? "Book");
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// The number of elements to create.
+ /// The created list.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs
index c705b5a7..837b1bf3 100644
--- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs
@@ -32,6 +32,9 @@ public class AddLibraryRequestFixture
/// Optional. Whether the consumption progress of the media library items should be tracked, or not.
/// Optional. The percentage of a media library item that must be consumed for its session to be considered completed.
/// Optional. The ordered parts of the path template of the media library.
+ /// Optional. The choices made for the metadata providers of the media library.
+ /// Optional. The choices made for the artwork providers of the media library.
+ /// Optional. The choices made for the book readers of the media library.
/// The created .
public AddLibraryRequest Create(
string? title = null,
@@ -46,7 +49,10 @@ public class AddLibraryRequestFixture
bool? isContentOnSsd = null,
bool? shouldTrackConsumptionProgress = null,
int? completionThresholdPercentage = null,
- LibraryPathTemplatePartRequest[]? pathTemplateParts = null)
+ LibraryPathTemplatePartRequest?[]? pathTemplateParts = null,
+ LibraryProviderSelectionRequest?[]? metadataProviders = null,
+ LibraryProviderSelectionRequest?[]? artworkProviders = null,
+ LibraryProviderSelectionRequest?[]? bookReaders = null)
{
return new AddLibraryRequest(
title ?? _faker.Commerce.Department(),
@@ -61,7 +67,10 @@ public class AddLibraryRequestFixture
isContentOnSsd ?? false,
shouldTrackConsumptionProgress,
completionThresholdPercentage,
- pathTemplateParts
+ pathTemplateParts,
+ metadataProviders,
+ artworkProviders,
+ bookReaders
);
}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/LibraryProviderSelectionRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/LibraryProviderSelectionRequestFixture.cs
new file mode 100644
index 00000000..c8787577
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/LibraryProviderSelectionRequestFixture.cs
@@ -0,0 +1,43 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.Requests.MediaLibrary.Management;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class LibraryProviderSelectionRequestFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the plugin providing the provider or reader.
+ /// Whether the provider or reader is enabled.
+ /// Whether the choice carries an enabled state. When , the enabled state is .
+ /// The created .
+ public LibraryProviderSelectionRequest Create(
+ Guid? pluginId = null,
+ bool isEnabled = true,
+ bool includeIsEnabled = true)
+ {
+ return new LibraryProviderSelectionRequest(
+ pluginId ?? Guid.NewGuid(),
+ includeIsEnabled ? isEnabled : null);
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// The number of elements to create.
+ /// The created list.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs
index 44208473..423d02a8 100644
--- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs
@@ -21,7 +21,6 @@ public class UpdateLibraryRequestFixture
/// Creates a random valid .
///
/// Optional. The Id of the media library to update.
- /// Optional. The Id of the user owning the media library.
/// Optional. The title of the media library.
/// Optional. The type of the media library.
/// Optional. The file system paths of the media library content directories.
@@ -35,10 +34,12 @@ public class UpdateLibraryRequestFixture
/// Optional. Whether the consumption progress of the media library items should be tracked, or not.
/// Optional. The percentage of a media library item that must be consumed for its session to be considered completed.
/// Optional. The ordered parts of the path template of the media library.
+ /// Optional. The choices made for the metadata providers of the media library.
+ /// Optional. The choices made for the artwork providers of the media library.
+ /// Optional. The choices made for the book readers of the media library.
/// The created .
public UpdateLibraryRequest Create(
Guid? id = null,
- Guid? userId = null,
string? title = null,
string? libraryType = null,
string[]? contentLocations = null,
@@ -51,11 +52,13 @@ public class UpdateLibraryRequestFixture
bool? isContentOnSsd = null,
bool? shouldTrackConsumptionProgress = null,
int? completionThresholdPercentage = null,
- LibraryPathTemplatePartRequest[]? pathTemplateParts = null)
+ LibraryPathTemplatePartRequest?[]? pathTemplateParts = null,
+ LibraryProviderSelectionRequest?[]? metadataProviders = null,
+ LibraryProviderSelectionRequest?[]? artworkProviders = null,
+ LibraryProviderSelectionRequest?[]? bookReaders = null)
{
return new UpdateLibraryRequest(
id ?? _faker.Random.Guid(),
- userId ?? _faker.Random.Guid(),
title ?? _faker.Commerce.Department(),
libraryType ?? "EBook",
contentLocations ?? [_faker.System.DirectoryPath()],
@@ -68,7 +71,10 @@ public class UpdateLibraryRequestFixture
isContentOnSsd ?? false,
shouldTrackConsumptionProgress,
completionThresholdPercentage,
- pathTemplateParts
+ pathTemplateParts,
+ metadataProviders,
+ artworkProviders,
+ bookReaders
);
}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeArtworkProvidersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeArtworkProvidersRequestFixture.cs
new file mode 100644
index 00000000..d7e7605a
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeArtworkProvidersRequestFixture.cs
@@ -0,0 +1,35 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.Requests.Plugins;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeArtworkProvidersRequestFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The media library type whose available artwork providers are retrieved.
+ /// The created .
+ public GetLibraryTypeArtworkProvidersRequest Create(string? libraryType = null)
+ {
+ return new GetLibraryTypeArtworkProvidersRequest(libraryType ?? "Book");
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// The number of elements to create.
+ /// The created list.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeBookReadersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeBookReadersRequestFixture.cs
new file mode 100644
index 00000000..d542f775
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeBookReadersRequestFixture.cs
@@ -0,0 +1,35 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.Requests.Plugins;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeBookReadersRequestFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The media library type whose available book readers are retrieved.
+ /// The created .
+ public GetLibraryTypeBookReadersRequest Create(string? libraryType = null)
+ {
+ return new GetLibraryTypeBookReadersRequest(libraryType ?? "Book");
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// The number of elements to create.
+ /// The created list.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeMetadataProvidersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeMetadataProvidersRequestFixture.cs
new file mode 100644
index 00000000..18ba5f97
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryTypeMetadataProvidersRequestFixture.cs
@@ -0,0 +1,35 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.Requests.Plugins;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeMetadataProvidersRequestFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The media library type whose available metadata providers are retrieved.
+ /// The created .
+ public GetLibraryTypeMetadataProvidersRequest Create(string? libraryType = null)
+ {
+ return new GetLibraryTypeMetadataProvidersRequest(libraryType ?? "Book");
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// The number of elements to create.
+ /// The created list.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs
deleted file mode 100644
index 8c65fa86..00000000
--- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Bogus;
-using Lumina.Contracts.Requests.Plugins;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-#endregion
-
-namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-
-///
-/// Fixture class for the record.
-///
-[ExcludeFromCodeCoverage]
-public class ReorderLibraryArtworkProvidersRequestFixture
-{
- private readonly Faker _faker = new();
-
- ///
- /// Creates a random valid .
- ///
- /// Optional. The Id of the media library whose artwork providers are reordered.
- /// Optional. The plugin Ids in the new order.
- /// The created .
- public ReorderLibraryArtworkProvidersRequest Create(
- Guid? libraryId = null,
- IReadOnlyList? pluginIds = null)
- {
- return new ReorderLibraryArtworkProvidersRequest(
- libraryId ?? _faker.Random.Guid(),
- pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()]
- );
- }
-
- ///
- /// Creates a list of .
- ///
- /// The number of elements to create.
- /// The created list.
- public List CreateMany(int count = 3)
- {
- return [.. Enumerable.Range(0, count).Select(_ => Create())];
- }
-}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs
deleted file mode 100644
index a740a144..00000000
--- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Bogus;
-using Lumina.Contracts.Requests.Plugins;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-#endregion
-
-namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-
-///
-/// Fixture class for the record.
-///
-[ExcludeFromCodeCoverage]
-public class ReorderLibraryMetadataProvidersRequestFixture
-{
- private readonly Faker _faker = new();
-
- ///
- /// Creates a random valid .
- ///
- /// Optional. The Id of the media library whose metadata providers are reordered.
- /// Optional. The plugin Ids in the new order.
- /// The created .
- public ReorderLibraryMetadataProvidersRequest Create(
- Guid? libraryId = null,
- IReadOnlyList? pluginIds = null)
- {
- return new ReorderLibraryMetadataProvidersRequest(
- libraryId ?? _faker.Random.Guid(),
- pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()]
- );
- }
-
- ///
- /// Creates a list of .
- ///
- /// The number of elements to create.
- /// The created list.
- public List CreateMany(int count = 3)
- {
- return [.. Enumerable.Range(0, count).Select(_ => Create())];
- }
-}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs
deleted file mode 100644
index cd7f3dbb..00000000
--- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Bogus;
-using Lumina.Contracts.Requests.Plugins;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-#endregion
-
-namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-
-///
-/// Fixture class for the record.
-///
-[ExcludeFromCodeCoverage]
-public class SetLibraryArtworkProviderEnabledRequestFixture
-{
- private readonly Faker _faker = new();
-
- ///
- /// Creates a random valid .
- ///
- /// Optional. The Id of the media library whose artwork provider is enabled or disabled.
- /// Optional. The Id of the plugin providing the artwork.
- /// Optional. Whether the artwork provider should be enabled.
- /// The created .
- public SetLibraryArtworkProviderEnabledRequest Create(
- Guid? libraryId = null,
- Guid? pluginId = null,
- bool? isEnabled = null)
- {
- return new SetLibraryArtworkProviderEnabledRequest(
- libraryId ?? _faker.Random.Guid(),
- pluginId ?? _faker.Random.Guid(),
- isEnabled ?? _faker.Random.Bool()
- );
- }
-
- ///
- /// Creates a list of .
- ///
- /// The number of elements to create.
- /// The created list.
- public List CreateMany(int count = 3)
- {
- return [.. Enumerable.Range(0, count).Select(_ => Create())];
- }
-}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryBookReaderEnabledRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryBookReaderEnabledRequestFixture.cs
deleted file mode 100644
index 68cdb841..00000000
--- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryBookReaderEnabledRequestFixture.cs
+++ /dev/null
@@ -1,41 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Contracts.Requests.Plugins;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-#endregion
-
-namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-
-///
-/// Fixture class for the record.
-///
-[ExcludeFromCodeCoverage]
-public class SetLibraryBookReaderEnabledRequestFixture
-{
- ///
- /// Creates a random valid .
- ///
- /// Optional. The Id of the media library whose book reader is enabled or disabled.
- /// Optional. The unique identifier of the plugin providing the book reader.
- /// Optional. Whether the book reader should be enabled for the media library.
- /// The created .
- public SetLibraryBookReaderEnabledRequest Create(
- Guid? libraryId = null,
- Guid? pluginId = null,
- bool? isEnabled = null)
- {
- return new SetLibraryBookReaderEnabledRequest(libraryId ?? Guid.NewGuid(), pluginId ?? Guid.NewGuid(), isEnabled ?? true);
- }
-
- ///
- /// Creates a list of .
- ///
- /// The number of elements to create.
- /// The created list.
- public List CreateMany(int count = 3)
- {
- return [.. Enumerable.Range(0, count).Select(_ => Create())];
- }
-}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs
deleted file mode 100644
index 2e47ed9c..00000000
--- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Bogus;
-using Lumina.Contracts.Requests.Plugins;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-#endregion
-
-namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-
-///
-/// Fixture class for the record.
-///
-[ExcludeFromCodeCoverage]
-public class SetLibraryMetadataProviderEnabledRequestFixture
-{
- private readonly Faker _faker = new();
-
- ///
- /// Creates a random valid .
- ///
- /// Optional. The Id of the media library whose metadata provider is enabled or disabled.
- /// Optional. The Id of the plugin providing the metadata.
- /// Optional. Whether the metadata provider should be enabled.
- /// The created .
- public SetLibraryMetadataProviderEnabledRequest Create(
- Guid? libraryId = null,
- Guid? pluginId = null,
- bool? isEnabled = null)
- {
- return new SetLibraryMetadataProviderEnabledRequest(
- libraryId ?? _faker.Random.Guid(),
- pluginId ?? _faker.Random.Guid(),
- isEnabled ?? _faker.Random.Bool()
- );
- }
-
- ///
- /// Creates a list of .
- ///
- /// The number of elements to create.
- /// The created list.
- public List CreateMany(int count = 3)
- {
- return [.. Enumerable.Range(0, count).Select(_ => Create())];
- }
-}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs
index 4fcd5780..896eda2f 100644
--- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs
@@ -31,7 +31,6 @@ public class LibraryDtoFixture
return new LibraryDto
{
Id = id ?? Guid.NewGuid(),
- UserId = Guid.NewGuid(),
Title = title ?? _faker.Commerce.Department(),
LibraryType = libraryType ?? _faker.PickRandom("Book", "Video", "Photo"),
CoverImage = _faker.Image.PicsumUrl(),
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryProviderSelectionDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryProviderSelectionDtoFixture.cs
new file mode 100644
index 00000000..6f631a1f
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryProviderSelectionDtoFixture.cs
@@ -0,0 +1,48 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Presentation.Web.Common.DTO.Libraries;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
+
+///
+/// Fixture class for the class.
+///
+[ExcludeFromCodeCoverage]
+public class LibraryProviderSelectionDtoFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the plugin providing the provider or reader.
+ /// Optional. Whether the provider or reader is enabled.
+ /// Whether the choice carries an enabled state. When , the enabled state is .
+ /// The created .
+ public LibraryProviderSelectionDto Create(
+ Guid? pluginId = null,
+ bool? isEnabled = null,
+ bool includeIsEnabled = true)
+ {
+ return new LibraryProviderSelectionDto
+ {
+ PluginId = pluginId ?? Guid.NewGuid(),
+ IsEnabled = includeIsEnabled ? isEnabled ?? _faker.Random.Bool() : null
+ };
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// The number of elements to create.
+ /// The created list.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeArtworkProvidersRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeArtworkProvidersRequestFixture.cs
new file mode 100644
index 00000000..c93cdf6f
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeArtworkProvidersRequestFixture.cs
@@ -0,0 +1,36 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Requests.Library.Management;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeArtworkProvidersRequestFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The media library type whose available artwork providers are retrieved.
+ /// The created .
+ public GetLibraryTypeArtworkProvidersRequest Create(
+ string? libraryType = null)
+ {
+ return new GetLibraryTypeArtworkProvidersRequest(libraryType ?? "Book");
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// The number of elements to create.
+ /// The created list.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeBookReadersRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeBookReadersRequestFixture.cs
new file mode 100644
index 00000000..4acb383a
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeBookReadersRequestFixture.cs
@@ -0,0 +1,36 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Requests.Library.Management;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeBookReadersRequestFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The media library type whose available book readers are retrieved.
+ /// The created .
+ public GetLibraryTypeBookReadersRequest Create(
+ string? libraryType = null)
+ {
+ return new GetLibraryTypeBookReadersRequest(libraryType ?? "Book");
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// The number of elements to create.
+ /// The created list.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeMetadataProvidersRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeMetadataProvidersRequestFixture.cs
new file mode 100644
index 00000000..2634e21f
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryTypeMetadataProvidersRequestFixture.cs
@@ -0,0 +1,36 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Requests.Library.Management;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeMetadataProvidersRequestFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The media library type whose available metadata providers are retrieved.
+ /// The created .
+ public GetLibraryTypeMetadataProvidersRequest Create(
+ string? libraryType = null)
+ {
+ return new GetLibraryTypeMetadataProvidersRequest(libraryType ?? "Book");
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// The number of elements to create.
+ /// The created list.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs
deleted file mode 100644
index d0cb7a97..00000000
--- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Bogus;
-using Lumina.Presentation.Web.Common.Requests.Plugins;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-#endregion
-
-namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
-
-///
-/// Fixture class for the record.
-///
-[ExcludeFromCodeCoverage]
-public class ReorderLibraryArtworkProvidersRequestFixture
-{
- private readonly Faker _faker = new();
-
- ///
- /// Creates a new instance with randomized test data.
- ///
- /// Optional identifier of the media library.
- /// Optional plugin Ids in the new order.
- /// A configured instance.
- public ReorderLibraryArtworkProvidersRequest Create(
- Guid? libraryId = null,
- List? pluginIds = null)
- {
- return new ReorderLibraryArtworkProvidersRequest(
- LibraryId: libraryId ?? Guid.NewGuid(),
- PluginIds: pluginIds ?? [_faker.Random.Guid(), _faker.Random.Guid()]
- );
- }
-
- ///
- /// Creates multiple instances with randomized test data.
- ///
- /// Number of instances to create.
- /// List of configured instances.
- public List CreateMany(int count = 3)
- {
- return [.. Enumerable.Range(0, count).Select(_ => Create())];
- }
-}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs
deleted file mode 100644
index c52dcdfc..00000000
--- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Bogus;
-using Lumina.Presentation.Web.Common.Requests.Plugins;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-#endregion
-
-namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
-
-///
-/// Fixture class for the record.
-///
-[ExcludeFromCodeCoverage]
-public class ReorderLibraryMetadataProvidersRequestFixture
-{
- private readonly Faker _faker = new();
-
- ///
- /// Creates a new instance with randomized test data.
- ///
- /// Optional identifier of the media library.
- /// Optional plugin Ids in the new order.
- /// A configured instance.
- public ReorderLibraryMetadataProvidersRequest Create(
- Guid? libraryId = null,
- List? pluginIds = null)
- {
- return new ReorderLibraryMetadataProvidersRequest(
- LibraryId: libraryId ?? Guid.NewGuid(),
- PluginIds: pluginIds ?? [_faker.Random.Guid(), _faker.Random.Guid()]
- );
- }
-
- ///
- /// Creates multiple instances with randomized test data.
- ///
- /// Number of instances to create.
- /// List of configured instances.
- public List CreateMany(int count = 3)
- {
- return [.. Enumerable.Range(0, count).Select(_ => Create())];
- }
-}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetBookReaderEnabledRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetBookReaderEnabledRequestFixture.cs
deleted file mode 100644
index 3e1047c5..00000000
--- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetBookReaderEnabledRequestFixture.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Presentation.Web.Common.Requests.Plugins;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-#endregion
-
-namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
-
-///
-/// Fixture class for the record.
-///
-[ExcludeFromCodeCoverage]
-public class SetBookReaderEnabledRequestFixture
-{
- ///
- /// Creates a random valid .
- ///
- /// Optional. The Id of the media library whose book reader is enabled or disabled.
- /// Optional. The unique identifier of the plugin providing the book reader.
- /// Optional. Whether the book reader should be enabled for the media library.
- /// The created .
- public SetBookReaderEnabledRequest Create(
- Guid? libraryId = null,
- Guid? pluginId = null,
- bool? isEnabled = null)
- {
- return new SetBookReaderEnabledRequest(
- LibraryId: libraryId ?? Guid.NewGuid(),
- PluginId: pluginId ?? Guid.NewGuid(),
- IsEnabled: isEnabled ?? true
- );
- }
-
- ///
- /// Creates a list of .
- ///
- /// The number of elements to create.
- /// The created list.
- public List CreateMany(int count = 3)
- {
- return [.. Enumerable.Range(0, count).Select(_ => Create())];
- }
-}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs
deleted file mode 100644
index db568e49..00000000
--- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Bogus;
-using Lumina.Presentation.Web.Common.Requests.Plugins;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-#endregion
-
-namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
-
-///
-/// Fixture class for the record.
-///
-[ExcludeFromCodeCoverage]
-public class SetLibraryArtworkProviderEnabledRequestFixture
-{
- private readonly Faker _faker = new();
-
- ///
- /// Creates a new instance with randomized test data.
- ///
- /// Optional identifier of the media library.
- /// Optional identifier of the plugin.
- /// Optional value indicating whether the artwork provider is enabled.
- /// A configured instance.
- public SetLibraryArtworkProviderEnabledRequest Create(
- Guid? libraryId = null,
- Guid? pluginId = null,
- bool? isEnabled = null)
- {
- return new SetLibraryArtworkProviderEnabledRequest(
- LibraryId: libraryId ?? Guid.NewGuid(),
- PluginId: pluginId ?? Guid.NewGuid(),
- IsEnabled: isEnabled ?? _faker.Random.Bool()
- );
- }
-
- ///
- /// Creates multiple instances with randomized test data.
- ///
- /// Number of instances to create.
- /// List of configured instances.
- public List CreateMany(int count = 3)
- {
- return [.. Enumerable.Range(0, count).Select(_ => Create())];
- }
-}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs
deleted file mode 100644
index fdf26cb3..00000000
--- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Bogus;
-using Lumina.Presentation.Web.Common.Requests.Plugins;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-#endregion
-
-namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
-
-///
-/// Fixture class for the record.
-///
-[ExcludeFromCodeCoverage]
-public class SetLibraryMetadataProviderEnabledRequestFixture
-{
- private readonly Faker _faker = new();
-
- ///
- /// Creates a new instance with randomized test data.
- ///
- /// Optional identifier of the media library.
- /// Optional identifier of the plugin.
- /// Optional value indicating whether the metadata provider is enabled.
- /// A configured instance.
- public SetLibraryMetadataProviderEnabledRequest Create(
- Guid? libraryId = null,
- Guid? pluginId = null,
- bool? isEnabled = null)
- {
- return new SetLibraryMetadataProviderEnabledRequest(
- LibraryId: libraryId ?? Guid.NewGuid(),
- PluginId: pluginId ?? Guid.NewGuid(),
- IsEnabled: isEnabled ?? _faker.Random.Bool()
- );
- }
-
- ///
- /// Creates multiple instances with randomized test data.
- ///
- /// Number of instances to create.
- /// List of configured instances.
- public List CreateMany(int count = 3)
- {
- return [.. Enumerable.Range(0, count).Select(_ => Create())];
- }
-}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs
index da59de5a..c89d7987 100644
--- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs
@@ -1,11 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Seed;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Infrastructure.Core.Security;
using Microsoft.Extensions.DependencyInjection;
using System;
@@ -33,6 +35,8 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
PropertyNameCaseInsensitive = true
};
private readonly UserEntityFixture _userEntityFixture = new();
+ private readonly PermissionEntityFixture _permissionEntityFixture = new();
+ private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new();
private readonly LoginRequestFixture _loginRequestFixture = new();
///
@@ -43,17 +47,18 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
///
/// Creates an HTTP client with authentication headers and a test user
///
+ /// The permissions granted directly to the test user, if any.
/// An HTTP client configured with auth headers
- public async Task CreateAuthenticatedClientAsync()
+ public async Task CreateAuthenticatedClientAsync(params AuthorizationPermission[] permissions)
{
HttpClient client = CreateClient();
TestUsername = $"testuser_{Guid.NewGuid()}";
- // add the X-Forwarded-For header
+ // Add the X-Forwarded-For header.
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}");
- // perform authentication
- await CreateAndAuthenticateUser(client);
+ // Perform authentication.
+ await CreateAndAuthenticateUser(client, permissions);
return client;
}
@@ -62,20 +67,23 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
/// Creates and authenticates a test user.
///
/// The HTTP client to configure with auth.
+ /// The permissions granted directly to the test user.
/// The created user entity.
- private async Task CreateAndAuthenticateUser(HttpClient client)
+ private async Task CreateAndAuthenticateUser(HttpClient client, AuthorizationPermission[] permissions)
{
using IServiceScope scope = Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- // create test user
+ // Create test user, with the permissions granted directly to it.
UserEntity user = _userEntityFixture.Create(username: TestUsername!, password: _hashService.HashString("TestPass123!"));
user.TotpSecret = null;
+ foreach (AuthorizationPermission permission in permissions)
+ user.UserPermissions.Add(_userPermissionEntityFixture.Create(user, _permissionEntityFixture.Create(permissionName: permission, createdBy: user.Id)));
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
- // authenticate user
+ // Authenticate user.
LoginRequest loginRequest = _loginRequestFixture.Create(
username: user.Username,
password: "TestPass123!",
@@ -86,7 +94,7 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
string content = await loginResponse.Content.ReadAsStringAsync();
LoginResponse? result = JsonSerializer.Deserialize(content, _jsonOptions);
- // set auth header for subsequent requests
+ // Set auth header for subsequent requests.
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token);
return user;
@@ -101,11 +109,11 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
HttpClient client = CreateClient();
TestUsername = $"testuser_{Guid.NewGuid()}";
- // add the X-Forwarded-For header
+ // Add the X-Forwarded-For header.
client.DefaultRequestHeaders.Add("X-Forwarded-For",
$"192.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}");
- // create and authenticate admin user
+ // Create and authenticate admin user.
await CreateAndAuthenticateAdminUser(client);
return client;
@@ -122,20 +130,20 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
IDataSeedService dataSeedService = scope.ServiceProvider.GetRequiredService();
- // create test user
+ // Create test user.
UserEntity user = _userEntityFixture.Create(username: TestUsername!, password: _hashService.HashString("TestPass123!"));
user.TotpSecret = null;
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
- // set up admin permissions and roles
+ // Set up admin permissions and roles.
await dataSeedService.SetDefaultAuthorizationPermissionsAsync(user.Id, CancellationToken.None);
await dataSeedService.SetDefaultAuthorizationRolesAsync(user.Id, CancellationToken.None);
await dataSeedService.SetAdminRolePermissionsAsync(user.Id, CancellationToken.None);
await dataSeedService.SetAdminRoleToAdministratorAccount(user.Id, CancellationToken.None);
- // authenticate user
+ // Authenticate user.
LoginRequest loginRequest = _loginRequestFixture.Create(
username: user.Username,
password: "TestPass123!",
@@ -146,7 +154,7 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
string content = await loginResponse.Content.ReadAsStringAsync();
LoginResponse? result = JsonSerializer.Deserialize(content, _jsonOptions);
- // set auth header for subsequent requests
+ // Set auth header for subsequent requests.
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token);
return user;
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs
index e8f615d3..a4f62d7c 100644
--- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs
@@ -10,6 +10,7 @@ using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
+using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@@ -32,6 +33,7 @@ public class AddLibraryEndpointTests : IClassFixture candidate.Title == title));
}
+ [Fact]
+ public async Task AddLibrary_WhenAProviderChoiceNamesAnUnsupportedPlugin_ShouldReturnValidationProblemAndNotPersist()
+ {
+ // Arrange
+ string title = "Unsupported Provider Library";
+ AddLibraryRequest request = _addLibraryRequestFixture.Create(
+ title: title,
+ libraryType: "Book",
+ contentLocations: ["C:/Media"],
+ coverImage: null,
+ metadataProviders: [_libraryProviderSelectionRequestFixture.Create(isEnabled: true)]
+ );
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
+
+ // Assert
+ await AssertValidationProblemAsync(response, "PluginNotSupportedForLibraryType");
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
+ }
+
+ [Fact]
+ public async Task AddLibrary_WhenAProviderChoiceIsNull_ShouldReturnValidationProblemAndNotPersist()
+ {
+ // Arrange
+ string title = "Null Provider Choice Library";
+ AddLibraryRequest request = _addLibraryRequestFixture.Create(
+ title: title,
+ libraryType: "Book",
+ contentLocations: ["C:/Media"],
+ coverImage: null,
+ bookReaders: [null]
+ );
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
+
+ // Assert
+ await AssertValidationProblemAsync(response, "PluginIdCannotBeEmpty");
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
+ }
+
+ [Fact]
+ public async Task AddLibrary_WhenAPathTemplatePartIsNull_ShouldReturnValidationProblemAndNotPersist()
+ {
+ // Arrange
+ string title = "Null Path Template Part Library";
+ AddLibraryRequest request = _addLibraryRequestFixture.Create(
+ title: title,
+ libraryType: "Book",
+ contentLocations: ["C:/Media"],
+ coverImage: null,
+ pathTemplateParts: [null]
+ );
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
+
+ // Assert
+ await AssertValidationProblemAsync(response, "PathTemplatePartKindNotSupportedForLibraryType");
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
+ }
+
+ [Fact]
+ public async Task AddLibrary_WhenProviderPluginIdsAreDuplicated_ShouldReturnValidationProblemAndNotPersist()
+ {
+ // Arrange
+ string title = "Duplicated Provider Library";
+ Guid pluginId = Guid.NewGuid();
+ AddLibraryRequest request = _addLibraryRequestFixture.Create(
+ title: title,
+ libraryType: "Book",
+ contentLocations: ["C:/Media"],
+ coverImage: null,
+ bookReaders: [_libraryProviderSelectionRequestFixture.Create(pluginId: pluginId), _libraryProviderSelectionRequestFixture.Create(pluginId: pluginId, isEnabled: false)]
+ );
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
+
+ // Assert
+ await AssertValidationProblemAsync(response, "PluginIdsMustBeUnique");
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
+ }
+
+ [Fact]
+ public async Task AddLibrary_WhenProviderChoicesAreEmpty_ShouldCreateLibrary()
+ {
+ // Arrange
+ string title = "Empty Provider Choices Library";
+ AddLibraryRequest request = _addLibraryRequestFixture.Create(
+ title: title,
+ libraryType: "Book",
+ contentLocations: ["C:/Media"],
+ coverImage: null,
+ metadataProviders: [],
+ artworkProviders: [],
+ bookReaders: []
+ );
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.True(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
+ }
+
///
/// Asserts that carries the standard validation problem of the add library route.
///
@@ -395,12 +519,12 @@ public class AddLibraryEndpointTests : IClassFixture();
- // clear junction tables first
+ // Clear junction tables first.
await dbContext.Set().ExecuteDeleteAsync();
await dbContext.Set().ExecuteDeleteAsync();
await dbContext.Set().ExecuteDeleteAsync();
- // then clear main tables
+ // Then clear main tables.
await dbContext.Set().ExecuteDeleteAsync();
await dbContext.Set().ExecuteDeleteAsync();
await dbContext.Set().ExecuteDeleteAsync();
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs
index c55d61f2..0bf11ce0 100644
--- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.DeleteLibrary;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
@@ -54,7 +55,7 @@ public class DeleteLibraryEndpointTests : IClassFixture
public async Task InitializeAsync()
{
- _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ _client = await _apiFactory.CreateAuthenticatedClientAsync(AuthorizationPermission.CanCreateLibraries);
}
[Fact]
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs
index d73469a3..7ce5c05b 100644
--- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs
@@ -6,6 +6,7 @@ using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.UpdateLibrary;
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
@@ -41,6 +42,7 @@ public class UpdateLibraryEndpointTests : IClassFixture
/// Initializes a new instance of the class.
@@ -57,7 +59,7 @@ public class UpdateLibraryEndpointTests : IClassFixture
public async Task InitializeAsync()
{
- _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ _client = await _apiFactory.CreateAuthenticatedClientAsync(AuthorizationPermission.CanCreateLibraries);
}
[Fact]
@@ -69,7 +71,6 @@ public class UpdateLibraryEndpointTests : IClassFixture();
+ LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == libraryId);
+ Assert.NotNull(storedLibrary);
+ Assert.Equal("Original Title", storedLibrary!.Title);
+ }
+
+ [Fact]
+ public async Task UpdateLibrary_WhenProviderChoicesAreEmpty_ShouldUpdateTheLibrary()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = Guid.NewGuid();
+ await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
+ UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
+ id: libraryId,
+ title: "Updated Title",
+ libraryType: "EBook",
+ contentLocations: ["C:/Media"],
+ coverImage: null,
+ shouldTrackConsumptionProgress: true,
+ completionThresholdPercentage: 70,
+ metadataProviders: [],
+ artworkProviders: [],
+ bookReaders: []
+ );
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == libraryId);
+ Assert.NotNull(storedLibrary);
+ Assert.Equal("Updated Title", storedLibrary!.Title);
+ }
+
///
/// Asserts that carries the standard validation problem of the update library route.
///
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs
new file mode 100644
index 00000000..f8e83eea
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs
@@ -0,0 +1,112 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.Responses.Plugins;
+using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders;
+using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
+using Microsoft.AspNetCore.Http;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private HttpClient _client;
+ private readonly AuthenticatedLuminaApiFactory _apiFactory;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true,
+ Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
+ };
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetLibraryTypeArtworkProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Theory]
+ [InlineData("Book")]
+ [InlineData("music")] // The casing of the type is ignored.
+ public async Task GetLibraryTypeArtworkProviders_WhenLibraryTypeIsValid_ShouldReturnOkWithTheAvailableProviders(string libraryType)
+ {
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/artwork-providers/{libraryType}");
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ List? providers = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(providers);
+ // The test host loads no plugins, so no provider supports the type; every provider that is returned starts disabled.
+ Assert.All(providers!, provider => Assert.False(provider.IsEnabled));
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeArtworkProviders_WhenLibraryTypeIsUnknown_ShouldReturnProblemResult()
+ {
+ // Arrange
+ string libraryType = "NotARealLibraryType";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/artwork-providers/{libraryType}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
+ Assert.Equal("General.Validation", problemDetails["title"].GetString());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("UnknownLibraryType", errors!["General.Validation"]);
+ Assert.Equal($"/api/v1/libraries/artwork-providers/{libraryType}", problemDetails["instance"].GetString());
+ Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/libraries/artwork-providers/Book");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ }
+
+ ///
+ /// Disposes API factory resources.
+ ///
+ public async Task DisposeAsync()
+ {
+ await _apiFactory.RemoveTestUserAsync();
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs
new file mode 100644
index 00000000..ea4ab772
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs
@@ -0,0 +1,112 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.Responses.Plugins;
+using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeBookReaders;
+using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
+using Microsoft.AspNetCore.Http;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryTypeBookReaders;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeBookReadersEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private HttpClient _client;
+ private readonly AuthenticatedLuminaApiFactory _apiFactory;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true,
+ Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
+ };
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetLibraryTypeBookReadersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Theory]
+ [InlineData("Book")]
+ [InlineData("music")] // The casing of the type is ignored.
+ public async Task GetLibraryTypeBookReaders_WhenLibraryTypeIsValid_ShouldReturnOkWithTheAvailableReaders(string libraryType)
+ {
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/book-readers/{libraryType}");
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ List? readers = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(readers);
+ // The test host loads no plugins, so no reader supports the type; every reader that is returned starts disabled.
+ Assert.All(readers!, reader => Assert.False(reader.IsEnabled));
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeBookReaders_WhenLibraryTypeIsUnknown_ShouldReturnProblemResult()
+ {
+ // Arrange
+ string libraryType = "NotARealLibraryType";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/book-readers/{libraryType}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
+ Assert.Equal("General.Validation", problemDetails["title"].GetString());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("UnknownLibraryType", errors!["General.Validation"]);
+ Assert.Equal($"/api/v1/libraries/book-readers/{libraryType}", problemDetails["instance"].GetString());
+ Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeBookReaders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/libraries/book-readers/Book");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ }
+
+ ///
+ /// Disposes API factory resources.
+ ///
+ public async Task DisposeAsync()
+ {
+ await _apiFactory.RemoveTestUserAsync();
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs
new file mode 100644
index 00000000..73af45cb
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs
@@ -0,0 +1,112 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.Responses.Plugins;
+using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders;
+using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
+using Microsoft.AspNetCore.Http;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private HttpClient _client;
+ private readonly AuthenticatedLuminaApiFactory _apiFactory;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true,
+ Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
+ };
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetLibraryTypeMetadataProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Theory]
+ [InlineData("Book")]
+ [InlineData("music")] // The casing of the type is ignored.
+ public async Task GetLibraryTypeMetadataProviders_WhenLibraryTypeIsValid_ShouldReturnOkWithTheAvailableProviders(string libraryType)
+ {
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/metadata-providers/{libraryType}");
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ List? providers = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(providers);
+ // The test host loads no plugins, so no provider supports the type; every provider that is returned starts disabled.
+ Assert.All(providers!, provider => Assert.False(provider.IsEnabled));
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeMetadataProviders_WhenLibraryTypeIsUnknown_ShouldReturnProblemResult()
+ {
+ // Arrange
+ string libraryType = "NotARealLibraryType";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/metadata-providers/{libraryType}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
+ Assert.Equal("General.Validation", problemDetails["title"].GetString());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("UnknownLibraryType", errors!["General.Validation"]);
+ Assert.Equal($"/api/v1/libraries/metadata-providers/{libraryType}", problemDetails["instance"].GetString());
+ Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/libraries/metadata-providers/Book");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ }
+
+ ///
+ /// Disposes API factory resources.
+ ///
+ public async Task DisposeAsync()
+ {
+ await _apiFactory.RemoveTestUserAsync();
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs
deleted file mode 100644
index 6887dc59..00000000
--- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs
+++ /dev/null
@@ -1,140 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Application.Common.DataAccess.Entities.Plugins;
-using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
-using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
-using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
-using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-using Lumina.Contracts.Requests.Plugins;
-using Lumina.DataAccess.Core.UoW;
-using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
-using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders;
-using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.Extensions.DependencyInjection;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-using System.Net;
-using System.Net.Http;
-using System.Net.Http.Json;
-using System.Threading.Tasks;
-#endregion
-
-namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders;
-
-///
-/// Contains integration tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class ReorderLibraryArtworkProvidersEndpointTests : IClassFixture, IAsyncLifetime
-{
- private HttpClient _client;
- private readonly AuthenticatedLuminaApiFactory _apiFactory;
- private readonly LibraryEntityFixture _libraryEntityFixture = new();
- private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
- private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Injected in-memory API factory.
- public ReorderLibraryArtworkProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
- {
- _client = apiFactory.CreateClient();
- _apiFactory = apiFactory;
- }
-
- ///
- /// Initializes authenticated API client.
- ///
- public async Task InitializeAsync()
- {
- _client = await _apiFactory.CreateAuthenticatedClientAsync();
- }
-
- [Fact]
- public async Task ReorderLibraryArtworkProviders_WhenCalledWithValidData_ShouldReorderTheProviders()
- {
- // Arrange
- Guid userId = GetCurrentUserId();
- Guid libraryId = Guid.NewGuid();
- await SeedLibraryAsync(libraryId, userId);
- Guid pluginIdA = Guid.NewGuid();
- Guid pluginIdB = Guid.NewGuid();
- await SeedConfigurationAsync(libraryId, pluginIdA, rank: 1);
- await SeedConfigurationAsync(libraryId, pluginIdB, rank: 2);
- ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(
- libraryId: libraryId,
- pluginIds: [pluginIdB, pluginIdA]
- );
-
- // Act
- HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", request);
-
- // Assert
- response.EnsureSuccessStatusCode();
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
-
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- List configurations = await dbContext.LibraryArtworkProviderConfigurations
- .Where(config => config.LibraryId == libraryId)
- .OrderBy(config => config.Rank)
- .ToListAsync();
- Assert.Equal(2, configurations.Count);
- Assert.Equal(pluginIdB, configurations[0].PluginId);
- Assert.Equal(1, configurations[0].Rank);
- Assert.Equal(pluginIdA, configurations[1].PluginId);
- Assert.Equal(2, configurations[1].Rank);
- }
-
- ///
- /// Seeds a owned by .
- ///
- /// The Id of the library to seed.
- /// The Id of the user that owns the library.
- /// A task representing the asynchronous operation.
- private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
- await dbContext.SaveChangesAsync();
- }
-
- ///
- /// Seeds a in the database.
- ///
- /// The Id of the media library.
- /// The Id of the plugin.
- /// The rank of the provider.
- /// A task representing the asynchronous operation.
- private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, int rank)
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank));
- await dbContext.SaveChangesAsync();
- }
-
- ///
- /// Gets the Id of the currently authenticated test user.
- ///
- /// The Id of the authenticated test user.
- private Guid GetCurrentUserId()
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
- return user.Id;
- }
-
- ///
- /// Disposes API factory resources.
- ///
- public async Task DisposeAsync()
- {
- await _apiFactory.RemoveTestUserAsync();
- }
-}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs
deleted file mode 100644
index e71c05ac..00000000
--- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs
+++ /dev/null
@@ -1,140 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Application.Common.DataAccess.Entities.Plugins;
-using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
-using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
-using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
-using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-using Lumina.Contracts.Requests.Plugins;
-using Lumina.DataAccess.Core.UoW;
-using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
-using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders;
-using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.Extensions.DependencyInjection;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-using System.Net;
-using System.Net.Http;
-using System.Net.Http.Json;
-using System.Threading.Tasks;
-#endregion
-
-namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders;
-
-///
-/// Contains integration tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture, IAsyncLifetime
-{
- private HttpClient _client;
- private readonly AuthenticatedLuminaApiFactory _apiFactory;
- private readonly LibraryEntityFixture _libraryEntityFixture = new();
- private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
- private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Injected in-memory API factory.
- public ReorderLibraryMetadataProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
- {
- _client = apiFactory.CreateClient();
- _apiFactory = apiFactory;
- }
-
- ///
- /// Initializes authenticated API client.
- ///
- public async Task InitializeAsync()
- {
- _client = await _apiFactory.CreateAuthenticatedClientAsync();
- }
-
- [Fact]
- public async Task ReorderLibraryMetadataProviders_WhenCalledWithValidData_ShouldReorderTheProviders()
- {
- // Arrange
- Guid userId = GetCurrentUserId();
- Guid libraryId = Guid.NewGuid();
- await SeedLibraryAsync(libraryId, userId);
- Guid pluginIdA = Guid.NewGuid();
- Guid pluginIdB = Guid.NewGuid();
- await SeedConfigurationAsync(libraryId, pluginIdA, rank: 1);
- await SeedConfigurationAsync(libraryId, pluginIdB, rank: 2);
- ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(
- libraryId: libraryId,
- pluginIds: [pluginIdB, pluginIdA]
- );
-
- // Act
- HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/reorder", request);
-
- // Assert
- response.EnsureSuccessStatusCode();
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
-
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- List configurations = await dbContext.LibraryMetadataProviderConfigurations
- .Where(config => config.LibraryId == libraryId)
- .OrderBy(config => config.Rank)
- .ToListAsync();
- Assert.Equal(2, configurations.Count);
- Assert.Equal(pluginIdB, configurations[0].PluginId);
- Assert.Equal(1, configurations[0].Rank);
- Assert.Equal(pluginIdA, configurations[1].PluginId);
- Assert.Equal(2, configurations[1].Rank);
- }
-
- ///
- /// Seeds a owned by .
- ///
- /// The Id of the library to seed.
- /// The Id of the user that owns the library.
- /// A task representing the asynchronous operation.
- private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
- await dbContext.SaveChangesAsync();
- }
-
- ///
- /// Seeds a in the database.
- ///
- /// The Id of the media library.
- /// The Id of the plugin.
- /// The rank of the provider.
- /// A task representing the asynchronous operation.
- private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, int rank)
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank));
- await dbContext.SaveChangesAsync();
- }
-
- ///
- /// Gets the Id of the currently authenticated test user.
- ///
- /// The Id of the authenticated test user.
- private Guid GetCurrentUserId()
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
- return user.Id;
- }
-
- ///
- /// Disposes API factory resources.
- ///
- public async Task DisposeAsync()
- {
- await _apiFactory.RemoveTestUserAsync();
- }
-}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs
deleted file mode 100644
index a8d33410..00000000
--- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs
+++ /dev/null
@@ -1,156 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Application.Common.DataAccess.Entities.Plugins;
-using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
-using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
-using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
-using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-using Lumina.Contracts.Requests.Plugins;
-using Lumina.DataAccess.Core.UoW;
-using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
-using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled;
-using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.Extensions.DependencyInjection;
-using System;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-using System.Net;
-using System.Net.Http;
-using System.Net.Http.Json;
-using System.Threading.Tasks;
-#endregion
-
-namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled;
-
-///
-/// Contains integration tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class SetLibraryArtworkProviderEnabledEndpointTests : IClassFixture, IAsyncLifetime
-{
- private HttpClient _client;
- private readonly AuthenticatedLuminaApiFactory _apiFactory;
- private readonly LibraryEntityFixture _libraryEntityFixture = new();
- private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
- private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Injected in-memory API factory.
- public SetLibraryArtworkProviderEnabledEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
- {
- _client = apiFactory.CreateClient();
- _apiFactory = apiFactory;
- }
-
- ///
- /// Initializes authenticated API client.
- ///
- public async Task InitializeAsync()
- {
- _client = await _apiFactory.CreateAuthenticatedClientAsync();
- }
-
- [Fact]
- public async Task SetLibraryArtworkProviderEnabled_WhenNoConfigurationExists_ShouldCreateIt()
- {
- // Arrange
- Guid userId = GetCurrentUserId();
- Guid libraryId = Guid.NewGuid();
- await SeedLibraryAsync(libraryId, userId);
- Guid pluginId = Guid.NewGuid();
- SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
-
- // Act
- HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request);
-
- // Assert
- response.EnsureSuccessStatusCode();
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
-
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- LibraryArtworkProviderConfigurationEntity? configuration = await dbContext.LibraryArtworkProviderConfigurations
- .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
- Assert.NotNull(configuration);
- Assert.True(configuration!.IsEnabled);
- Assert.Equal(1, configuration.Rank);
- }
-
- [Fact]
- public async Task SetLibraryArtworkProviderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState()
- {
- // Arrange
- Guid userId = GetCurrentUserId();
- Guid libraryId = Guid.NewGuid();
- await SeedLibraryAsync(libraryId, userId);
- Guid pluginId = Guid.NewGuid();
- await SeedConfigurationAsync(libraryId, pluginId, isEnabled: false, rank: 1);
- SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
-
- // Act
- HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request);
-
- // Assert
- response.EnsureSuccessStatusCode();
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
-
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- LibraryArtworkProviderConfigurationEntity? configuration = await dbContext.LibraryArtworkProviderConfigurations
- .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
- Assert.NotNull(configuration);
- Assert.True(configuration!.IsEnabled);
- }
-
- ///
- /// Seeds a owned by .
- ///
- /// The Id of the library to seed.
- /// The Id of the user that owns the library.
- /// A task representing the asynchronous operation.
- private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
- await dbContext.SaveChangesAsync();
- }
-
- ///
- /// Seeds a in the database.
- ///
- /// The Id of the media library.
- /// The Id of the plugin.
- /// Whether the provider is enabled.
- /// The rank of the provider.
- /// A task representing the asynchronous operation.
- private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, bool isEnabled, int rank)
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank, isEnabled: isEnabled));
- await dbContext.SaveChangesAsync();
- }
-
- ///
- /// Gets the Id of the currently authenticated test user.
- ///
- /// The Id of the authenticated test user.
- private Guid GetCurrentUserId()
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
- return user.Id;
- }
-
- ///
- /// Disposes API factory resources.
- ///
- public async Task DisposeAsync()
- {
- await _apiFactory.RemoveTestUserAsync();
- }
-}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs
deleted file mode 100644
index 5d6bfd50..00000000
--- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs
+++ /dev/null
@@ -1,199 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
-using Lumina.Application.Common.DataAccess.Entities.Plugins;
-using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
-using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
-using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
-using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
-using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-using Lumina.Contracts.Requests.Plugins;
-using Lumina.DataAccess.Core.UoW;
-using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.Extensions.DependencyInjection;
-using System;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-using System.Net;
-using System.Net.Http;
-using System.Net.Http.Json;
-using System.Threading.Tasks;
-#endregion
-
-namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled;
-
-///
-/// Contains integration tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class SetLibraryBookReaderEnabledEndpointTests : IClassFixture, IAsyncLifetime
-{
- private HttpClient _client;
- private readonly AuthenticatedLuminaApiFactory _apiFactory;
- private readonly LibraryEntityFixture _libraryEntityFixture = new();
- private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new();
- private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new();
- private readonly UserEntityFixture _userEntityFixture = new();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Injected in-memory API factory.
- public SetLibraryBookReaderEnabledEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
- {
- _client = apiFactory.CreateClient();
- _apiFactory = apiFactory;
- }
-
- ///
- /// Initializes authenticated API client.
- ///
- public async Task InitializeAsync()
- {
- _client = await _apiFactory.CreateAuthenticatedClientAsync();
- }
-
- [Fact]
- public async Task SetLibraryBookReaderEnabled_WhenNoConfigurationExists_ShouldCreateIt()
- {
- // Arrange
- Guid userId = GetCurrentUserId();
- Guid libraryId = Guid.NewGuid();
- await SeedLibraryAsync(libraryId, userId);
- Guid pluginId = Guid.NewGuid();
- SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
-
- // Act
- HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request);
-
- // Assert
- response.EnsureSuccessStatusCode();
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
-
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- LibraryBookReaderConfigurationEntity? configuration = await dbContext.LibraryBookReaderConfigurations
- .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
- Assert.NotNull(configuration);
- Assert.True(configuration!.IsEnabled);
- }
-
- [Fact]
- public async Task SetLibraryBookReaderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState()
- {
- // Arrange
- Guid userId = GetCurrentUserId();
- Guid libraryId = Guid.NewGuid();
- await SeedLibraryAsync(libraryId, userId);
- Guid pluginId = Guid.NewGuid();
- await SeedConfigurationAsync(libraryId, pluginId, isEnabled: false);
- SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
-
- // Act
- HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request);
-
- // Assert
- response.EnsureSuccessStatusCode();
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
-
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- LibraryBookReaderConfigurationEntity configuration = await dbContext.LibraryBookReaderConfigurations
- .SingleAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
- Assert.True(configuration.IsEnabled);
- }
-
- [Fact]
- public async Task SetLibraryBookReaderEnabled_WhenLibraryIsNotOwned_ShouldReturnForbidden()
- {
- // Arrange
- Guid otherUserId = await SeedOtherUserAsync();
- Guid libraryId = Guid.NewGuid();
- await SeedLibraryAsync(libraryId, otherUserId);
- Guid pluginId = Guid.NewGuid();
- SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
-
- // Act
- HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request);
-
- // Assert
- Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
- }
-
- [Fact]
- public async Task SetLibraryBookReaderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult()
- {
- // Arrange
- HttpClient unauthenticatedClient = _apiFactory.CreateClient();
- Guid libraryId = Guid.NewGuid();
- Guid pluginId = Guid.NewGuid();
- SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
-
- // Act
- HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request);
-
- // Assert
- Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
- }
-
- ///
- /// Seeds a library owned by .
- ///
- /// The Id of the library to seed.
- /// The Id of the user that owns the library.
- private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary.LibraryType.EBook, contentLocations: []));
- await dbContext.SaveChangesAsync();
- }
-
- ///
- /// Seeds a book reader configuration for the library and plugin.
- ///
- /// The Id of the library.
- /// The Id of the plugin.
- /// Whether the book reader is enabled.
- private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, bool isEnabled)
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- dbContext.LibraryBookReaderConfigurations.Add(_libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: isEnabled));
- await dbContext.SaveChangesAsync();
- }
-
- ///
- /// Seeds a user that is not the authenticated one and returns its Id.
- ///
- /// The Id of the seeded user.
- private async Task SeedOtherUserAsync()
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- Guid userId = Guid.NewGuid();
- dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
- await dbContext.SaveChangesAsync();
- return userId;
- }
-
- ///
- /// Gets the Id of the currently authenticated test user.
- ///
- /// The Id of the authenticated test user.
- private Guid GetCurrentUserId()
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
- return user.Id;
- }
-
- ///
- /// Disposes API factory resources.
- ///
- public async Task DisposeAsync()
- {
- await _apiFactory.RemoveTestUserAsync();
- }
-}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs
deleted file mode 100644
index 0eb07d2a..00000000
--- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs
+++ /dev/null
@@ -1,156 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Application.Common.DataAccess.Entities.Plugins;
-using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
-using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
-using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
-using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-using Lumina.Contracts.Requests.Plugins;
-using Lumina.DataAccess.Core.UoW;
-using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
-using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled;
-using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.Extensions.DependencyInjection;
-using System;
-using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-using System.Net;
-using System.Net.Http;
-using System.Net.Http.Json;
-using System.Threading.Tasks;
-#endregion
-
-namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled;
-
-///
-/// Contains integration tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture, IAsyncLifetime
-{
- private HttpClient _client;
- private readonly AuthenticatedLuminaApiFactory _apiFactory;
- private readonly LibraryEntityFixture _libraryEntityFixture = new();
- private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
- private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Injected in-memory API factory.
- public SetLibraryMetadataProviderEnabledEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
- {
- _client = apiFactory.CreateClient();
- _apiFactory = apiFactory;
- }
-
- ///
- /// Initializes authenticated API client.
- ///
- public async Task InitializeAsync()
- {
- _client = await _apiFactory.CreateAuthenticatedClientAsync();
- }
-
- [Fact]
- public async Task SetLibraryMetadataProviderEnabled_WhenNoConfigurationExists_ShouldCreateIt()
- {
- // Arrange
- Guid userId = GetCurrentUserId();
- Guid libraryId = Guid.NewGuid();
- await SeedLibraryAsync(libraryId, userId);
- Guid pluginId = Guid.NewGuid();
- SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
-
- // Act
- HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", request);
-
- // Assert
- response.EnsureSuccessStatusCode();
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
-
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- LibraryMetadataProviderConfigurationEntity? configuration = await dbContext.LibraryMetadataProviderConfigurations
- .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
- Assert.NotNull(configuration);
- Assert.True(configuration!.IsEnabled);
- Assert.Equal(1, configuration.Rank);
- }
-
- [Fact]
- public async Task SetLibraryMetadataProviderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState()
- {
- // Arrange
- Guid userId = GetCurrentUserId();
- Guid libraryId = Guid.NewGuid();
- await SeedLibraryAsync(libraryId, userId);
- Guid pluginId = Guid.NewGuid();
- await SeedConfigurationAsync(libraryId, pluginId, isEnabled: false, rank: 1);
- SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
-
- // Act
- HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", request);
-
- // Assert
- response.EnsureSuccessStatusCode();
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
-
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- LibraryMetadataProviderConfigurationEntity? configuration = await dbContext.LibraryMetadataProviderConfigurations
- .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId);
- Assert.NotNull(configuration);
- Assert.True(configuration!.IsEnabled);
- }
-
- ///
- /// Seeds a owned by .
- ///
- /// The Id of the library to seed.
- /// The Id of the user that owns the library.
- /// A task representing the asynchronous operation.
- private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
- await dbContext.SaveChangesAsync();
- }
-
- ///
- /// Seeds a in the database.
- ///
- /// The Id of the media library.
- /// The Id of the plugin.
- /// Whether the provider is enabled.
- /// The rank of the provider.
- /// A task representing the asynchronous operation.
- private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, bool isEnabled, int rank)
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank, isEnabled: isEnabled));
- await dbContext.SaveChangesAsync();
- }
-
- ///
- /// Gets the Id of the currently authenticated test user.
- ///
- /// The Id of the authenticated test user.
- private Guid GetCurrentUserId()
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
- return user.Id;
- }
-
- ///
- /// Disposes API factory resources.
- ///
- public async Task DisposeAsync()
- {
- await _apiFactory.RemoveTestUserAsync();
- }
-}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs
new file mode 100644
index 00000000..483c38ec
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs
@@ -0,0 +1,96 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.Plugins;
+using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders;
+using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
+using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
+using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture
+{
+ private readonly LuminaWebFactory _apiFactory;
+ private readonly LibraryArtworkProviderDtoFixture _libraryArtworkProviderDtoFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public GetLibraryTypeArtworkProvidersEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeArtworkProviders_WhenCalledByAuthenticatedUser_ShouldReturnProvidersJson()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ string libraryType = "Book";
+ LibraryArtworkProviderDto[] expectedProviders =
+ [
+ _libraryArtworkProviderDtoFixture.Create(name: "EPUB Reader", isEnabled: false)
+ ];
+ _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/artwork-providers/{libraryType}", expectedProviders);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-artwork-providers/{libraryType}");
+ getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ using JsonDocument json = JsonDocument.Parse(content);
+ Assert.True(json.RootElement.GetProperty("success").GetBoolean());
+ JsonElement data = json.RootElement.GetProperty("data");
+ Assert.Equal(1, data.GetArrayLength());
+ Assert.Equal("EPUB Reader", data[0].GetProperty("name").GetString());
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeArtworkProviders_WhenCalled_ShouldRequestProvidersFromApi()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ string libraryType = "Book";
+ _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/artwork-providers/{libraryType}", Array.Empty());
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-artwork-providers/{libraryType}");
+ getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ Assert.Contains($"libraries/artwork-providers/{libraryType}", _apiFactory.ApiClientStub.GetEndpointsCalled);
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeArtworkProviders_WhenNotAuthenticated_ShouldRedirectToLogin()
+ {
+ // Arrange
+ HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await anonymousClient.GetAsync("/en-us/libraries/manage/api-get-library-type-artwork-providers/Book");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs
new file mode 100644
index 00000000..a7a62af6
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs
@@ -0,0 +1,96 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.Plugins;
+using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders;
+using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
+using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
+using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeBookReadersEndpointTests : IClassFixture
+{
+ private readonly LuminaWebFactory _apiFactory;
+ private readonly LibraryBookReaderDtoFixture _libraryBookReaderDtoFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public GetLibraryTypeBookReadersEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeBookReaders_WhenCalledByAuthenticatedUser_ShouldReturnBookReadersJson()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ string libraryType = "Book";
+ LibraryBookReaderDto[] expectedReaders =
+ [
+ _libraryBookReaderDtoFixture.Create(name: "EPUB Reader", isEnabled: false)
+ ];
+ _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/book-readers/{libraryType}", expectedReaders);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-book-readers/{libraryType}");
+ getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ using JsonDocument json = JsonDocument.Parse(content);
+ Assert.True(json.RootElement.GetProperty("success").GetBoolean());
+ JsonElement data = json.RootElement.GetProperty("data");
+ Assert.Equal(1, data.GetArrayLength());
+ Assert.Equal("EPUB Reader", data[0].GetProperty("name").GetString());
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeBookReaders_WhenCalled_ShouldRequestBookReadersFromApi()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ string libraryType = "Book";
+ _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/book-readers/{libraryType}", Array.Empty());
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-book-readers/{libraryType}");
+ getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ Assert.Contains($"libraries/book-readers/{libraryType}", _apiFactory.ApiClientStub.GetEndpointsCalled);
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeBookReaders_WhenNotAuthenticated_ShouldRedirectToLogin()
+ {
+ // Arrange
+ HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await anonymousClient.GetAsync("/en-us/libraries/manage/api-get-library-type-book-readers/Book");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs
new file mode 100644
index 00000000..49f27f3b
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs
@@ -0,0 +1,96 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.Plugins;
+using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders;
+using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
+using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
+using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture
+{
+ private readonly LuminaWebFactory _apiFactory;
+ private readonly LibraryMetadataProviderDtoFixture _libraryMetadataProviderDtoFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public GetLibraryTypeMetadataProvidersEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeMetadataProviders_WhenCalledByAuthenticatedUser_ShouldReturnProvidersJson()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ string libraryType = "Book";
+ LibraryMetadataProviderDto[] expectedProviders =
+ [
+ _libraryMetadataProviderDtoFixture.Create(name: "EPUB Reader", isEnabled: false)
+ ];
+ _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/metadata-providers/{libraryType}", expectedProviders);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-metadata-providers/{libraryType}");
+ getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ using JsonDocument json = JsonDocument.Parse(content);
+ Assert.True(json.RootElement.GetProperty("success").GetBoolean());
+ JsonElement data = json.RootElement.GetProperty("data");
+ Assert.Equal(1, data.GetArrayLength());
+ Assert.Equal("EPUB Reader", data[0].GetProperty("name").GetString());
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeMetadataProviders_WhenCalled_ShouldRequestProvidersFromApi()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ string libraryType = "Book";
+ _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/metadata-providers/{libraryType}", Array.Empty());
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-library-type-metadata-providers/{libraryType}");
+ getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ Assert.Contains($"libraries/metadata-providers/{libraryType}", _apiFactory.ApiClientStub.GetEndpointsCalled);
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeMetadataProviders_WhenNotAuthenticated_ShouldRedirectToLogin()
+ {
+ // Arrange
+ HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await anonymousClient.GetAsync("/en-us/libraries/manage/api-get-library-type-metadata-providers/Book");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs
index af5eeff6..0095e77d 100644
--- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs
@@ -1,7 +1,10 @@
#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.Index;
+using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
+using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
@@ -17,6 +20,7 @@ namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Manage
public class LibrariesIndexViewEndpointTests : IClassFixture
{
private readonly LuminaWebFactory _apiFactory;
+ private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
///
/// Initializes a new instance of the class.
@@ -44,8 +48,8 @@ public class LibrariesIndexViewEndpointTests : IClassFixture
}
[Theory]
- [InlineData("/en-us/libraries/manage", "%2Fen-us%2Flibraries%2Fmanage")] // plain page
- [InlineData("/en-us/libraries/manage?tab=scans", "%2Fen-us%2Flibraries%2Fmanage%3Ftab%3Dscans")] // query string is kept
+ [InlineData("/en-us/libraries/manage", "%2Fen-us%2Flibraries%2Fmanage")] // Plain page.
+ [InlineData("/en-us/libraries/manage?tab=scans", "%2Fen-us%2Flibraries%2Fmanage%3Ftab%3Dscans")] // Query string is kept.
public async Task LibrariesIndexView_WhenNavigatedToWithoutAuthentication_ShouldRedirectToLoginWithRequestedPageAsReturnUrl(string requestedUrl, string expectedEncodedReturnUrl)
{
// Arrange
@@ -60,4 +64,45 @@ public class LibrariesIndexViewEndpointTests : IClassFixture
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal($"http://localhost/en-us/auth/login?returnUrl={expectedEncodedReturnUrl}", response.Headers.Location!.ToString());
}
+
+ [Theory]
+ [InlineData("User", true, "true")] // The permission lets a user manage the libraries they own.
+ [InlineData("User", false, "false")] // Without the permission, a user cannot change even the libraries they own.
+ [InlineData("Admin", false, "true")] // An administrator can manage every library, with or without the permission.
+ public async Task LibrariesIndexView_WhenRendered_ShouldOfferTheEditAndDeleteActionsOnlyToUsersAllowedToManageLibraries(string role, bool hasManagePermission, string expectedCanManageLibraries)
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(
+ userId: Guid.NewGuid(),
+ role: role,
+ permissions: hasManagePermission ? [AuthorizationPermission.CanCreateLibraries] : []);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage");
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.Contains($"const canManageLibraries = {expectedCanManageLibraries};", content);
+ }
+
+ [Fact]
+ public async Task LibrariesIndexView_WhenRenderedInACultureWithNonAsciiLabels_ShouldInjectTheScriptLabelsAsJson()
+ {
+ // Arrange
+ // Razor would encode the non-ASCII letters of a raw label as HTML entities, which the browser shows literally inside a script, while JSON escapes them
+ _apiFactory.ApiClientStub.Reset();
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync("/ro-ro/libraries/manage");
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.Contains("\"LibraryDeleted\":\"Biblioteca a fost \\u0219tears\\u0103!\"", content);
+ Assert.DoesNotContain("ștears", content);
+ }
}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointTests.cs
deleted file mode 100644
index 940c6cf0..00000000
--- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointTests.cs
+++ /dev/null
@@ -1,71 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Presentation.Web.Common.Requests.Plugins;
-using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderArtworkProviders;
-using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
-using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
-using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
-using System;
-using System.Diagnostics.CodeAnalysis;
-using System.Net;
-using System.Net.Http;
-using System.Net.Http.Headers;
-using System.Net.Http.Json;
-using System.Text.Json;
-using System.Threading.Tasks;
-#endregion
-
-namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ReorderArtworkProviders;
-
-///
-/// Contains integration tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class ReorderArtworkProvidersEndpointTests : IClassFixture
-{
- private readonly LuminaWebFactory _apiFactory;
- private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Injected Web application factory.
- public ReorderArtworkProvidersEndpointTests(LuminaWebFactory apiFactory)
- {
- _apiFactory = apiFactory;
- }
-
- [Fact]
- public async Task ReorderArtworkProviders_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldReorderProvidersAndReturnSuccess()
- {
- // Arrange
- _apiFactory.ApiClientStub.Reset();
- Guid libraryId = Guid.NewGuid();
- Guid firstPluginId = Guid.NewGuid();
- Guid secondPluginId = Guid.NewGuid();
- ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(
- libraryId: libraryId,
- pluginIds: [firstPluginId, secondPluginId]
- );
- string expectedEndpoint = $"libraries/{libraryId}/artwork-providers/reorder";
- _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
- AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
- HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-reorder-artwork-providers")
- {
- Content = JsonContent.Create(request)
- };
- updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
- updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
-
- // Act
- HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
- string content = await response.Content.ReadAsStringAsync();
-
- // Assert
- response.EnsureSuccessStatusCode();
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- using JsonDocument json = JsonDocument.Parse(content);
- Assert.True(json.RootElement.GetProperty("success").GetBoolean());
- Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
- }
-}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs
deleted file mode 100644
index 059ebed5..00000000
--- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs
+++ /dev/null
@@ -1,71 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Presentation.Web.Common.Requests.Plugins;
-using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderMetadataProviders;
-using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
-using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
-using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
-using System;
-using System.Diagnostics.CodeAnalysis;
-using System.Net;
-using System.Net.Http;
-using System.Net.Http.Headers;
-using System.Net.Http.Json;
-using System.Text.Json;
-using System.Threading.Tasks;
-#endregion
-
-namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ReorderMetadataProviders;
-
-///
-/// Contains integration tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class ReorderMetadataProvidersEndpointTests : IClassFixture
-{
- private readonly LuminaWebFactory _apiFactory;
- private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Injected Web application factory.
- public ReorderMetadataProvidersEndpointTests(LuminaWebFactory apiFactory)
- {
- _apiFactory = apiFactory;
- }
-
- [Fact]
- public async Task ReorderMetadataProviders_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldReorderProvidersAndReturnSuccess()
- {
- // Arrange
- _apiFactory.ApiClientStub.Reset();
- Guid libraryId = Guid.NewGuid();
- Guid firstPluginId = Guid.NewGuid();
- Guid secondPluginId = Guid.NewGuid();
- ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(
- libraryId: libraryId,
- pluginIds: [firstPluginId, secondPluginId]
- );
- string expectedEndpoint = $"libraries/{libraryId}/metadata-providers/reorder";
- _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
- AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
- HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-reorder-metadata-providers")
- {
- Content = JsonContent.Create(request)
- };
- updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
- updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
-
- // Act
- HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
- string content = await response.Content.ReadAsStringAsync();
-
- // Assert
- response.EnsureSuccessStatusCode();
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- using JsonDocument json = JsonDocument.Parse(content);
- Assert.True(json.RootElement.GetProperty("success").GetBoolean());
- Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
- }
-}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs
index 121701e4..f06d0cc4 100644
--- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs
@@ -64,6 +64,43 @@ public class SaveLibraryEndpointTests : IClassFixture
Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries");
}
+ [Fact]
+ public async Task SaveLibrary_WhenAProviderChoiceHasNoEnabledState_ShouldForwardItWithoutAState()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ Guid pluginId = Guid.NewGuid();
+ LibraryDto request = _libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book");
+ request.Id = null;
+ _apiFactory.ApiClientStub.RegisterPostResponse("libraries", _libraryDtoFixture.Create(id: Guid.NewGuid(), title: request.Title, libraryType: request.LibraryType));
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ // The choice is sent without its enabled state, the way a caller that only reorders the providers would send it.
+ HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item")
+ {
+ Content = JsonContent.Create(new
+ {
+ request.Title,
+ request.LibraryType,
+ request.ContentLocations,
+ MetadataProviders = new[] { new { PluginId = pluginId } }
+ })
+ };
+ saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
+ saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+ saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ (string _, object? data) = Assert.Single(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries");
+ LibraryDto forwardedLibrary = Assert.IsType(data);
+ LibraryProviderSelectionDto forwardedChoice = Assert.Single(forwardedLibrary.MetadataProviders!);
+ Assert.Equal(pluginId, forwardedChoice.PluginId);
+ Assert.Null(forwardedChoice.IsEnabled);
+ }
+
[Fact]
public async Task SaveLibrary_WhenCalledWithoutAntiforgeryToken_ShouldReturnBadRequest()
{
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointTests.cs
deleted file mode 100644
index 2a2c9995..00000000
--- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointTests.cs
+++ /dev/null
@@ -1,71 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Presentation.Web.Common.Requests.Plugins;
-using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetArtworkProviderEnabled;
-using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
-using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
-using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
-using System;
-using System.Diagnostics.CodeAnalysis;
-using System.Net;
-using System.Net.Http;
-using System.Net.Http.Headers;
-using System.Net.Http.Json;
-using System.Text.Json;
-using System.Threading.Tasks;
-#endregion
-
-namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetArtworkProviderEnabled;
-
-///
-/// Contains integration tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class SetArtworkProviderEnabledEndpointTests : IClassFixture
-{
- private readonly LuminaWebFactory _apiFactory;
- private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Injected Web application factory.
- public SetArtworkProviderEnabledEndpointTests(LuminaWebFactory apiFactory)
- {
- _apiFactory = apiFactory;
- }
-
- [Fact]
- public async Task SetArtworkProviderEnabled_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldEnableProviderAndReturnSuccess()
- {
- // Arrange
- _apiFactory.ApiClientStub.Reset();
- Guid libraryId = Guid.NewGuid();
- Guid pluginId = Guid.NewGuid();
- SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(
- libraryId: libraryId,
- pluginId: pluginId,
- isEnabled: true
- );
- string expectedEndpoint = $"libraries/{libraryId}/artwork-providers/{pluginId}/enabled";
- _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
- AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
- HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-artwork-provider-enabled")
- {
- Content = JsonContent.Create(request)
- };
- updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
- updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
-
- // Act
- HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
- string content = await response.Content.ReadAsStringAsync();
-
- // Assert
- response.EnsureSuccessStatusCode();
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- using JsonDocument json = JsonDocument.Parse(content);
- Assert.True(json.RootElement.GetProperty("success").GetBoolean());
- Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
- }
-}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs
deleted file mode 100644
index 11aa7902..00000000
--- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs
+++ /dev/null
@@ -1,87 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Presentation.Web.Common.Requests.Common;
-using Lumina.Presentation.Web.Common.Requests.Plugins;
-using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetBookReaderEnabled;
-using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
-using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
-using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
-using System;
-using System.Diagnostics.CodeAnalysis;
-using System.Net;
-using System.Net.Http;
-using System.Net.Http.Headers;
-using System.Net.Http.Json;
-using System.Text.Json;
-using System.Threading.Tasks;
-#endregion
-
-namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetBookReaderEnabled;
-
-///
-/// Contains integration tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class SetBookReaderEnabledEndpointTests : IClassFixture
-{
- private readonly LuminaWebFactory _apiFactory;
- private readonly SetBookReaderEnabledRequestFixture _setBookReaderEnabledRequestFixture = new();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Injected Web application factory.
- public SetBookReaderEnabledEndpointTests(LuminaWebFactory apiFactory)
- {
- _apiFactory = apiFactory;
- }
-
- [Fact]
- public async Task SetBookReaderEnabled_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldEnableReaderAndReturnSuccess()
- {
- // Arrange
- _apiFactory.ApiClientStub.Reset();
- Guid libraryId = Guid.NewGuid();
- Guid pluginId = Guid.NewGuid();
- SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
- string expectedEndpoint = $"libraries/{libraryId}/book-readers/{pluginId}/enabled";
- _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new EmptyRequest());
- AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
- HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled")
- {
- Content = JsonContent.Create(request)
- };
- updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
- updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
-
- // Act
- HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
- string content = await response.Content.ReadAsStringAsync();
-
- // Assert
- response.EnsureSuccessStatusCode();
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- using JsonDocument json = JsonDocument.Parse(content);
- Assert.True(json.RootElement.GetProperty("success").GetBoolean());
- Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
- }
-
- [Fact]
- public async Task SetBookReaderEnabled_WhenNotAuthenticated_ShouldRedirectToLogin()
- {
- // Arrange
- HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
- SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create();
- HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled")
- {
- Content = JsonContent.Create(request)
- };
- updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
-
- // Act
- HttpResponseMessage response = await anonymousClient.SendAsync(updateRequest);
-
- // Assert
- Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
- }
-}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs
deleted file mode 100644
index ad6752ac..00000000
--- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs
+++ /dev/null
@@ -1,71 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Presentation.Web.Common.Requests.Plugins;
-using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetMetadataProviderEnabled;
-using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
-using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
-using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
-using System;
-using System.Diagnostics.CodeAnalysis;
-using System.Net;
-using System.Net.Http;
-using System.Net.Http.Headers;
-using System.Net.Http.Json;
-using System.Text.Json;
-using System.Threading.Tasks;
-#endregion
-
-namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetMetadataProviderEnabled;
-
-///
-/// Contains integration tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class SetMetadataProviderEnabledEndpointTests : IClassFixture
-{
- private readonly LuminaWebFactory _apiFactory;
- private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Injected Web application factory.
- public SetMetadataProviderEnabledEndpointTests(LuminaWebFactory apiFactory)
- {
- _apiFactory = apiFactory;
- }
-
- [Fact]
- public async Task SetMetadataProviderEnabled_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldEnableProviderAndReturnSuccess()
- {
- // Arrange
- _apiFactory.ApiClientStub.Reset();
- Guid libraryId = Guid.NewGuid();
- Guid pluginId = Guid.NewGuid();
- SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(
- libraryId: libraryId,
- pluginId: pluginId,
- isEnabled: true
- );
- string expectedEndpoint = $"libraries/{libraryId}/metadata-providers/{pluginId}/enabled";
- _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
- AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
- HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-metadata-provider-enabled")
- {
- Content = JsonContent.Create(request)
- };
- updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
- updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
-
- // Act
- HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
- string content = await response.Content.ReadAsStringAsync();
-
- // Assert
- response.EnsureSuccessStatusCode();
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- using JsonDocument json = JsonDocument.Parse(content);
- Assert.True(json.RootElement.GetProperty("success").GetBoolean());
- Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
- }
-}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs
index 659b8547..b16c27a1 100644
--- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs
@@ -9,6 +9,7 @@ using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Common.Interceptors;
using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.Security;
using Microsoft.AspNetCore.Authentication.JwtBearer;
@@ -45,6 +46,8 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable
private readonly UserEntityFixture _userEntityFixture = new();
private readonly RoleEntityFixture _roleEntityFixture = new();
private readonly UserRoleEntityFixture _userRoleEntityFixture = new();
+ private readonly PermissionEntityFixture _permissionEntityFixture = new();
+ private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=";
@@ -55,11 +58,11 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable
///
public LuminaApiFactory()
{
- // each factory gets its own uniquely named shared in-memory database, so that parallel test classes remain isolated from one another;
+ // Each factory gets its own uniquely named shared in-memory database, so that parallel test classes remain isolated from one another;
// the shared cache allows each DbContext to open its own pooled connection to the same database, instead of sharing a single connection,
- // which would otherwise serialize every request on one connection and cause nested transaction errors between requests
+ // which would otherwise serialize every request on one connection and cause nested transaction errors between requests.
_sharedInMemoryConnectionString = string.Format(SHARED_IN_MEMORY_CONNECTION_STRING_PREFIX, Guid.NewGuid());
- // keep a single anchor connection open, so that the shared in-memory database it refers to is not dropped
+ // Keep a single anchor connection open, so that the shared in-memory database it refers to is not dropped.
_connection = new SqliteConnection(_sharedInMemoryConnectionString);
_connection.Open();
}
@@ -202,6 +205,40 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable
return (userId, username);
}
+ ///
+ /// Creates a test user that holds a single permission directly, authenticates it on , and returns its Id and username.
+ ///
+ /// The HTTP client to configure with authentication headers.
+ /// The permission granted to the created user.
+ /// The Id and username of the created test user.
+ public async Task<(Guid UserId, string Username)> CreateAndAuthenticateUserWithPermissionAsync(HttpClient client, AuthorizationPermission permission)
+ {
+ // A unique X-Forwarded-For isolates rate limiting state per test.
+ client.DefaultRequestHeaders.Clear();
+ client.DefaultRequestHeaders.Add("X-Forwarded-For", GetUniqueTestIp());
+
+ using IServiceScope scope = Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+
+ Guid userId = Guid.NewGuid();
+ string username = $"testuser_{Guid.NewGuid()}";
+ UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
+ user.TotpSecret = null;
+ dbContext.Users.Add(user);
+
+ PermissionEntity permissionEntity = _permissionEntityFixture.Create(permissionName: permission);
+ dbContext.Permissions.Add(permissionEntity);
+ dbContext.UserPermissions.Add(_userPermissionEntityFixture.Create(user, permissionEntity));
+ await dbContext.SaveChangesAsync();
+
+ HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!"));
+ string content = await loginResponse.Content.ReadAsStringAsync();
+ LoginResponse? loginResult = JsonSerializer.Deserialize(content, _jsonOptions);
+ client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
+
+ return (userId, username);
+ }
+
///
/// Removes a test user and its owned libraries from the database.
///
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs
index a400aa53..562f164c 100644
--- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
@@ -60,12 +61,12 @@ public class DeleteLibraryEndpointTests : IClassFixture
}
[Theory]
- [InlineData("' OR '1'='1")] // basic SQL injection
- [InlineData("'; DROP TABLE Libraries--")] // destructive injection
+ [InlineData("' OR '1'='1")] // Basic SQL injection.
+ [InlineData("'; DROP TABLE Libraries--")] // Destructive injection.
public async Task DeleteLibrary_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId)
{
// Arrange
- // authenticate with an admin user and seed a library, so a valid id would reach the handler and be authorized
+ // Authenticate with an admin user and seed a library, so a valid id would reach the handler and be authorized.
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
await SeedLibraryAsync(userId);
@@ -74,10 +75,9 @@ public class DeleteLibraryEndpointTests : IClassFixture
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}");
// Assert
- // note: the {id} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler
- // note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding
- // ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here)
- // note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
+ // Note: the {id} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler.
+ // The observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here).
+ // That 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here.
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
@@ -86,6 +86,68 @@ public class DeleteLibraryEndpointTests : IClassFixture
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
+ [Fact]
+ public async Task DeleteLibrary_WhenTheOwnerLacksTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary()
+ {
+ // Arrange
+ // The created user holds no permission, so it owns the library without being allowed to change it.
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ Guid libraryId = Guid.NewGuid();
+ await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
+
+ // Act
+ HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
+ Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ using (IServiceScope scope = _apiFactory.Services.CreateScope())
+ {
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.NotNull(await dbContext.Libraries.FindAsync(libraryId));
+ }
+
+ await _apiFactory.RemoveTestUserAsync(ownerUsername);
+ }
+
+ [Fact]
+ public async Task DeleteLibrary_WhenNonOwnerHoldsTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary()
+ {
+ // Arrange
+ // Ownership and the manage permission are both required, so a user that holds the permission must not delete a library it does not own.
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ Guid libraryId = Guid.NewGuid();
+ await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
+ (Guid _, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserWithPermissionAsync(client, AuthorizationPermission.CanCreateLibraries);
+
+ // Act
+ HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
+ Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ using (IServiceScope scope = _apiFactory.Services.CreateScope())
+ {
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.NotNull(await dbContext.Libraries.FindAsync(libraryId));
+ }
+
+ await _apiFactory.RemoveTestUserAsync(ownerUsername);
+ await _apiFactory.RemoveTestUserAsync(attackerUsername);
+ }
+
///
/// Seeds a owned by .
///
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs
index 2204a24c..d0abcadf 100644
--- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs
@@ -4,6 +4,7 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Manage
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
@@ -13,6 +14,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
+using System.Text.Json.Nodes;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.UpdateLibrary;
@@ -49,7 +51,6 @@ public class UpdateLibraryEndpointTests : IClassFixture
string libraryId = Guid.NewGuid().ToString();
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: Guid.NewGuid(),
- userId: Guid.NewGuid(),
title: "Updated Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -79,8 +80,8 @@ public class UpdateLibraryEndpointTests : IClassFixture
}
[Theory]
- [InlineData("' OR '1'='1")] // basic SQL injection
- [InlineData("'; DROP TABLE Libraries--")] // destructive injection
+ [InlineData("' OR '1'='1")] // Basic SQL injection.
+ [InlineData("'; DROP TABLE Libraries--")] // Destructive injection.
public async Task UpdateLibrary_WithSQLInjectionInTitle_ShouldNotLeakOrError(string maliciousTitle)
{
// Arrange
@@ -90,7 +91,6 @@ public class UpdateLibraryEndpointTests : IClassFixture
await SeedLibraryAsync(libraryId, userId);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
- userId: userId,
title: maliciousTitle,
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -106,7 +106,7 @@ public class UpdateLibraryEndpointTests : IClassFixture
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
- // the malicious title passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim
+ // The malicious title passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim.
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
@@ -123,10 +123,10 @@ public class UpdateLibraryEndpointTests : IClassFixture
}
[Theory]
- [InlineData(-1)] // just below the allowed range
- [InlineData(101)] // just above the allowed range
- [InlineData(int.MinValue)] // lowest possible value
- [InlineData(int.MaxValue)] // highest possible value
+ [InlineData(-1)] // Just below the allowed range.
+ [InlineData(101)] // Just above the allowed range.
+ [InlineData(int.MinValue)] // Lowest possible value.
+ [InlineData(int.MaxValue)] // Highest possible value.
public async Task UpdateLibrary_WhenThresholdIsOutsideAllowedRange_ShouldRejectTheRequestAndKeepTheStoredSettings(int completionThresholdPercentage)
{
// Arrange
@@ -136,7 +136,6 @@ public class UpdateLibraryEndpointTests : IClassFixture
await SeedLibraryAsync(libraryId, userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
- userId: userId,
title: "Test Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -177,7 +176,6 @@ public class UpdateLibraryEndpointTests : IClassFixture
await SeedLibraryAsync(libraryId, userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
- userId: userId,
title: "Test Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -223,7 +221,6 @@ public class UpdateLibraryEndpointTests : IClassFixture
(Guid _, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
- userId: ownerId,
title: "Test Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
@@ -275,6 +272,129 @@ public class UpdateLibraryEndpointTests : IClassFixture
await _apiFactory.RemoveTestUserAsync(ownerUsername);
}
+ [Fact]
+ public async Task UpdateLibrary_WhenNonOwnerHoldsTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary()
+ {
+ // Arrange
+ // Ownership and the manage permission are both required, so a user that holds the permission must not update a library it does not own.
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ Guid libraryId = Guid.NewGuid();
+ await SeedLibraryAsync(libraryId, ownerId, title: "Original Title");
+ (Guid _, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserWithPermissionAsync(client, AuthorizationPermission.CanCreateLibraries);
+ UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
+ id: libraryId,
+ title: "Updated Title",
+ libraryType: "EBook",
+ contentLocations: ["C:/Media"],
+ coverImage: null);
+
+ // Act
+ HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
+ Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ using (IServiceScope scope = _apiFactory.Services.CreateScope())
+ {
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
+ Assert.NotNull(storedLibrary);
+ Assert.Equal("Original Title", storedLibrary!.Title);
+ }
+
+ await _apiFactory.RemoveTestUserAsync(ownerUsername);
+ await _apiFactory.RemoveTestUserAsync(attackerUsername);
+ }
+
+ [Fact]
+ public async Task UpdateLibrary_WhenTheOwnerLacksTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary()
+ {
+ // Arrange
+ // The created user holds no permission, so it owns the library without being allowed to change it.
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ Guid libraryId = Guid.NewGuid();
+ await SeedLibraryAsync(libraryId, ownerId, title: "Original Title");
+ UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
+ id: libraryId,
+ title: "Updated Title",
+ libraryType: "Book",
+ contentLocations: ["C:/Media"],
+ coverImage: null
+ );
+
+ // Act
+ HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
+ Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ using (IServiceScope scope = _apiFactory.Services.CreateScope())
+ {
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
+ Assert.NotNull(storedLibrary);
+ Assert.Equal("Original Title", storedLibrary!.Title);
+ Assert.Equal(LibraryType.EBook, storedLibrary.LibraryType);
+ }
+
+ await _apiFactory.RemoveTestUserAsync(ownerUsername);
+ }
+
+ [Fact]
+ public async Task UpdateLibrary_WhenBodyNamesAnotherOwner_ShouldKeepTheStoredOwner()
+ {
+ // Arrange
+ HttpClient ownerClient = _apiFactory.CreateClient();
+ (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
+ Guid libraryId = Guid.NewGuid();
+ await SeedLibraryAsync(libraryId, ownerId);
+ HttpClient client = _apiFactory.CreateClient();
+ Guid adminId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
+ UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
+ id: libraryId,
+ title: "Test Library",
+ libraryType: "EBook",
+ contentLocations: ["C:/Media"],
+ coverImage: null,
+ isEnabled: true,
+ isLocked: false,
+ canDownloadMetadataFromWeb: true,
+ shouldSaveMetadataInMediaDirectories: false,
+ shouldSkipUnchangedDirectoriesDuringScan: true
+ );
+ // The request has no owner, so the claimed owner is added to the raw body, the way a crafted request would carry it.
+ JsonObject body = JsonSerializer.SerializeToNode(request, new JsonSerializerOptions(JsonSerializerDefaults.Web))!.AsObject();
+ body["userId"] = adminId.ToString();
+
+ // Act
+ HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", body);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ using (IServiceScope scope = _apiFactory.Services.CreateScope())
+ {
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
+ Assert.NotNull(storedLibrary);
+ Assert.Equal(ownerId, storedLibrary!.UserId);
+ }
+
+ await _apiFactory.RemoveTestUserAsync(ownerUsername);
+ await _apiFactory.RemoveAdminUserAsync(adminId);
+ }
+
///
/// Asserts that carries the standard validation problem of the update library route.
///
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs
new file mode 100644
index 00000000..c7f32ee1
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs
@@ -0,0 +1,114 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders;
+using Lumina.Presentation.Api.SecurityTests.Common.Setup;
+using Microsoft.AspNetCore.Http;
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders;
+
+///
+/// Contains security tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture, IDisposable
+{
+ private readonly LuminaApiFactory _apiFactory;
+ private readonly HttpClient _client;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true
+ };
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetLibraryTypeArtworkProvidersEndpointTests(LuminaApiFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ _client = apiFactory.CreateClient();
+ // A unique X-Forwarded-For isolates rate limiting state per test.
+ _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ string libraryType = "Music";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/artwork-providers/{libraryType}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+
+ string content = await response.Content.ReadAsStringAsync();
+
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal($"/api/v1/libraries/artwork-providers/{libraryType}", problemDetails["instance"].GetProperty("value").GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // Basic SQL injection.
+ [InlineData("'; DROP TABLE Libraries--")] // Destructive SQL injection.
+ [InlineData("Music; rm -rf /")] // Command injection.
+ [InlineData("$(whoami)")] // Command substitution injection.
+ [InlineData("`whoami`")] // Backtick command injection.
+ [InlineData("{0}{1}{0}")] // Template/placeholder injection.
+ [InlineData("..\\..\\..\\Windows\\System32\\config\\SAM")] // Windows path traversal.
+ [InlineData("%2e%2e%2fetc%2fpasswd")] // Encoded path traversal.
+ public async Task GetLibraryTypeArtworkProviders_WithInjectionInLibraryType_ShouldNotLeakOrError(string maliciousLibraryType)
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
+
+ // Act
+ HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/artwork-providers/{Uri.EscapeDataString(maliciousLibraryType)}");
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ // An unrecognized library type fails the validation of the query, so it is reported as a validation problem, and the response
+ // must stay generic: the failed request leaks no database, filesystem or framework internals.
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
+ Assert.Equal("General.Validation", problemDetails["title"].GetString());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("UnknownLibraryType", errors!["General.Validation"]);
+ Assert.StartsWith("/api/v1/libraries/artwork-providers/", problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// Disposes the API factory resources.
+ ///
+ public void Dispose()
+ {
+ _client.Dispose();
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs
new file mode 100644
index 00000000..ea29c351
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs
@@ -0,0 +1,114 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeBookReaders;
+using Lumina.Presentation.Api.SecurityTests.Common.Setup;
+using Microsoft.AspNetCore.Http;
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryTypeBookReaders;
+
+///
+/// Contains security tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeBookReadersEndpointTests : IClassFixture, IDisposable
+{
+ private readonly LuminaApiFactory _apiFactory;
+ private readonly HttpClient _client;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true
+ };
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetLibraryTypeBookReadersEndpointTests(LuminaApiFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ _client = apiFactory.CreateClient();
+ // A unique X-Forwarded-For isolates rate limiting state per test.
+ _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeBookReaders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ string libraryType = "Music";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/book-readers/{libraryType}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+
+ string content = await response.Content.ReadAsStringAsync();
+
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal($"/api/v1/libraries/book-readers/{libraryType}", problemDetails["instance"].GetProperty("value").GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // Basic SQL injection.
+ [InlineData("'; DROP TABLE Libraries--")] // Destructive SQL injection.
+ [InlineData("Music; rm -rf /")] // Command injection.
+ [InlineData("$(whoami)")] // Command substitution injection.
+ [InlineData("`whoami`")] // Backtick command injection.
+ [InlineData("{0}{1}{0}")] // Template/placeholder injection.
+ [InlineData("..\\..\\..\\Windows\\System32\\config\\SAM")] // Windows path traversal.
+ [InlineData("%2e%2e%2fetc%2fpasswd")] // Encoded path traversal.
+ public async Task GetLibraryTypeBookReaders_WithInjectionInLibraryType_ShouldNotLeakOrError(string maliciousLibraryType)
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
+
+ // Act
+ HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/book-readers/{Uri.EscapeDataString(maliciousLibraryType)}");
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ // An unrecognized library type fails the validation of the query, so it is reported as a validation problem, and the response
+ // must stay generic: the failed request leaks no database, filesystem or framework internals.
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
+ Assert.Equal("General.Validation", problemDetails["title"].GetString());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("UnknownLibraryType", errors!["General.Validation"]);
+ Assert.StartsWith("/api/v1/libraries/book-readers/", problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// Disposes the API factory resources.
+ ///
+ public void Dispose()
+ {
+ _client.Dispose();
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs
new file mode 100644
index 00000000..7b5563e3
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs
@@ -0,0 +1,114 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders;
+using Lumina.Presentation.Api.SecurityTests.Common.Setup;
+using Microsoft.AspNetCore.Http;
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders;
+
+///
+/// Contains security tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture, IDisposable
+{
+ private readonly LuminaApiFactory _apiFactory;
+ private readonly HttpClient _client;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true
+ };
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetLibraryTypeMetadataProvidersEndpointTests(LuminaApiFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ _client = apiFactory.CreateClient();
+ // A unique X-Forwarded-For isolates rate limiting state per test.
+ _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ string libraryType = "Music";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/metadata-providers/{libraryType}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+
+ string content = await response.Content.ReadAsStringAsync();
+
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal($"/api/v1/libraries/metadata-providers/{libraryType}", problemDetails["instance"].GetProperty("value").GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // Basic SQL injection.
+ [InlineData("'; DROP TABLE Libraries--")] // Destructive SQL injection.
+ [InlineData("Music; rm -rf /")] // Command injection.
+ [InlineData("$(whoami)")] // Command substitution injection.
+ [InlineData("`whoami`")] // Backtick command injection.
+ [InlineData("{0}{1}{0}")] // Template/placeholder injection.
+ [InlineData("..\\..\\..\\Windows\\System32\\config\\SAM")] // Windows path traversal.
+ [InlineData("%2e%2e%2fetc%2fpasswd")] // Encoded path traversal.
+ public async Task GetLibraryTypeMetadataProviders_WithInjectionInLibraryType_ShouldNotLeakOrError(string maliciousLibraryType)
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
+
+ // Act
+ HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/metadata-providers/{Uri.EscapeDataString(maliciousLibraryType)}");
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ // An unrecognized library type fails the validation of the query, so it is reported as a validation problem, and the response
+ // must stay generic: the failed request leaks no database, filesystem or framework internals.
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
+ Assert.Equal("General.Validation", problemDetails["title"].GetString());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("UnknownLibraryType", errors!["General.Validation"]);
+ Assert.StartsWith("/api/v1/libraries/metadata-providers/", problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// Disposes the API factory resources.
+ ///
+ public void Dispose()
+ {
+ _client.Dispose();
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs
deleted file mode 100644
index ac511655..00000000
--- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs
+++ /dev/null
@@ -1,133 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
-using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
-using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-using Lumina.Contracts.Requests.Plugins;
-using Lumina.DataAccess.Core.UoW;
-using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
-using Lumina.Presentation.Api.SecurityTests.Common.Setup;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.DependencyInjection;
-using System.Diagnostics.CodeAnalysis;
-using System.Net;
-using System.Net.Http.Json;
-using System.Text.Json;
-#endregion
-
-namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders;
-
-///
-/// Contains security tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class ReorderLibraryArtworkProvidersEndpointTests : IClassFixture
-{
- private readonly HttpClient _client;
- private readonly LuminaApiFactory _apiFactory;
- private readonly JsonSerializerOptions _jsonOptions = new()
- {
- PropertyNameCaseInsensitive = true
- };
- private readonly LibraryEntityFixture _libraryEntityFixture = new();
- private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
- private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Injected in-memory API factory.
- public ReorderLibraryArtworkProvidersEndpointTests(LuminaApiFactory apiFactory)
- {
- _apiFactory = apiFactory;
- _client = apiFactory.CreateClient();
- }
-
- [Fact]
- public async Task ReorderLibraryArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
- {
- // Arrange
- string libraryId = Guid.NewGuid().ToString();
- ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(
- libraryId: Guid.NewGuid(),
- pluginIds: [Guid.NewGuid()]
- );
-
- // Act
- HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", request);
-
- // Assert
- Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
-
- string content = await response.Content.ReadAsStringAsync();
-
- Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
- Assert.NotNull(problemDetails);
- Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
- Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
- Assert.Equal("Unauthorized", problemDetails["title"].GetString());
- Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", problemDetails["instance"].GetProperty("value").GetString());
- Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
- }
-
- [Theory]
- [InlineData("' OR '1'='1")] // basic SQL injection
- [InlineData("'; DROP TABLE Plugins--")] // destructive injection
- public async Task ReorderLibraryArtworkProviders_WithSQLInjectionInPluginIds_ShouldNotLeakOrError(string maliciousPluginId)
- {
- // Arrange
- // authenticate with an admin user and seed a library with artwork provider configurations, so valid ids would reach the handler
- HttpClient client = _apiFactory.CreateClient();
- Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
- Guid libraryId = await SeedLibraryAsync(userId);
- await SeedConfigurationAsync(libraryId, rank: 1);
- await SeedConfigurationAsync(libraryId, rank: 2);
-
- // Act
- // the malicious value cannot bind to the Guid-typed PluginIds request property, so the body fails JSON deserialization
- // before it ever reaches the endpoint handler
- HttpResponseMessage response = await client.PutAsJsonAsync(
- $"/api/v1/libraries/{libraryId}/artwork-providers/reorder",
- new { libraryId, pluginIds = new[] { maliciousPluginId } });
-
- // Assert
- // note: observed status is 500 because the JSON body cannot be deserialized into the Guid-typed PluginIds property, and
- // FastEndpoints, combined with DontCatchExceptions(), turns the resulting JsonException into a 500 response instead of 400
- // (pre-existing production bug, not fixed here)
- // note: that 500 body leaks the JsonException details, so no DoesNotContain("Exception") is asserted here
- Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
- string content = await response.Content.ReadAsStringAsync();
- Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
- Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
- Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
- Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
- }
-
- ///
- /// Seeds a owned by .
- ///
- /// The Id of the user that owns the library.
- /// The Id of the seeded library.
- private async Task SeedLibraryAsync(Guid userId)
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- Guid libraryId = Guid.NewGuid();
- dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
- await dbContext.SaveChangesAsync();
- return libraryId;
- }
-
- ///
- /// Seeds a for the library identified by .
- ///
- /// The Id of the media library.
- /// The rank of the provider.
- /// A task representing the asynchronous operation.
- private async Task SeedConfigurationAsync(Guid libraryId, int rank)
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: rank));
- await dbContext.SaveChangesAsync();
- }
-}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs
deleted file mode 100644
index d7604735..00000000
--- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs
+++ /dev/null
@@ -1,133 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
-using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
-using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-using Lumina.Contracts.Requests.Plugins;
-using Lumina.DataAccess.Core.UoW;
-using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
-using Lumina.Presentation.Api.SecurityTests.Common.Setup;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.DependencyInjection;
-using System.Diagnostics.CodeAnalysis;
-using System.Net;
-using System.Net.Http.Json;
-using System.Text.Json;
-#endregion
-
-namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders;
-
-///
-/// Contains security tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture
-{
- private readonly HttpClient _client;
- private readonly LuminaApiFactory _apiFactory;
- private readonly JsonSerializerOptions _jsonOptions = new()
- {
- PropertyNameCaseInsensitive = true
- };
- private readonly LibraryEntityFixture _libraryEntityFixture = new();
- private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
- private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Injected in-memory API factory.
- public ReorderLibraryMetadataProvidersEndpointTests(LuminaApiFactory apiFactory)
- {
- _apiFactory = apiFactory;
- _client = apiFactory.CreateClient();
- }
-
- [Fact]
- public async Task ReorderLibraryMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
- {
- // Arrange
- string libraryId = Guid.NewGuid().ToString();
- ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(
- libraryId: Guid.NewGuid(),
- pluginIds: [Guid.NewGuid()]
- );
-
- // Act
- HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/reorder", request);
-
- // Assert
- Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
-
- string content = await response.Content.ReadAsStringAsync();
-
- Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
- Assert.NotNull(problemDetails);
- Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
- Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
- Assert.Equal("Unauthorized", problemDetails["title"].GetString());
- Assert.Equal($"/api/v1/libraries/{libraryId}/metadata-providers/reorder", problemDetails["instance"].GetProperty("value").GetString());
- Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
- }
-
- [Theory]
- [InlineData("' OR '1'='1")] // basic SQL injection
- [InlineData("'; DROP TABLE Plugins--")] // destructive injection
- public async Task ReorderLibraryMetadataProviders_WithSQLInjectionInPluginIds_ShouldNotLeakOrError(string maliciousPluginId)
- {
- // Arrange
- // authenticate with an admin user and seed a library with metadata provider configurations, so valid ids would reach the handler
- HttpClient client = _apiFactory.CreateClient();
- Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
- Guid libraryId = await SeedLibraryAsync(userId);
- await SeedConfigurationAsync(libraryId, rank: 1);
- await SeedConfigurationAsync(libraryId, rank: 2);
-
- // Act
- // the malicious value cannot bind to the Guid-typed PluginIds request property, so the body fails JSON deserialization
- // before it ever reaches the endpoint handler
- HttpResponseMessage response = await client.PutAsJsonAsync(
- $"/api/v1/libraries/{libraryId}/metadata-providers/reorder",
- new { libraryId = libraryId, pluginIds = new[] { maliciousPluginId } });
-
- // Assert
- // note: observed status is 500 because the JSON body cannot be deserialized into the Guid-typed PluginIds property, and
- // FastEndpoints, combined with DontCatchExceptions(), turns the resulting JsonException into a 500 response instead of 400
- // (pre-existing production bug, not fixed here)
- // note: that 500 body leaks the JsonException details, so no DoesNotContain("Exception") is asserted here
- Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
- string content = await response.Content.ReadAsStringAsync();
- Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
- Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
- Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
- Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
- }
-
- ///
- /// Seeds a owned by .
- ///
- /// The Id of the user that owns the library.
- /// The Id of the seeded library.
- private async Task SeedLibraryAsync(Guid userId)
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- Guid libraryId = Guid.NewGuid();
- dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
- await dbContext.SaveChangesAsync();
- return libraryId;
- }
-
- ///
- /// Seeds a for the library identified by .
- ///
- /// The Id of the media library.
- /// The rank of the provider.
- /// A task representing the asynchronous operation.
- private async Task SeedConfigurationAsync(Guid libraryId, int rank)
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: rank));
- await dbContext.SaveChangesAsync();
- }
-}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs
deleted file mode 100644
index ad92bf3c..00000000
--- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs
+++ /dev/null
@@ -1,126 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
-using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
-using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-using Lumina.Contracts.Requests.Plugins;
-using Lumina.DataAccess.Core.UoW;
-using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
-using Lumina.Presentation.Api.SecurityTests.Common.Setup;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.DependencyInjection;
-using System.Diagnostics.CodeAnalysis;
-using System.Net;
-using System.Net.Http.Json;
-using System.Text.Json;
-#endregion
-
-namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled;
-
-///
-/// Contains security tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class SetLibraryArtworkProviderEnabledEndpointTests : IClassFixture
-{
- private readonly HttpClient _client;
- private readonly LuminaApiFactory _apiFactory;
- private readonly JsonSerializerOptions _jsonOptions = new()
- {
- PropertyNameCaseInsensitive = true
- };
- private readonly LibraryEntityFixture _libraryEntityFixture = new();
- private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
- private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Injected in-memory API factory.
- public SetLibraryArtworkProviderEnabledEndpointTests(LuminaApiFactory apiFactory)
- {
- _apiFactory = apiFactory;
- _client = apiFactory.CreateClient();
- }
-
- [Fact]
- public async Task SetLibraryArtworkProviderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult()
- {
- // Arrange
- string libraryId = Guid.NewGuid().ToString();
- string pluginId = Guid.NewGuid().ToString();
- SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create();
-
- // Act
- HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request);
-
- // Assert
- Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
-
- string content = await response.Content.ReadAsStringAsync();
-
- Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
- Assert.NotNull(problemDetails);
- Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
- Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
- Assert.Equal("Unauthorized", problemDetails["title"].GetString());
- Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", problemDetails["instance"].GetProperty("value").GetString());
- Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
- }
-
- [Theory]
- [InlineData("' OR '1'='1")] // basic SQL injection
- [InlineData("'; DROP TABLE Libraries--")] // destructive injection
- public async Task SetLibraryArtworkProviderEnabled_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId)
- {
- // Arrange
- // authenticate with an admin user and seed a library with an artwork provider configuration, so valid ids would reach the handler
- HttpClient client = _apiFactory.CreateClient();
- Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
- Guid libraryId = await SeedLibraryAsync(userId);
- await SeedConfigurationAsync(libraryId);
- SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), isEnabled: true);
-
- // Act
- HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/artwork-providers/{Guid.NewGuid()}/enabled", request);
-
- // Assert
- // note: the {libraryId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler
- // note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding
- // ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here)
- // note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
- Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
- string content = await response.Content.ReadAsStringAsync();
- Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
- Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
- Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
- Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
- }
-
- ///
- /// Seeds a owned by .
- ///
- /// The Id of the user that owns the library.
- /// The Id of the seeded library.
- private async Task SeedLibraryAsync(Guid userId)
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- Guid libraryId = Guid.NewGuid();
- dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
- await dbContext.SaveChangesAsync();
- return libraryId;
- }
-
- ///
- /// Seeds a for the library identified by .
- ///
- /// The Id of the media library.
- /// A task representing the asynchronous operation.
- private async Task SeedConfigurationAsync(Guid libraryId)
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1, isEnabled: false));
- await dbContext.SaveChangesAsync();
- }
-}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs
deleted file mode 100644
index 8a5ccf4c..00000000
--- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-using Lumina.Contracts.Requests.Plugins;
-using Lumina.Presentation.Api.SecurityTests.Common.Setup;
-using Microsoft.AspNetCore.Http;
-using System.Diagnostics.CodeAnalysis;
-using System.Net;
-using System.Net.Http.Json;
-using System.Text.Json;
-#endregion
-
-namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled;
-
-///
-/// Contains security tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class SetLibraryBookReaderEnabledEndpointTests : IClassFixture
-{
- private readonly HttpClient _client;
- private readonly JsonSerializerOptions _jsonOptions = new()
- {
- PropertyNameCaseInsensitive = true
- };
- private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Injected in-memory API factory.
- public SetLibraryBookReaderEnabledEndpointTests(LuminaApiFactory apiFactory)
- {
- _client = apiFactory.CreateClient();
- }
-
- [Fact]
- public async Task SetLibraryBookReaderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult()
- {
- // Arrange
- Guid libraryId = Guid.NewGuid();
- Guid pluginId = Guid.NewGuid();
- SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true);
-
- // Act
- HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/book-readers/{pluginId}/enabled", request);
-
- // Assert
- Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
- string content = await response.Content.ReadAsStringAsync();
- Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
- Assert.NotNull(problemDetails);
- Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
- Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
- Assert.Equal("Unauthorized", problemDetails["title"].GetString());
- Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
- Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
- }
-
- [Theory]
- [InlineData("' OR '1'='1")] // basic SQL injection
- [InlineData("'; DROP TABLE LibraryBookReaderConfigurations--")] // destructive injection
- public async Task SetLibraryBookReaderEnabled_WithSQLInjectionInPluginId_ShouldNotLeakDatabaseDetails(string maliciousPluginId)
- {
- // Arrange
- SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(libraryId: Guid.NewGuid(), pluginId: Guid.NewGuid(), isEnabled: true);
-
- // Act
- HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/book-readers/{Uri.EscapeDataString(maliciousPluginId)}/enabled", request);
- string content = await response.Content.ReadAsStringAsync();
-
- // Assert
- Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
- Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
- Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
- Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
- }
-}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs
deleted file mode 100644
index 29fe12c0..00000000
--- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs
+++ /dev/null
@@ -1,126 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
-using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
-using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-using Lumina.Contracts.Requests.Plugins;
-using Lumina.DataAccess.Core.UoW;
-using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
-using Lumina.Presentation.Api.SecurityTests.Common.Setup;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.DependencyInjection;
-using System.Diagnostics.CodeAnalysis;
-using System.Net;
-using System.Net.Http.Json;
-using System.Text.Json;
-#endregion
-
-namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled;
-
-///
-/// Contains security tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture
-{
- private readonly HttpClient _client;
- private readonly LuminaApiFactory _apiFactory;
- private readonly JsonSerializerOptions _jsonOptions = new()
- {
- PropertyNameCaseInsensitive = true
- };
- private readonly LibraryEntityFixture _libraryEntityFixture = new();
- private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
- private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Injected in-memory API factory.
- public SetLibraryMetadataProviderEnabledEndpointTests(LuminaApiFactory apiFactory)
- {
- _apiFactory = apiFactory;
- _client = apiFactory.CreateClient();
- }
-
- [Fact]
- public async Task SetLibraryMetadataProviderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult()
- {
- // Arrange
- string libraryId = Guid.NewGuid().ToString();
- string pluginId = Guid.NewGuid().ToString();
- SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create();
-
- // Act
- HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", request);
-
- // Assert
- Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
-
- string content = await response.Content.ReadAsStringAsync();
-
- Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
- Assert.NotNull(problemDetails);
- Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
- Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
- Assert.Equal("Unauthorized", problemDetails["title"].GetString());
- Assert.Equal($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", problemDetails["instance"].GetProperty("value").GetString());
- Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
- }
-
- [Theory]
- [InlineData("' OR '1'='1")] // basic SQL injection
- [InlineData("'; DROP TABLE Libraries--")] // destructive injection
- public async Task SetLibraryMetadataProviderEnabled_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId)
- {
- // Arrange
- // authenticate with an admin user and seed a library with a metadata provider configuration, so valid ids would reach the handler
- HttpClient client = _apiFactory.CreateClient();
- Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
- Guid libraryId = await SeedLibraryAsync(userId);
- await SeedConfigurationAsync(libraryId);
- SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), isEnabled: true);
-
- // Act
- HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/metadata-providers/{Guid.NewGuid()}/enabled", request);
-
- // Assert
- // note: the {libraryId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler
- // note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding
- // ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here)
- // note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
- Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
- string content = await response.Content.ReadAsStringAsync();
- Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
- Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
- Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
- Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
- }
-
- ///
- /// Seeds a owned by .
- ///
- /// The Id of the user that owns the library.
- /// The Id of the seeded library.
- private async Task SeedLibraryAsync(Guid userId)
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- Guid libraryId = Guid.NewGuid();
- dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
- await dbContext.SaveChangesAsync();
- return libraryId;
- }
-
- ///
- /// Seeds a for the library identified by .
- ///
- /// The Id of the media library.
- /// A task representing the asynchronous operation.
- private async Task SeedConfigurationAsync(Guid libraryId)
- {
- using IServiceScope scope = _apiFactory.Services.CreateScope();
- LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
- dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1, isEnabled: false));
- await dbContext.SaveChangesAsync();
- }
-}
diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs
index 90e1620e..fbe67979 100644
--- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs
+++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.AddLibrary;
+using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
@@ -15,6 +16,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Managemen
public class AddLibraryViewEndpointTests : IClassFixture
{
private readonly LuminaWebFactory _apiFactory;
+ private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
///
/// Initializes a new instance of the class.
@@ -39,4 +41,20 @@ public class AddLibraryViewEndpointTests : IClassFixture
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
}
+
+ [Fact]
+ public async Task AddLibraryView_WhenTheUserLacksTheManagePermission_ShouldRedirectToAccessDenied()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage/item");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ Assert.Contains("access-denied", response.Headers.Location!.ToString());
+ }
}
diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs
index b0718dd1..ad8bc125 100644
--- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs
+++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.DeleteLibrary;
+using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
@@ -17,6 +18,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Managemen
public class DeleteLibraryEndpointTests : IClassFixture
{
private readonly LuminaWebFactory _apiFactory;
+ private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
///
/// Initializes a new instance of the class.
@@ -64,6 +66,47 @@ public class DeleteLibraryEndpointTests : IClassFixture
Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}");
}
+ [Fact]
+ public async Task DeleteLibrary_WhenTheUserLacksTheManagePermission_ShouldRedirectToAccessDeniedWithoutDeletingTheLibrary()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ Guid libraryId = Guid.NewGuid();
+ HttpRequestMessage deleteRequest = CreateDeleteRequest(libraryId);
+ deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ Assert.Contains("access-denied", response.Headers.Location!.ToString());
+ Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}");
+ }
+
+ [Fact]
+ public async Task DeleteLibrary_WhenAnAdministratorLacksTheManagePermission_ShouldForwardTheDeletion()
+ {
+ // Arrange
+ // The API lets administrators delete any library, so the Web must not refuse them for lacking the permission.
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ Guid libraryId = Guid.NewGuid();
+ _apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}");
+ HttpRequestMessage deleteRequest = CreateDeleteRequest(libraryId);
+ deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.Contains(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}");
+ }
+
///
/// Builds the delete request for the library identified by .
///
diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs
index 6d9e3879..f39b1aa6 100644
--- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs
+++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.EditLibrary;
+using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
@@ -15,6 +16,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Managemen
public class EditLibraryViewEndpointTests : IClassFixture
{
private readonly LuminaWebFactory _apiFactory;
+ private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
///
/// Initializes a new instance of the class.
@@ -41,4 +43,22 @@ public class EditLibraryViewEndpointTests : IClassFixture
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}");
}
+
+ [Fact]
+ public async Task EditLibraryView_WhenTheUserLacksTheManagePermission_ShouldRedirectToAccessDeniedWithoutLoadingTheLibrary()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ Guid libraryId = Guid.NewGuid();
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/item/{libraryId}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ Assert.Contains("access-denied", response.Headers.Location!.ToString());
+ Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}");
+ }
}
diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs
new file mode 100644
index 00000000..2b309332
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeArtworkProviders/GetLibraryTypeArtworkProvidersEndpointTests.cs
@@ -0,0 +1,67 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.Plugins;
+using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders;
+using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
+using Lumina.Presentation.Web.SecurityTests.Common.Setup;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+#endregion
+
+namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders;
+
+///
+/// Contains security tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeArtworkProvidersEndpointTests : IClassFixture
+{
+ private readonly LuminaWebFactory _apiFactory;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public GetLibraryTypeArtworkProvidersEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeArtworkProviders_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage/api-get-library-type-artwork-providers/Book");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
+ Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.Contains("artwork-providers", StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // Basic SQL injection.
+ [InlineData("'; DROP TABLE Libraries--")] // Destructive injection.
+ public async Task GetLibraryTypeArtworkProviders_WhenCalledWithInjectionInLibraryType_ShouldRemainSecure(string maliciousLibraryType)
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/artwork-providers/{Uri.EscapeDataString(maliciousLibraryType)}", Array.Empty());
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/api-get-library-type-artwork-providers/{Uri.EscapeDataString(maliciousLibraryType)}");
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs
new file mode 100644
index 00000000..065f247d
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeBookReaders/GetLibraryTypeBookReadersEndpointTests.cs
@@ -0,0 +1,67 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.Plugins;
+using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders;
+using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
+using Lumina.Presentation.Web.SecurityTests.Common.Setup;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+#endregion
+
+namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders;
+
+///
+/// Contains security tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeBookReadersEndpointTests : IClassFixture
+{
+ private readonly LuminaWebFactory _apiFactory;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public GetLibraryTypeBookReadersEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeBookReaders_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage/api-get-library-type-book-readers/Book");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
+ Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.Contains("book-readers", StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // Basic SQL injection.
+ [InlineData("'; DROP TABLE Libraries--")] // Destructive injection.
+ public async Task GetLibraryTypeBookReaders_WhenCalledWithInjectionInLibraryType_ShouldRemainSecure(string maliciousLibraryType)
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/book-readers/{Uri.EscapeDataString(maliciousLibraryType)}", Array.Empty());
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/api-get-library-type-book-readers/{Uri.EscapeDataString(maliciousLibraryType)}");
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs
new file mode 100644
index 00000000..fe75a189
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraryTypeMetadataProviders/GetLibraryTypeMetadataProvidersEndpointTests.cs
@@ -0,0 +1,67 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.Plugins;
+using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders;
+using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
+using Lumina.Presentation.Web.SecurityTests.Common.Setup;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+#endregion
+
+namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders;
+
+///
+/// Contains security tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeMetadataProvidersEndpointTests : IClassFixture
+{
+ private readonly LuminaWebFactory _apiFactory;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public GetLibraryTypeMetadataProvidersEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task GetLibraryTypeMetadataProviders_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage/api-get-library-type-metadata-providers/Book");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
+ Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.Contains("metadata-providers", StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // Basic SQL injection.
+ [InlineData("'; DROP TABLE Libraries--")] // Destructive injection.
+ public async Task GetLibraryTypeMetadataProviders_WhenCalledWithInjectionInLibraryType_ShouldRemainSecure(string maliciousLibraryType)
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/metadata-providers/{Uri.EscapeDataString(maliciousLibraryType)}", Array.Empty());
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/api-get-library-type-metadata-providers/{Uri.EscapeDataString(maliciousLibraryType)}");
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs
deleted file mode 100644
index 2fc62af3..00000000
--- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs
+++ /dev/null
@@ -1,89 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Presentation.Web.Common.Requests.Plugins;
-using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderMetadataProviders;
-using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
-using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
-using Lumina.Presentation.Web.SecurityTests.Common.Setup;
-using System.Diagnostics.CodeAnalysis;
-using System.Net;
-using System.Net.Http.Headers;
-using System.Net.Http.Json;
-#endregion
-
-namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.ReorderMetadataProviders;
-
-///
-/// Contains security tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class ReorderMetadataProvidersEndpointTests : IClassFixture
-{
- private readonly LuminaWebFactory _apiFactory;
- private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Injected Web application factory.
- public ReorderMetadataProvidersEndpointTests(LuminaWebFactory apiFactory)
- {
- _apiFactory = apiFactory;
- }
-
- [Fact]
- public async Task ReorderMetadataProviders_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
- {
- // Arrange
- _apiFactory.ApiClientStub.Reset();
- HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
- string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
- Guid libraryId = Guid.NewGuid();
- HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId);
- updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
-
- // Act
- HttpResponseMessage response = await client.SendAsync(updateRequest);
-
- // Assert
- Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
- Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
- Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/reorder");
- }
-
- [Fact]
- public async Task ReorderMetadataProviders_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
- {
- // Arrange
- _apiFactory.ApiClientStub.Reset();
- AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
- Guid libraryId = Guid.NewGuid();
- HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId);
-
- // Act
- HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
-
- // Assert
- Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
- Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/reorder");
- }
-
- ///
- /// Builds the update request that reorders the metadata providers of the library identified by .
- ///
- /// The Id of the media library.
- /// The configured update request.
- private HttpRequestMessage CreateUpdateRequest(Guid libraryId)
- {
- ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(
- libraryId: libraryId,
- pluginIds: [Guid.NewGuid(), Guid.NewGuid()]
- );
- HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-reorder-metadata-providers")
- {
- Content = JsonContent.Create(request)
- };
- updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
- updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- return updateRequest;
- }
-}
diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs
index b47dd931..03761e5f 100644
--- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs
+++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs
@@ -1,7 +1,9 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Libraries;
+using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
+using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
@@ -20,6 +22,7 @@ public class SaveLibraryEndpointTests : IClassFixture
{
private readonly LuminaWebFactory _apiFactory;
private readonly LibraryDtoFixture _libraryDtoFixture = new();
+ private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
///
/// Initializes a new instance of the class.
@@ -34,7 +37,7 @@ public class SaveLibraryEndpointTests : IClassFixture
public async Task SaveLibrary_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
{
// Arrange
- _apiFactory.ApiClientStub.Reset();
+ ResetApiStub();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage saveRequest = CreateSaveRequest(_libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book"));
@@ -50,7 +53,7 @@ public class SaveLibraryEndpointTests : IClassFixture
public async Task SaveLibrary_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequest()
{
// Arrange
- _apiFactory.ApiClientStub.Reset();
+ ResetApiStub();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage saveRequest = CreateSaveRequest(_libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book"));
saveRequest.Headers.Remove("RequestVerificationToken");
@@ -64,11 +67,52 @@ public class SaveLibraryEndpointTests : IClassFixture
Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries");
}
+ [Fact]
+ public async Task SaveLibrary_WhenTheUserLacksTheManagePermission_ShouldRedirectToAccessDeniedWithoutSaving()
+ {
+ // Arrange
+ ResetApiStub();
+ _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage saveRequest = CreateSaveRequest(_libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book"));
+ saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ Assert.Contains("access-denied", response.Headers.Location!.ToString());
+ Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries");
+ }
+
+ [Fact]
+ public async Task SaveLibrary_WhenAnAdministratorLacksTheManagePermission_ShouldForwardTheSave()
+ {
+ // Arrange
+ // The API lets administrators save any library, so the Web must not refuse them for lacking the permission.
+ ResetApiStub();
+ _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ LibraryDto request = _libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book");
+ request.Id = null;
+ _apiFactory.ApiClientStub.RegisterPostResponse("libraries", _libraryDtoFixture.Create(id: Guid.NewGuid(), title: request.Title, libraryType: request.LibraryType));
+ HttpRequestMessage saveRequest = CreateSaveRequest(request);
+ saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries");
+ }
+
[Fact]
public async Task SaveLibrary_WhenCalledWithInjectionInLibraryTitle_ShouldRemainSecure()
{
// Arrange
- _apiFactory.ApiClientStub.Reset();
+ ResetApiStub();
LibraryDto request = _libraryDtoFixture.Create(title: "'; DROP TABLE Libraries--", libraryType: "Book");
request.Id = null;
_apiFactory.ApiClientStub.RegisterPostResponse("libraries", _libraryDtoFixture.Create(id: Guid.NewGuid(), title: request.Title, libraryType: request.LibraryType));
@@ -85,6 +129,18 @@ public class SaveLibraryEndpointTests : IClassFixture
Assert.DoesNotContain("Exception", content);
}
+ ///
+ /// Resets the stubbed API client and restores the authorization state of an administrator with every permission, because the stub is shared by all the tests of the class.
+ ///
+ private void ResetApiStub()
+ {
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(
+ userId: Guid.NewGuid(),
+ role: "Admin",
+ permissions: Enum.GetValues());
+ }
+
///
/// Builds the save request that sends the given to the library save endpoint.
///
diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs
deleted file mode 100644
index add45a9f..00000000
--- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointTests.cs
+++ /dev/null
@@ -1,81 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Presentation.Web.Common.Requests.Plugins;
-using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetBookReaderEnabled;
-using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
-using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
-using Lumina.Presentation.Web.SecurityTests.Common.Setup;
-using System;
-using System.Diagnostics.CodeAnalysis;
-using System.Net;
-using System.Net.Http;
-using System.Net.Http.Headers;
-using System.Net.Http.Json;
-using System.Threading.Tasks;
-#endregion
-
-namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.SetBookReaderEnabled;
-
-///
-/// Contains security tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class SetBookReaderEnabledEndpointTests : IClassFixture
-{
- private readonly LuminaWebFactory _apiFactory;
- private readonly SetBookReaderEnabledRequestFixture _setBookReaderEnabledRequestFixture = new();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Injected Web application factory.
- public SetBookReaderEnabledEndpointTests(LuminaWebFactory apiFactory)
- {
- _apiFactory = apiFactory;
- }
-
- [Fact]
- public async Task SetBookReaderEnabled_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
- {
- // Arrange
- HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
- SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create();
- HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled")
- {
- Content = JsonContent.Create(request)
- };
- updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
-
- // Act
- HttpResponseMessage response = await client.SendAsync(updateRequest);
-
- // Assert
- Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
- Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
- }
-
- [Fact]
- public async Task SetBookReaderEnabled_WhenCalledWithoutAntiforgeryToken_ShouldReturnBadRequest()
- {
- // Arrange
- _apiFactory.ApiClientStub.Reset();
- AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
- SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create();
- HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-book-reader-enabled")
- {
- Content = JsonContent.Create(request)
- };
- updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
-
- // Act
- HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
- string content = await response.Content.ReadAsStringAsync();
-
- // Assert
- Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
- Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
- Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
- Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
- Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
- Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
- }
-}
diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs
deleted file mode 100644
index fb13897e..00000000
--- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs
+++ /dev/null
@@ -1,93 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Presentation.Web.Common.Requests.Plugins;
-using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetMetadataProviderEnabled;
-using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
-using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
-using Lumina.Presentation.Web.SecurityTests.Common.Setup;
-using System.Diagnostics.CodeAnalysis;
-using System.Net;
-using System.Net.Http.Headers;
-using System.Net.Http.Json;
-#endregion
-
-namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.SetMetadataProviderEnabled;
-
-///
-/// Contains security tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class SetMetadataProviderEnabledEndpointTests : IClassFixture
-{
- private readonly LuminaWebFactory _apiFactory;
- private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Injected Web application factory.
- public SetMetadataProviderEnabledEndpointTests(LuminaWebFactory apiFactory)
- {
- _apiFactory = apiFactory;
- }
-
- [Fact]
- public async Task SetMetadataProviderEnabled_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
- {
- // Arrange
- _apiFactory.ApiClientStub.Reset();
- HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
- string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
- Guid libraryId = Guid.NewGuid();
- Guid pluginId = Guid.NewGuid();
- HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId, pluginId);
- updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
-
- // Act
- HttpResponseMessage response = await client.SendAsync(updateRequest);
-
- // Assert
- Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
- Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
- Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/{pluginId}/enabled");
- }
-
- [Fact]
- public async Task SetMetadataProviderEnabled_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
- {
- // Arrange
- _apiFactory.ApiClientStub.Reset();
- AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
- Guid libraryId = Guid.NewGuid();
- Guid pluginId = Guid.NewGuid();
- HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId, pluginId);
-
- // Act
- HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
-
- // Assert
- Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
- Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/{pluginId}/enabled");
- }
-
- ///
- /// Builds the update request that enables the metadata provider of the library identified by and .
- ///
- /// The Id of the media library.
- /// The Id of the plugin providing the metadata.
- /// The configured update request.
- private HttpRequestMessage CreateUpdateRequest(Guid libraryId, Guid pluginId)
- {
- SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(
- libraryId: libraryId,
- pluginId: pluginId,
- isEnabled: true
- );
- HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-metadata-provider-enabled")
- {
- Content = JsonContent.Create(request)
- };
- updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
- updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- return updateRequest;
- }
-}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs
index 427a8c83..594d14a9 100644
--- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs
@@ -1,10 +1,13 @@
#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
using System.Diagnostics.CodeAnalysis;
+using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
@@ -16,6 +19,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
public class AddMediaLibraryRequestMappingTests
{
private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new();
+ private readonly LibraryProviderSelectionRequestFixture _libraryProviderSelectionRequestFixture = new();
private readonly LibraryPathTemplatePartRequestFixture _libraryPathTemplatePartRequestFixture = new();
[Fact]
@@ -245,4 +249,85 @@ public class AddMediaLibraryRequestMappingTests
Assert.False(result.ShouldTrackConsumptionProgress.Value);
Assert.Null(result.CompletionThresholdPercentage);
}
+
+ [Fact]
+ public void ToCommand_WhenProviderChoicesAreProvided_ShouldMapThemInOrder()
+ {
+ // Arrange
+ LibraryProviderSelectionRequest[] metadataProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true), _libraryProviderSelectionRequestFixture.Create(isEnabled: false)];
+ LibraryProviderSelectionRequest[] artworkProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: false)];
+ LibraryProviderSelectionRequest[] bookReaders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true)];
+ AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: metadataProviders, artworkProviders: artworkProviders, bookReaders: bookReaders);
+
+ // Act
+ AddLibraryCommand result = request.ToCommand();
+
+ // Assert
+ Assert.Equal(metadataProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.MetadataProviders!.Select(selection => (selection.PluginId, selection.IsEnabled)));
+ Assert.Equal(artworkProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.ArtworkProviders!.Select(selection => (selection.PluginId, selection.IsEnabled)));
+ Assert.Equal(bookReaders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.BookReaders!.Select(selection => (selection.PluginId, selection.IsEnabled)));
+ }
+
+ [Fact]
+ public void ToCommand_WhenProviderChoicesAreNotProvided_ShouldMapThemAsNull()
+ {
+ // Arrange
+ AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: null, artworkProviders: null, bookReaders: null);
+
+ // Act
+ AddLibraryCommand result = request.ToCommand();
+
+ // Assert
+ Assert.Null(result.MetadataProviders);
+ Assert.Null(result.ArtworkProviders);
+ Assert.Null(result.BookReaders);
+ }
+
+ [Fact]
+ public void ToCommand_WhenAProviderChoiceIsNull_ShouldMapItToAChoiceWithoutPluginId()
+ {
+ // Arrange
+ AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: [null], artworkProviders: [null], bookReaders: [null]);
+
+ // Act
+ AddLibraryCommand result = request.ToCommand();
+
+ // Assert
+ Assert.Equal(Guid.Empty, Assert.Single(result.MetadataProviders!).PluginId);
+ Assert.Null(result.MetadataProviders![0].IsEnabled);
+ Assert.Equal(Guid.Empty, Assert.Single(result.ArtworkProviders!).PluginId);
+ Assert.Equal(Guid.Empty, Assert.Single(result.BookReaders!).PluginId);
+ }
+
+ [Fact]
+ public void ToCommand_WhenAPathTemplatePartIsNull_ShouldMapItToAPartWithoutKind()
+ {
+ // Arrange
+ AddLibraryRequest request = _addLibraryRequestFixture.Create(pathTemplateParts: [null]);
+
+ // Act
+ AddLibraryCommand result = request.ToCommand();
+
+ // Assert
+ LibraryPathTemplatePartDto part = Assert.Single(result.PathTemplateParts!);
+ Assert.Null(part.Kind);
+ Assert.Null(part.Representation);
+ Assert.False(part.IsOptional);
+ }
+
+ [Fact]
+ public void ToCommand_WhenAProviderChoiceHasNoEnabledState_ShouldMapTheStateAsNull()
+ {
+ // Arrange
+ LibraryProviderSelectionRequest choice = _libraryProviderSelectionRequestFixture.Create(includeIsEnabled: false);
+ AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: [choice]);
+
+ // Act
+ AddLibraryCommand result = request.ToCommand();
+
+ // Assert
+ LibraryProviderSelectionDto mappedChoice = Assert.Single(result.MetadataProviders!);
+ Assert.Equal(choice.PluginId, mappedChoice.PluginId);
+ Assert.Null(mappedChoice.IsEnabled);
+ }
}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs
index 9675c2b9..e160d948 100644
--- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs
@@ -1,10 +1,13 @@
#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
using System.Diagnostics.CodeAnalysis;
+using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
@@ -16,6 +19,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
public class UpdateLibraryRequestMappingTests
{
private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new();
+ private readonly LibraryProviderSelectionRequestFixture _libraryProviderSelectionRequestFixture = new();
private readonly LibraryPathTemplatePartRequestFixture _libraryPathTemplatePartRequestFixture = new();
[Fact]
@@ -148,4 +152,85 @@ public class UpdateLibraryRequestMappingTests
Assert.False(result.ShouldTrackConsumptionProgress.Value);
Assert.Null(result.CompletionThresholdPercentage);
}
+
+ [Fact]
+ public void ToCommand_WhenProviderChoicesAreProvided_ShouldMapThemInOrder()
+ {
+ // Arrange
+ LibraryProviderSelectionRequest[] metadataProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true), _libraryProviderSelectionRequestFixture.Create(isEnabled: false)];
+ LibraryProviderSelectionRequest[] artworkProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: false)];
+ LibraryProviderSelectionRequest[] bookReaders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true)];
+ UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: metadataProviders, artworkProviders: artworkProviders, bookReaders: bookReaders);
+
+ // Act
+ UpdateLibraryCommand result = request.ToCommand();
+
+ // Assert
+ Assert.Equal(metadataProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.MetadataProviders!.Select(selection => (selection.PluginId, selection.IsEnabled)));
+ Assert.Equal(artworkProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.ArtworkProviders!.Select(selection => (selection.PluginId, selection.IsEnabled)));
+ Assert.Equal(bookReaders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.BookReaders!.Select(selection => (selection.PluginId, selection.IsEnabled)));
+ }
+
+ [Fact]
+ public void ToCommand_WhenProviderChoicesAreNotProvided_ShouldMapThemAsNull()
+ {
+ // Arrange
+ UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: null, artworkProviders: null, bookReaders: null);
+
+ // Act
+ UpdateLibraryCommand result = request.ToCommand();
+
+ // Assert
+ Assert.Null(result.MetadataProviders);
+ Assert.Null(result.ArtworkProviders);
+ Assert.Null(result.BookReaders);
+ }
+
+ [Fact]
+ public void ToCommand_WhenAProviderChoiceIsNull_ShouldMapItToAChoiceWithoutPluginId()
+ {
+ // Arrange
+ UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: [null], artworkProviders: [null], bookReaders: [null]);
+
+ // Act
+ UpdateLibraryCommand result = request.ToCommand();
+
+ // Assert
+ Assert.Equal(Guid.Empty, Assert.Single(result.MetadataProviders!).PluginId);
+ Assert.Null(result.MetadataProviders![0].IsEnabled);
+ Assert.Equal(Guid.Empty, Assert.Single(result.ArtworkProviders!).PluginId);
+ Assert.Equal(Guid.Empty, Assert.Single(result.BookReaders!).PluginId);
+ }
+
+ [Fact]
+ public void ToCommand_WhenAPathTemplatePartIsNull_ShouldMapItToAPartWithoutKind()
+ {
+ // Arrange
+ UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(pathTemplateParts: [null]);
+
+ // Act
+ UpdateLibraryCommand result = request.ToCommand();
+
+ // Assert
+ LibraryPathTemplatePartDto part = Assert.Single(result.PathTemplateParts!);
+ Assert.Null(part.Kind);
+ Assert.Null(part.Representation);
+ Assert.False(part.IsOptional);
+ }
+
+ [Fact]
+ public void ToCommand_WhenAProviderChoiceHasNoEnabledState_ShouldMapTheStateAsNull()
+ {
+ // Arrange
+ LibraryProviderSelectionRequest choice = _libraryProviderSelectionRequestFixture.Create(includeIsEnabled: false);
+ UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: [choice]);
+
+ // Act
+ UpdateLibraryCommand result = request.ToCommand();
+
+ // Assert
+ LibraryProviderSelectionDto mappedChoice = Assert.Single(result.MetadataProviders!);
+ Assert.Equal(choice.PluginId, mappedChoice.PluginId);
+ Assert.Null(mappedChoice.IsEnabled);
+ }
}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeArtworkProvidersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeArtworkProvidersRequestMappingTests.cs
new file mode 100644
index 00000000..79126c8a
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeArtworkProvidersRequestMappingTests.cs
@@ -0,0 +1,32 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Mapping.Plugins;
+using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders;
+using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
+using Lumina.Contracts.Requests.Plugins;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeArtworkProvidersRequestMappingTests
+{
+ private readonly GetLibraryTypeArtworkProvidersRequestFixture _getLibraryTypeArtworkProvidersRequestFixture = new();
+
+ [Fact]
+ public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
+ {
+ // Arrange
+ GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(libraryType: "Music");
+
+ // Act
+ GetLibraryTypeArtworkProvidersQuery result = request.ToQuery();
+
+ // Assert
+ Assert.NotNull(result);
+ Assert.Equal(request.LibraryType, result.LibraryType);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeBookReadersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeBookReadersRequestMappingTests.cs
new file mode 100644
index 00000000..76595851
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeBookReadersRequestMappingTests.cs
@@ -0,0 +1,32 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Mapping.Plugins;
+using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders;
+using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
+using Lumina.Contracts.Requests.Plugins;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeBookReadersRequestMappingTests
+{
+ private readonly GetLibraryTypeBookReadersRequestFixture _getLibraryTypeBookReadersRequestFixture = new();
+
+ [Fact]
+ public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
+ {
+ // Arrange
+ GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(libraryType: "Music");
+
+ // Act
+ GetLibraryTypeBookReadersQuery result = request.ToQuery();
+
+ // Assert
+ Assert.NotNull(result);
+ Assert.Equal(request.LibraryType, result.LibraryType);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeMetadataProvidersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeMetadataProvidersRequestMappingTests.cs
new file mode 100644
index 00000000..32629e3b
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryTypeMetadataProvidersRequestMappingTests.cs
@@ -0,0 +1,32 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Mapping.Plugins;
+using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders;
+using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
+using Lumina.Contracts.Requests.Plugins;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibraryTypeMetadataProvidersRequestMappingTests
+{
+ private readonly GetLibraryTypeMetadataProvidersRequestFixture _getLibraryTypeMetadataProvidersRequestFixture = new();
+
+ [Fact]
+ public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
+ {
+ // Arrange
+ GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(libraryType: "Music");
+
+ // Act
+ GetLibraryTypeMetadataProvidersQuery result = request.ToQuery();
+
+ // Assert
+ Assert.NotNull(result);
+ Assert.Equal(request.LibraryType, result.LibraryType);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMappingTests.cs
deleted file mode 100644
index eb922a18..00000000
--- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMappingTests.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Application.Common.Mapping.Plugins;
-using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
-using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-using Lumina.Contracts.Requests.Plugins;
-using System.Diagnostics.CodeAnalysis;
-#endregion
-
-namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
-
-///
-/// Contains unit tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class ReorderLibraryArtworkProvidersRequestMappingTests
-{
- private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new();
-
- [Fact]
- public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
- {
- // Arrange
- ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create();
-
- // Act
- ReorderLibraryArtworkProvidersCommand result = request.ToCommand();
-
- // Assert
- Assert.Equal(request.LibraryId, result.LibraryId);
- Assert.Equal(request.PluginIds, result.PluginIds);
- }
-}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMappingTests.cs
deleted file mode 100644
index d88564a1..00000000
--- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMappingTests.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Application.Common.Mapping.Plugins;
-using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
-using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-using Lumina.Contracts.Requests.Plugins;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
-#endregion
-
-namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
-
-///
-/// Contains unit tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class ReorderLibraryMetadataProvidersRequestMappingTests
-{
- private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new();
-
- [Fact]
- public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
- {
- // Arrange
- ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(Guid.NewGuid(), [Guid.NewGuid(), Guid.NewGuid()]);
-
- // Act
- ReorderLibraryMetadataProvidersCommand result = request.ToCommand();
-
- // Assert
- Assert.NotNull(result);
- Assert.Equal(request.LibraryId, result.LibraryId);
- Assert.Equal(request.PluginIds, result.PluginIds);
- }
-}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMappingTests.cs
deleted file mode 100644
index b4ce861a..00000000
--- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMappingTests.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Application.Common.Mapping.Plugins;
-using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
-using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-using Lumina.Contracts.Requests.Plugins;
-using System.Diagnostics.CodeAnalysis;
-#endregion
-
-namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
-
-///
-/// Contains unit tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class SetLibraryArtworkProviderEnabledRequestMappingTests
-{
- private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new();
-
- [Fact]
- public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
- {
- // Arrange
- SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(isEnabled: true);
-
- // Act
- SetLibraryArtworkProviderEnabledCommand result = request.ToCommand();
-
- // Assert
- Assert.Equal(request.LibraryId, result.LibraryId);
- Assert.Equal(request.PluginId, result.PluginId);
- Assert.Equal(request.IsEnabled, result.IsEnabled);
- }
-}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMappingTests.cs
deleted file mode 100644
index cec75047..00000000
--- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryBookReaderEnabledRequestMappingTests.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Application.Common.Mapping.Plugins;
-using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
-using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-using Lumina.Contracts.Requests.Plugins;
-using System.Diagnostics.CodeAnalysis;
-#endregion
-
-namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
-
-///
-/// Contains unit tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class SetLibraryBookReaderEnabledRequestMappingTests
-{
- private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new();
-
- [Fact]
- public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
- {
- // Arrange
- SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create();
-
- // Act
- SetLibraryBookReaderEnabledCommand result = request.ToCommand();
-
- // Assert
- Assert.NotNull(result);
- Assert.Equal(request.LibraryId, result.LibraryId);
- Assert.Equal(request.PluginId, result.PluginId);
- Assert.Equal(request.IsEnabled, result.IsEnabled);
- }
-}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMappingTests.cs
deleted file mode 100644
index 26376d27..00000000
--- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMappingTests.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using Lumina.Application.Common.Mapping.Plugins;
-using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
-using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
-using Lumina.Contracts.Requests.Plugins;
-using System;
-using System.Diagnostics.CodeAnalysis;
-#endregion
-
-namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
-
-///
-/// Contains unit tests for the class.
-///
-[ExcludeFromCodeCoverage]
-public class SetLibraryMetadataProviderEnabledRequestMappingTests
-{
- private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new();
-
- [Fact]
- public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
- {
- // Arrange
- SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(Guid.NewGuid(), Guid.NewGuid(), true);
-
- // Act
- SetLibraryMetadataProviderEnabledCommand result = request.ToCommand();
-
- // Assert
- Assert.NotNull(result);
- Assert.Equal(request.LibraryId, result.LibraryId);
- Assert.Equal(request.PluginId, result.PluginId);
- Assert.Equal(request.IsEnabled, result.IsEnabled);
- }
-}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs
index ded42481..677d7291 100644
--- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs
@@ -56,6 +56,7 @@ public class AddLibraryCommandHandlerTests
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
+ private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new();
private readonly Guid _userId;
///
@@ -76,14 +77,14 @@ public class AddLibraryCommandHandlerTests
_mockValidator = Substitute.For>();
_userId = Guid.NewGuid();
- // default stubs: the current user is authenticated, is an admin, the cover image is a valid image, and the provider configurations are seeded successfully
+ // Default stubs: the current user is authenticated, is an admin, the cover image is a valid image, and the provider configurations are seeded successfully.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true);
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any())
.Returns(Result.From(ImageType.PNG));
_mockLibraryRepository.InsertAsync(Arg.Any(), Arg.Any())
.Returns(Result.Created);
- _mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any())
+ _mockProviderConfigurationStore.ConfigureProvidersAsync(Arg.Any(), Arg.Any(), Arg.Any?>(), Arg.Any?>(), Arg.Any?>(), Arg.Any(), Arg.Any())
.Returns(Result.Success);
_mockValidator.Validate(Arg.Any()).Returns([]);
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(Result.From(LibraryPathTemplate.Empty()));
@@ -107,8 +108,8 @@ public class AddLibraryCommandHandlerTests
Assert.False(result.IsFailure);
Assert.Equal(persistedLibrary.Id, result.Value.Id);
await _mockLibraryRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any());
- await _mockProviderConfigurationStore.Received(1).EnsureProviderConfigurationsAsync(
- Arg.Any(), Arg.Is(libraryType => libraryType == Enum.Parse(command.LibraryType)), Arg.Any());
+ await _mockProviderConfigurationStore.Received(1).ConfigureProvidersAsync(
+ Arg.Any(), Arg.Is(libraryType => libraryType == Enum.Parse