From 7aeed04255fabaafba44ec47d5b26364f8eae598 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 24 Aug 2026 14:19:45 -0700 Subject: [PATCH] Adds test fixtures and endpoint test coverage --- .../DTO/Filtering/BaseFilterDtoFixture.cs | 41 +++++ .../DTO/Filtering/LibraryFilterDtoFixture.cs | 52 ++++++ .../Pagination/PaginatedResultDtoFixture.cs | 55 +++++++ .../Pagination/PaginationDataDtoFixture.cs | 45 +++++ .../Authorization/RoleEntityFixture.cs | 61 +++++++ .../Entities/Common/GenreEntityFixture.cs | 41 +++++ .../Entities/Common/TagEntityFixture.cs | 41 +++++ .../BookLibrary/IsbnEntityFixture.cs | 46 ++++++ .../DTO/Themes/ThemeArchiveDtoFixture.cs | 46 ++++++ .../Models/DTO/Themes/ThemeAssetDtoFixture.cs | 43 +++++ .../GetPermissionsQueryFixture.cs | 34 ++++ .../CheckInitializationQueryFixture.cs | 34 ++++ .../CancelLibrariesScanCommandFixture.cs | 34 ++++ .../ScanLibrariesCommandFixture.cs | 34 ++++ .../GetEnabledLibrariesQueryFixture.cs | 34 ++++ .../GetLibraries/GetLibrariesQueryFixture.cs | 34 ++++ .../GetRunningLibraryScansQueryFixture.cs | 34 ++++ .../GetPlugins/GetPluginsQueryFixture.cs | 34 ++++ .../GetUserSettingsQueryFixture.cs | 34 ++++ .../Core/DTO/Common/GenreDtoFixture.cs | 41 +++++ .../Core/DTO/Common/LanguageInfoDtoFixture.cs | 46 ++++++ .../Core/DTO/Common/ReleaseInfoDtoFixture.cs | 53 ++++++ .../Core/DTO/Common/TagDtoFixture.cs | 41 +++++ .../MediaContributorDtoFixture.cs | 45 +++++ .../MediaContributorNameDtoFixture.cs | 43 +++++ .../MediaContributorRoleDtoFixture.cs | 43 +++++ .../WrittenContentMetadataDtoFixture.cs | 65 ++++++++ .../Authorization/AddRoleRequestFixture.cs | 42 +++++ .../Authorization/DeleteRoleRequestFixture.cs | 40 +++++ .../GetRolePermissionsRequestFixture.cs | 37 +++++ .../GetUserPermissionsRequestFixture.cs | 37 +++++ .../GetUserRoleRequestFixture.cs | 37 +++++ .../Books/GetBookRequestFixture.cs | 37 +++++ .../ChangePasswordResponseFixture.cs | 39 +++++ .../Authentication/LoginResponseFixture.cs | 50 ++++++ .../RecoverPasswordResponseFixture.cs | 39 +++++ .../AuthorizationResponseFixture.cs | 48 ++++++ .../Authorization/RoleResponseFixture.cs | 42 +++++ .../FileSystemTypeResponseFixture.cs | 40 +++++ .../Path/PathExistsResponseFixture.cs | 39 +++++ .../Path/PathValidResponseFixture.cs | 39 +++++ .../MediaLibraryScanResponseFixture.cs | 39 +++++ .../InitializationResponseFixture.cs | 39 +++++ .../Common/PaginatedResponseFixture.cs | 55 +++++++ .../DTO/Authorization/PermissionDtoFixture.cs | 46 ++++++ .../RolePermissionsDtoFixture.cs | 43 +++++ .../DTO/Common/ProblemDetailsDtoFixture.cs | 54 ++++++ .../EncryptionSettingsDtoFixture.cs | 42 +++++ .../ServerConfigurationDtoFixture.cs | 48 ++++++ .../BlobDataDtoFixture.cs | 45 +++++ .../DirectoryDtoFixture.cs | 54 ++++++ .../FileSystemManagement/FileDtoFixture.cs | 52 ++++++ .../FileSystemTreeNodeDtoFixture.cs | 54 ++++++ .../FileSystemTypeDtoFixture.cs | 43 +++++ .../PathExistsDtoFixture.cs | 41 +++++ .../PathSegmentDtoFixture.cs | 42 +++++ .../PathSeparatorDtoFixture.cs | 41 +++++ .../PathValidDtoFixture.cs | 41 +++++ .../DTO/Libraries/BookLiteDtoFixture.cs | 56 +++++++ .../LibraryScanJobProgressDtoFixture.cs | 53 ++++++ .../LibraryScanProgressDtoFixture.cs | 66 ++++++++ .../Libraries/PaginatedBookLiteDtoFixture.cs | 54 ++++++ .../DTO/Themes/ThemeLayoutPageDtoFixture.cs | 46 ++++++ .../DTO/Themes/ThemeNavEntryDtoFixture.cs | 53 ++++++ .../DTO/Themes/ThemeNavSectionDtoFixture.cs | 44 +++++ .../Themes/ThemePageRenderResultDtoFixture.cs | 44 +++++ .../DTO/UsersManagement/UserDtoFixture.cs | 45 +++++ .../Authorization/UpdateRoleRequestFixture.cs | 48 ++++++ ...ateUserRoleAndPermissionsRequestFixture.cs | 45 +++++ .../Books/GetBooksViewRequestFixture.cs | 39 +++++ .../Themes/DeleteThemeRequestFixture.cs | 38 +++++ .../Themes/GetThemeArchiveRequestFixture.cs | 38 +++++ .../Themes/GetThemeAssetRequestFixture.cs | 41 +++++ .../Themes/RestoreThemeRequestFixture.cs | 38 +++++ .../Themes/SetCurrentThemeRequestFixture.cs | 38 +++++ .../GetAuthorizationResponseFixture.cs | 49 ++++++ .../ChangePasswordResponseFixture.cs | 39 +++++ .../RecoverPasswordResponseFixture.cs | 39 +++++ .../RegisterResponseFixture.cs | 44 +++++ .../Roles/AddRole/AddRoleEndpointTests.cs | 93 +++++++++++ .../DeleteRole/DeleteRoleEndpointTests.cs | 89 ++++++++++ .../GetRolePermissionsEndpointTests.cs | 78 +++++++++ .../UpdateRole/UpdateRoleEndpointTests.cs | 93 +++++++++++ .../ManagePermissionsViewEndpointTests.cs | 78 +++++++++ .../ManageRolesViewEndpointTests.cs | 73 +++++++++ .../DeleteTheme/DeleteThemeEndpointTests.cs | 82 ++++++++++ .../DownloadThemeEndpointTests.cs | 70 ++++++++ .../GetThemes/GetThemesEndpointTests.cs | 69 ++++++++ .../InstallTheme/InstallThemeEndpointTests.cs | 96 +++++++++++ .../RestoreTheme/RestoreThemeEndpointTests.cs | 64 ++++++++ .../SetCurrentThemeEndpointTests.cs | 65 ++++++++ .../Themes/ThemesIndexViewEndpointTests.cs | 54 ++++++ .../GetUserPermissionsEndpointTests.cs | 78 +++++++++ .../GetUserRole/GetUserRoleEndpointTests.cs | 78 +++++++++ ...dateUserRoleAndPermissionsEndpointTests.cs | 94 +++++++++++ .../GetDirectoriesEndpointTests.cs | 61 +++++++ .../GetDrives/GetDrivesEndpointTests.cs | 58 +++++++ .../GetType/GetTypeEndpointTests.cs | 57 +++++++ .../Files/GetFiles/GetFilesEndpointTests.cs | 61 +++++++ .../GetTreeFiles/GetTreeFilesEndpointTests.cs | 61 +++++++ .../CheckPathExistsEndpointTests.cs | 59 +++++++ .../GetPathParentEndpointTests.cs | 61 +++++++ .../GetPathRoot/GetPathRootEndpointTests.cs | 59 +++++++ .../GetPathSeparatorEndpointTests.cs | 57 +++++++ .../Path/SplitPath/SplitPathEndpointTests.cs | 66 ++++++++ .../ValidatePath/ValidatePathEndpointTests.cs | 59 +++++++ .../Endpoints/Home/HomeErrorEndpointTests.cs | 46 ++++++ .../Home/HomeNotFoundViewEndpointTests.cs | 44 +++++ .../Home/HomePrivacyEndpointTests.cs | 46 ++++++ .../AddLibrary/AddLibraryViewEndpointTests.cs | 45 +++++ .../CancelLibrariesScanEndpointTests.cs | 71 ++++++++ .../CancelLibraryScanEndpointTests.cs | 74 +++++++++ .../DeleteLibraryEndpointTests.cs | 74 +++++++++ .../EditLibraryViewEndpointTests.cs | 53 ++++++ .../GetEnabledLibrariesEndpointTests.cs | 82 ++++++++++ .../GetMetadataProvidersEndpointTests.cs | 84 ++++++++++ .../GetRunningLibraryScansEndpointTests.cs | 82 ++++++++++ .../Index/LibrariesIndexViewEndpointTests.cs | 45 +++++ .../ReorderMetadataProvidersEndpointTests.cs | 71 ++++++++ .../ScanLibrariesEndpointTests.cs | 81 +++++++++ .../ScanLibrary/ScanLibraryEndpointTests.cs | 78 +++++++++ ...SetMetadataProviderEnabledEndpointTests.cs | 71 ++++++++ .../EditBook/EditBookViewEndpointTests.cs | 48 ++++++ .../GetLibraryItemsEndpointTests.cs | 63 +++++++ .../Index/BooksIndexViewEndpointTests.cs | 70 ++++++++ .../GetPluginSettingsEndpointTests.cs | 61 +++++++ .../Index/PluginsIndexViewEndpointTests.cs | 55 +++++++ .../ThemeAssets/ThemeAssetsEndpointTests.cs | 68 ++++++++ .../AccessDeniedViewEndpointTests.cs | 44 +++++ .../ChangePasswordEndpointTests.cs | 81 +++++++++ .../ChangePasswordViewEndpointTests.cs | 46 ++++++ .../Logout/LogoutEndpointTests.cs | 44 +++++ .../RecoverPasswordEndpointTests.cs | 80 +++++++++ .../RecoverPasswordViewEndpointTests.cs | 46 ++++++ .../Register/RegisterEndpointTests.cs | 103 ++++++++++++ .../Register/RegisterViewEndpointTests.cs | 46 ++++++ .../CheckInitializationEndpointTests.cs | 41 +++++ .../SetupApplicationEndpointTests.cs | 92 +++++++++++ .../Roles/AddRole/AddRoleEndpointTests.cs | 139 ++++++++++++++++ .../DeleteRole/DeleteRoleEndpointTests.cs | 136 ++++++++++++++++ .../GetRolePermissionsEndpointTests.cs | 80 +++++++++ .../UpdateRole/UpdateRoleEndpointTests.cs | 139 ++++++++++++++++ .../ManagePermissionsViewEndpointTests.cs | 91 +++++++++++ .../ManageRolesViewEndpointTests.cs | 86 ++++++++++ .../DeleteTheme/DeleteThemeEndpointTests.cs | 80 +++++++++ .../DownloadThemeEndpointTests.cs | 45 +++++ .../GetThemes/GetThemesEndpointTests.cs | 46 ++++++ .../InstallTheme/InstallThemeEndpointTests.cs | 84 ++++++++++ .../RestoreTheme/RestoreThemeEndpointTests.cs | 80 +++++++++ .../SetCurrentThemeEndpointTests.cs | 80 +++++++++ .../Themes/ThemesIndexViewEndpointTests.cs | 43 +++++ .../GetUserPermissionsEndpointTests.cs | 81 +++++++++ .../GetUserRole/GetUserRoleEndpointTests.cs | 80 +++++++++ ...dateUserRoleAndPermissionsEndpointTests.cs | 137 ++++++++++++++++ .../GetDirectoriesEndpointTests.cs | 74 +++++++++ .../GetDrives/GetDrivesEndpointTests.cs | 43 +++++ .../GetType/GetTypeEndpointTests.cs | 43 +++++ .../Files/GetFiles/GetFilesEndpointTests.cs | 74 +++++++++ .../GetTreeFiles/GetTreeFilesEndpointTests.cs | 43 +++++ .../CheckPathExistsEndpointTests.cs | 75 +++++++++ .../GetPathParentEndpointTests.cs | 74 +++++++++ .../GetPathRoot/GetPathRootEndpointTests.cs | 75 +++++++++ .../GetPathSeparatorEndpointTests.cs | 43 +++++ .../Path/SplitPath/SplitPathEndpointTests.cs | 74 +++++++++ .../ValidatePath/ValidatePathEndpointTests.cs | 75 +++++++++ .../Endpoints/Home/HomeErrorEndpointTests.cs | 41 +++++ .../Endpoints/Home/HomeIndexEndpointTests.cs | 61 +++++++ .../Home/HomeNotFoundViewEndpointTests.cs | 41 +++++ .../Home/HomePrivacyEndpointTests.cs | 41 +++++ .../AddLibrary/AddLibraryViewEndpointTests.cs | 42 +++++ .../CancelLibrariesScanEndpointTests.cs | 80 +++++++++ .../CancelLibraryScanEndpointTests.cs | 85 ++++++++++ .../EditLibraryViewEndpointTests.cs | 44 +++++ .../GetEnabledLibrariesEndpointTests.cs | 46 ++++++ .../GetLibraries/GetLibrariesEndpointTests.cs | 46 ++++++ .../GetMetadataProvidersEndpointTests.cs | 47 ++++++ .../GetRunningLibraryScansEndpointTests.cs | 46 ++++++ .../Index/LibrariesIndexViewEndpointTests.cs | 42 +++++ .../ReorderMetadataProvidersEndpointTests.cs | 89 ++++++++++ .../ScanLibrariesEndpointTests.cs | 80 +++++++++ .../ScanLibrary/ScanLibraryEndpointTests.cs | 114 +++++++++++++ ...SetMetadataProviderEnabledEndpointTests.cs | 93 +++++++++++ .../EditBook/EditBookViewEndpointTests.cs | 42 +++++ .../GetLibraryItemsEndpointTests.cs | 76 +++++++++ .../Index/BooksIndexViewEndpointTests.cs | 43 +++++ .../GetPluginSettingsEndpointTests.cs | 78 +++++++++ .../Index/PluginsIndexViewEndpointTests.cs | 43 +++++ .../ThemeAssets/ThemeAssetsEndpointTests.cs | 97 +++++++++++ .../SetLanguage/SetLanguageEndpointTests.cs | 41 +++++ .../AccessDeniedViewEndpointTests.cs | 42 +++++ .../ChangePasswordEndpointTests.cs | 154 ++++++++++++++++++ .../ChangePasswordViewEndpointTests.cs | 41 +++++ .../Login/LoginViewEndpointTests.cs | 44 +++++ .../Logout/LogoutEndpointTests.cs | 42 +++++ .../RecoverPasswordEndpointTests.cs | 130 +++++++++++++++ .../RecoverPasswordViewEndpointTests.cs | 42 +++++ .../Register/RegisterEndpointTests.cs | 130 +++++++++++++++ .../Register/RegisterViewEndpointTests.cs | 42 +++++ 198 files changed, 11649 insertions(+) create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DTO/Filtering/BaseFilterDtoFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DTO/Filtering/LibraryFilterDtoFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DTO/Pagination/PaginatedResultDtoFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DTO/Pagination/PaginationDataDtoFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RoleEntityFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/GenreEntityFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/TagEntityFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnEntityFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeArchiveDtoFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeAssetDtoFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetPlugins/GetPluginsQueryFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/GenreDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/LanguageInfoDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ReleaseInfoDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/TagDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorNameDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorRoleDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/AddRoleRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/DeleteRoleRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetRolePermissionsRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserPermissionsRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserRoleRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/ChangePasswordResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/LoginResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/RecoverPasswordResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authorization/AuthorizationResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authorization/RoleResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathExistsResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathValidResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/MediaLibraryScanResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/InitializationResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Responses/Common/PaginatedResponseFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/PermissionDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RolePermissionsDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/ProblemDetailsDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Configuration/EncryptionSettingsDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Configuration/ServerConfigurationDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/BlobDataDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/DirectoryDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTreeNodeDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTypeDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathExistsDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSegmentDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSeparatorDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathValidDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/BookLiteDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanJobProgressDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanProgressDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/PaginatedBookLiteDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeLayoutPageDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavEntryDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavSectionDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageRenderResultDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateRoleRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateUserRoleAndPermissionsRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksViewRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/DeleteThemeRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeArchiveRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeAssetRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/RestoreThemeRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/SetCurrentThemeRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/Authorization/GetAuthorizationResponseFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/ChangePasswordResponseFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/RecoverPasswordResponseFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/RegisterResponseFixture.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/Filtering/BaseFilterDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Filtering/BaseFilterDtoFixture.cs new file mode 100644 index 00000000..24071540 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Filtering/BaseFilterDtoFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.Filtering; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.Filtering; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class BaseFilterDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The search term used to filter results. + /// The created . + public BaseFilterDto Create(string? searchTerm = null) + { + return new BaseFilterDto + { + SearchTerm = searchTerm ?? _faker.Lorem.Sentence() + }; + } + + /// + /// 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/Common/DTO/Filtering/LibraryFilterDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Filtering/LibraryFilterDtoFixture.cs new file mode 100644 index 00000000..f9a8971d --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Filtering/LibraryFilterDtoFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.Filtering; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.Filtering; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryFilterDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library used to filter data. + /// Optional. The search term used to filter results. + /// Optional. The alpha key used to filter by the first character of the item title. + /// Whether the leading "The " prefix should be ignored when computing the alpha key, or not. + /// The created . + public LibraryFilterDto Create( + Guid? libraryId = null, + string? searchTerm = null, + string? filterAlphaKey = null, + bool shouldIgnoreThePrefixForAlphaPicker = false) + { + return new LibraryFilterDto + { + LibraryId = libraryId ?? _faker.Random.Guid(), + SearchTerm = searchTerm, + FilterAlphaKey = filterAlphaKey, + ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker + }; + } + + /// + /// Creates a list of 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.Application.Fixtures/Common/DTO/Pagination/PaginatedResultDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Pagination/PaginatedResultDtoFixture.cs new file mode 100644 index 00000000..0cdc69be --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Pagination/PaginatedResultDtoFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.Pagination; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.Pagination; + +/// +/// Fixture class for the record. +/// +/// The type of the data items contained in the paginated result. +[ExcludeFromCodeCoverage] +public class PaginatedResultDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The collection of data items. + /// Optional. The current page number. + /// Optional. The number of items per page. + /// Optional. The total number of elements available. + /// Optional. The total number of pages. + /// The created . + public PaginatedResultDto Create( + IReadOnlyList? data = null, + int? currentPage = null, + int? perPage = null, + int? count = null, + int? numberOfPages = null) + { + return new PaginatedResultDto + { + Data = data ?? [], + CurrentPage = currentPage ?? _faker.Random.Int(1, 10), + PerPage = perPage ?? _faker.Random.Int(1, 100), + Count = count ?? _faker.Random.Int(0, 1000), + NumberOfPages = numberOfPages ?? _faker.Random.Int(1, 100) + }; + } + + /// + /// Creates a list of 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.Application.Fixtures/Common/DTO/Pagination/PaginationDataDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Pagination/PaginationDataDtoFixture.cs new file mode 100644 index 00000000..2bbc63cf --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Pagination/PaginationDataDtoFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.Pagination; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.Pagination; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PaginationDataDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The current page number in a paginated collection. + /// Optional. The number of items to include per page in paginated results. + /// The created . + public PaginationDataDto Create( + int? currentPage = null, + int? perPage = null) + { + return new PaginationDataDto + { + CurrentPage = currentPage ?? _faker.Random.Int(1, 100), + PerPage = perPage ?? _faker.Random.Int(1, 200) + }; + } + + /// + /// Creates a list of 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.Application.Fixtures/Common/DataAccess/Entities/Authorization/RoleEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RoleEntityFixture.cs new file mode 100644 index 00000000..3ffee2c1 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RoleEntityFixture.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class RoleEntityFixture +{ + private readonly RolePermissionEntityFixture _rolePermissionEntityFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the role. + /// Optional. The name of the role. + /// Optional. The role permission associations of the role. + /// Whether the role should include role permission associations or not. + /// Optional. The Id of the user that created the role. + /// Optional. The time and date when the role was added. + /// The created . + public RoleEntity Create( + Guid? id = null, + string? roleName = null, + IEnumerable? rolePermissions = null, + bool includeRolePermissions = false, + Guid? createdBy = null, + DateTime? createdOnUtc = null) + { + return new Faker() + .CustomInstantiator(faker => new RoleEntity + { + Id = id ?? faker.Random.Guid(), + RoleName = roleName ?? faker.Random.String2(faker.Random.Number(1, 50)), + RolePermissions = includeRolePermissions ? (rolePermissions ?? _rolePermissionEntityFixture.CreateMany()).ToList() : [], + CreatedOnUtc = createdOnUtc ?? faker.Date.Past(), + CreatedBy = createdBy ?? faker.Random.Guid(), + UpdatedOnUtc = null, + UpdatedBy = null + }) + .Generate(); + } + + /// + /// Creates a list of 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.Application.Fixtures/Common/DataAccess/Entities/Common/GenreEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/GenreEntityFixture.cs new file mode 100644 index 00000000..a0cc7ad3 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/GenreEntityFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GenreEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the genre. + /// Whether the name should be included, or forced to . + /// The created . + public GenreEntity Create( + string? name = null, + bool includeName = true) + { + return new GenreEntity(includeName ? name ?? _faker.Lorem.Word() : 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/Common/DataAccess/Entities/Common/TagEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/TagEntityFixture.cs new file mode 100644 index 00000000..1985f046 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/TagEntityFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class TagEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the tag. + /// Whether the name should be included, or forced to . + /// The created . + public TagEntity Create( + string? name = null, + bool includeName = true) + { + return new TagEntity(includeName ? name ?? _faker.Lorem.Word() : 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/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnEntityFixture.cs new file mode 100644 index 00000000..0ad25a7d --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnEntityFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class IsbnEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The ISBN value. + /// Optional. The format of the ISBN. + /// Whether the value should be included, or forced to . + /// The created . + public IsbnEntity Create( + string? value = null, + IsbnFormat? format = null, + bool includeValue = true) + { + return new IsbnEntity( + includeValue ? value ?? _faker.Random.String2(13, "0123456789") : null, + format); + } + + /// + /// 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/Common/Infrastructure/Models/DTO/Themes/ThemeArchiveDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeArchiveDtoFixture.cs new file mode 100644 index 00000000..103743bb --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeArchiveDtoFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ThemeArchiveDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The bytes of the ZIP archive. + /// Optional. The file name to expose when downloading the archive. + /// Optional. The MIME content type of the archive. + /// The created . + public ThemeArchiveDto Create( + byte[]? bytes = null, + string? fileName = null, + string? contentType = null) + { + return new ThemeArchiveDto( + bytes ?? _faker.Random.Bytes(10), + fileName ?? _faker.System.FileName(), + contentType ?? _faker.System.MimeType()); + } + + /// + /// 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/Common/Infrastructure/Models/DTO/Themes/ThemeAssetDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeAssetDtoFixture.cs new file mode 100644 index 00000000..dce663b9 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeAssetDtoFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ThemeAssetDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The bytes of the asset file. + /// Optional. The MIME content type of the asset file. + /// The created . + public ThemeAssetDto Create( + byte[]? bytes = null, + string? contentType = null) + { + return new ThemeAssetDto( + bytes ?? _faker.Random.Bytes(10), + contentType ?? _faker.System.MimeType()); + } + + /// + /// 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/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryFixture.cs new file mode 100644 index 00000000..962a415c --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Admin.Authorization.Permissions.Queries.GetPermissions; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPermissionsQueryFixture +{ + /// + /// Creates a random valid query to get permissions. + /// + /// The created query. + public GetPermissionsQuery Create() + { + return new GetPermissionsQuery(); + } + + /// + /// 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/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryFixture.cs new file mode 100644 index 00000000..5bf4cfed --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class CheckInitializationQueryFixture +{ + /// + /// Creates a . + /// + /// The created . + public CheckInitializationQuery Create() + { + return new CheckInitializationQuery(); + } + + /// + /// 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/CancelLibrariesScan/CancelLibrariesScanCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandFixture.cs new file mode 100644 index 00000000..0c35040a --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.CancelLibrariesScan; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class CancelLibrariesScanCommandFixture +{ + /// + /// Creates a . + /// + /// The created . + public CancelLibrariesScanCommand Create() + { + return new CancelLibrariesScanCommand(); + } + + /// + /// 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/ScanLibraries/ScanLibrariesCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandFixture.cs new file mode 100644 index 00000000..69e2519a --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.ScanLibraries; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ScanLibrariesCommandFixture +{ + /// + /// Creates a . + /// + /// The created . + public ScanLibrariesCommand Create() + { + return new ScanLibrariesCommand(); + } + + /// + /// 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/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryFixture.cs new file mode 100644 index 00000000..df7be1bc --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetEnabledLibraries; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetEnabledLibraries; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetEnabledLibrariesQueryFixture +{ + /// + /// Creates a . + /// + /// The created . + public GetEnabledLibrariesQuery Create() + { + return new GetEnabledLibrariesQuery(); + } + + /// + /// 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/Queries/GetLibraries/GetLibrariesQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryFixture.cs new file mode 100644 index 00000000..084f8b5d --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraries; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetLibraries; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibrariesQueryFixture +{ + /// + /// Creates a . + /// + /// The created . + public GetLibrariesQuery Create() + { + return new GetLibrariesQuery(); + } + + /// + /// 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/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryFixture.cs new file mode 100644 index 00000000..9b322530 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetRunningLibraryScans; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetRunningLibraryScans; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetRunningLibraryScansQueryFixture +{ + /// + /// Creates a . + /// + /// The created . + public GetRunningLibraryScansQuery Create() + { + return new GetRunningLibraryScansQuery(); + } + + /// + /// 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/GetPlugins/GetPluginsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetPlugins/GetPluginsQueryFixture.cs new file mode 100644 index 00000000..3b82f852 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetPlugins/GetPluginsQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetPlugins; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetPlugins; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPluginsQueryFixture +{ + /// + /// Creates a . + /// + /// The created . + public GetPluginsQuery Create() + { + return new GetPluginsQuery(); + } + + /// + /// 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/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryFixture.cs new file mode 100644 index 00000000..6fc4a7a9 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.UsersManagement.Settings.Queries.GetUserSettings; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.UsersManagement.Settings.Queries.GetUserSettings; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserSettingsQueryFixture +{ + /// + /// Creates a random valid query to get the settings of the current user. + /// + /// The created query. + public GetUserSettingsQuery Create() + { + return new GetUserSettingsQuery(); + } + + /// + /// 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/DTO/Common/GenreDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/GenreDtoFixture.cs new file mode 100644 index 00000000..24179b03 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/GenreDtoFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.Common; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GenreDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the genre. + /// Whether the name should be included, or forced to . + /// The created . + public GenreDto Create( + string? name = null, + bool includeName = true) + { + return new GenreDto(includeName ? name ?? _faker.Lorem.Word() : 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/DTO/Common/LanguageInfoDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/LanguageInfoDtoFixture.cs new file mode 100644 index 00000000..e67f358d --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/LanguageInfoDtoFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.Common; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LanguageInfoDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The ISO code of the language. + /// Optional. The name of the language in English. + /// Optional. The native name of the language. + /// The created . + public LanguageInfoDto Create( + string? languageCode = null, + string? languageName = null, + string? nativeName = null) + { + return new LanguageInfoDto( + languageCode ?? _faker.Random.String2(2), + languageName ?? _faker.Lorem.Word(), + nativeName ?? _faker.Lorem.Word()); + } + + /// + /// 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/DTO/Common/ReleaseInfoDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ReleaseInfoDtoFixture.cs new file mode 100644 index 00000000..6de91897 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ReleaseInfoDtoFixture.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.Common; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ReleaseInfoDtoFixture +{ + /// + /// Creates an , preserving the values that are not provided as . + /// + /// Optional. The original release date of the content. + /// Optional. The original release year of the content. + /// Optional. The re-release date of the content. + /// Optional. The re-release year of the content. + /// Optional. The country where the content was released. + /// Optional. The version or edition of the content's release. + /// The created . + public ReleaseInfoDto Create( + DateOnly? originalReleaseDate = null, + int? originalReleaseYear = null, + DateOnly? reReleaseDate = null, + int? reReleaseYear = null, + string? releaseCountry = null, + string? releaseVersion = null) + { + return new ReleaseInfoDto( + originalReleaseDate, + originalReleaseYear, + reReleaseDate, + reReleaseYear, + releaseCountry, + releaseVersion); + } + + /// + /// 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/DTO/Common/TagDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/TagDtoFixture.cs new file mode 100644 index 00000000..4dd94b80 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/TagDtoFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.Common; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class TagDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the tag. + /// Whether the name should be included, or forced to . + /// The created . + public TagDto Create( + string? name = null, + bool includeName = true) + { + return new TagDto(includeName ? name ?? _faker.Lorem.Word() : 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/DTO/MediaContributors/MediaContributorDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs new file mode 100644 index 00000000..6082894e --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.MediaContributors; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The display name of the media contributor. + /// Optional. The name of the role assigned to the media contributor. + /// Optional. The category of the role. + /// The created . + public MediaContributorDto Create( + string? displayName = null, + string? roleName = null, + string? roleCategory = null) + { + return new MediaContributorDto( + Name: new MediaContributorNameDto(DisplayName: displayName ?? _faker.Name.FullName(), LegalName: null), + Role: new MediaContributorRoleDto(Name: roleName ?? _faker.Commerce.Department(), Category: roleCategory ?? "Writing")); + } + + /// + /// 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/DTO/MediaContributors/MediaContributorNameDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorNameDtoFixture.cs new file mode 100644 index 00000000..a332a8a7 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorNameDtoFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.MediaContributors; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorNameDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The display name of the media contributor. + /// Optional. The legal name of the media contributor. + /// The created . + public MediaContributorNameDto Create( + string? displayName = null, + string? legalName = null) + { + return new MediaContributorNameDto( + displayName ?? _faker.Name.FullName(), + legalName ?? _faker.Name.FullName()); + } + + /// + /// 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/DTO/MediaContributors/MediaContributorRoleDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorRoleDtoFixture.cs new file mode 100644 index 00000000..93e8d187 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorRoleDtoFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.MediaContributors; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorRoleDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the role assigned to the media contributor. + /// Optional. The category of the role. + /// The created . + public MediaContributorRoleDto Create( + string? name = null, + string? category = null) + { + return new MediaContributorRoleDto( + name ?? _faker.Commerce.Department(), + category ?? _faker.Commerce.Department()); + } + + /// + /// 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/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs new file mode 100644 index 00000000..6775e3d6 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class WrittenContentMetadataDtoFixture +{ + /// + /// Creates a with the requested values, leaving unspecified properties as . + /// + /// Optional. The title of the written content. + /// Optional. The original title of the written content. + /// Optional. A brief description or summary of the written content. + /// Optional. The release information of the written content. + /// Optional. The genres associated with the written content. + /// Optional. The tags that describe or categorize the written content. + /// Optional. The language in which the written content is written. + /// Optional. The original language of the written content. + /// Optional. The name of the publisher of the written content. + /// Optional. The number of pages in the written content. + /// The created . + public WrittenContentMetadataDto Create( + string? title = null, + string? originalTitle = null, + string? description = null, + ReleaseInfoDto? releaseInfo = null, + List? genres = null, + List? tags = null, + LanguageInfoDto? language = null, + LanguageInfoDto? originalLanguage = null, + string? publisher = null, + int? pageCount = null) + { + return new WrittenContentMetadataDto( + title, + originalTitle, + description, + releaseInfo, + genres, + tags, + language, + originalLanguage, + publisher, + pageCount); + } + + /// + /// 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/Authorization/AddRoleRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/AddRoleRequestFixture.cs new file mode 100644 index 00000000..a28b3057 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/AddRoleRequestFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Authorization; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AddRoleRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the role. + /// Optional. The Ids of the permissions granted to the role. + /// The created . + public AddRoleRequest Create( + string? roleName = null, + List? permissions = null) + { + return new AddRoleRequest(roleName ?? _faker.Commerce.Department(), permissions ?? []); + } + + /// + /// 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/Authorization/DeleteRoleRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/DeleteRoleRequestFixture.cs new file mode 100644 index 00000000..820d3494 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/DeleteRoleRequestFixture.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Authorization; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class DeleteRoleRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the role to delete. + /// The created . + public DeleteRoleRequest Create( + Guid? roleId = null) + { + return new DeleteRoleRequest(roleId ?? 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/Authorization/GetRolePermissionsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetRolePermissionsRequestFixture.cs new file mode 100644 index 00000000..a2a022cf --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetRolePermissionsRequestFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Authorization; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetRolePermissionsRequestFixture +{ + /// + /// Creates a random valid . + /// + /// The Id of the role whose permissions are retrieved. + /// The created . + public GetRolePermissionsRequest Create( + Guid? roleId = null) + { + return new GetRolePermissionsRequest(roleId ?? 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/Authorization/GetUserPermissionsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserPermissionsRequestFixture.cs new file mode 100644 index 00000000..7d597f77 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserPermissionsRequestFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Authorization; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetUserPermissionsRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the user whose permissions are retrieved. + /// The created . + public GetUserPermissionsRequest Create( + Guid? userId = null) + { + return new GetUserPermissionsRequest(userId ?? 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/Authorization/GetUserRoleRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserRoleRequestFixture.cs new file mode 100644 index 00000000..aa32e308 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserRoleRequestFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Authorization; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetUserRoleRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the user whose role is retrieved. + /// The created . + public GetUserRoleRequest Create( + Guid? userId = null) + { + return new GetUserRoleRequest(userId ?? 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/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestFixture.cs new file mode 100644 index 00000000..92ed937f --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetBookRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The unique identifier of the book to retrieve. + /// The created . + public GetBookRequest Create( + string? id = null) + { + return new GetBookRequest(id ?? Guid.NewGuid().ToString()); + } + + /// + /// Creates a list of 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.Contracts.Fixtures/Core/Responses/Authentication/ChangePasswordResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/ChangePasswordResponseFixture.cs new file mode 100644 index 00000000..0f15870a --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/ChangePasswordResponseFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Authentication; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Authentication; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. Whether the password was changed. + /// The created . + public ChangePasswordResponse Create( + bool? isPasswordChanged = null) + { + return new ChangePasswordResponse(isPasswordChanged ?? _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/Responses/Authentication/LoginResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/LoginResponseFixture.cs new file mode 100644 index 00000000..43b60891 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/LoginResponseFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Authentication; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Authentication; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LoginResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the authenticated user. + /// Optional. The username of the authenticated user. + /// Optional. The authentication token of the user. + /// Optional. Whether the user uses two-factor authentication. + /// The created . + public LoginResponse Create( + Guid? id = null, + string? username = null, + string? token = null, + bool? usesTotp = null) + { + return new LoginResponse( + id ?? Guid.NewGuid(), + username ?? _faker.Internet.UserName(), + token ?? _faker.Random.Hexadecimal(32), + usesTotp ?? _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/Responses/Authentication/RecoverPasswordResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/RecoverPasswordResponseFixture.cs new file mode 100644 index 00000000..a0a338de --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/RecoverPasswordResponseFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Authentication; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Authentication; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. Whether the password was reset. + /// The created . + public RecoverPasswordResponse Create( + bool? isPasswordReset = null) + { + return new RecoverPasswordResponse(isPasswordReset ?? _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/Responses/Authorization/AuthorizationResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authorization/AuthorizationResponseFixture.cs new file mode 100644 index 00000000..737bfaeb --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authorization/AuthorizationResponseFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Authorization; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AuthorizationResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the user. + /// Optional. The role of the user. + /// Optional. The permissions of the user. + /// The created . + public AuthorizationResponse Create( + Guid? userId = null, + string? role = null, + IReadOnlySet? permissions = null) + { + return new AuthorizationResponse( + userId ?? Guid.NewGuid(), + role, + permissions ?? new HashSet()); + } + + /// + /// 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/Responses/Authorization/RoleResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authorization/RoleResponseFixture.cs new file mode 100644 index 00000000..1fdcad3f --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authorization/RoleResponseFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Authorization; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RoleResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the role. + /// Optional. The name of the role. + /// The created . + public RoleResponse Create( + Guid? id = null, + string? roleName = null) + { + return new RoleResponse(id ?? Guid.NewGuid(), roleName ?? _faker.Commerce.Department()); + } + + /// + /// 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/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponseFixture.cs new file mode 100644 index 00000000..9a33d454 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponseFixture.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.FileSystem; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class FileSystemTypeResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The type of the file system platform. + /// The created . + public FileSystemTypeResponse Create( + PlatformType? platformType = null) + { + return new FileSystemTypeResponse(platformType ?? _faker.PickRandom()); + } + + /// + /// 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/Responses/FileSystemManagement/Path/PathExistsResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathExistsResponseFixture.cs new file mode 100644 index 00000000..3d0d53bf --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathExistsResponseFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Path; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PathExistsResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. Whether the path exists. + /// The created . + public PathExistsResponse Create( + bool? exists = null) + { + return new PathExistsResponse(exists ?? _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/Responses/FileSystemManagement/Path/PathValidResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathValidResponseFixture.cs new file mode 100644 index 00000000..d3f9fb85 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathValidResponseFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Path; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PathValidResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. Whether the path is valid. + /// The created . + public PathValidResponse Create( + bool? isValid = null) + { + return new PathValidResponse(isValid ?? _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/Responses/MediaLibrary/Management/MediaLibraryScanResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/MediaLibraryScanResponseFixture.cs new file mode 100644 index 00000000..3b9610ef --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/MediaLibraryScanResponseFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.MediaLibrary.Management; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanResponseFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library scan. + /// Optional. The Id of the media library the scan belongs to. + /// The created . + public MediaLibraryScanResponse Create( + Guid? scanId = null, + Guid? libraryId = null) + { + return new MediaLibraryScanResponse(scanId ?? Guid.NewGuid(), libraryId ?? 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/Responses/UsersManagement/InitializationResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/InitializationResponseFixture.cs new file mode 100644 index 00000000..1d48b9ce --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/InitializationResponseFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.UsersManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.UsersManagement; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class InitializationResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. Whether the application is initialized. + /// The created . + public InitializationResponse Create( + bool? isInitialized = null) + { + return new InitializationResponse(isInitialized ?? _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/Responses/Common/PaginatedResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Responses/Common/PaginatedResponseFixture.cs new file mode 100644 index 00000000..007d5790 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Responses/Common/PaginatedResponseFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Responses.Common; + +/// +/// Fixture class for the record. +/// +/// The type of the data items contained in the paginated response. +[ExcludeFromCodeCoverage] +public class PaginatedResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The collection of data items. + /// Optional. The current page number. + /// Optional. The number of items per page. + /// Optional. The total number of elements available. + /// Optional. The total number of pages. + /// The created . + public PaginatedResponse Create( + IReadOnlyList? data = null, + int? currentPage = null, + int? perPage = null, + int? count = null, + int? numberOfPages = null) + { + return new PaginatedResponse + { + Data = data ?? [], + CurrentPage = currentPage ?? _faker.Random.Int(1, 10), + PerPage = perPage ?? _faker.Random.Int(1, 100), + Count = count ?? _faker.Random.Int(0, 1000), + NumberOfPages = numberOfPages ?? _faker.Random.Int(1, 100) + }; + } + + /// + /// Creates a list of 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/DTO/Authorization/PermissionDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/PermissionDtoFixture.cs new file mode 100644 index 00000000..0c21230c --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/PermissionDtoFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.Enums.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class PermissionDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional unique identifier of the permission. + /// Optional name of the permission. + /// A configured instance. + public PermissionDto Create( + Guid? id = null, + AuthorizationPermission? permission = null) + { + return new PermissionDto( + Id: id ?? Guid.NewGuid(), + PermissionName: permission ?? _faker.Random.Enum() + ); + } + + /// + /// 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/DTO/Authorization/RolePermissionsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RolePermissionsDtoFixture.cs new file mode 100644 index 00000000..9b78d6ff --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RolePermissionsDtoFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RolePermissionsDtoFixture +{ + private readonly RoleDtoFixture _roleDtoFixture = new(); + private readonly PermissionDtoFixture _permissionDtoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The authorization role. + /// Optional. The permissions of the authorization role. + /// The created . + public RolePermissionsDto Create( + RoleDto? role = null, + PermissionDto[]? permissions = null) + { + return new RolePermissionsDto( + role ?? _roleDtoFixture.Create(), + permissions ?? [.. _permissionDtoFixture.CreateMany()]); + } + + /// + /// Creates a list of 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/DTO/Common/ProblemDetailsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/ProblemDetailsDtoFixture.cs new file mode 100644 index 00000000..fbb0e8e7 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/ProblemDetailsDtoFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Common; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ProblemDetailsDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The URI reference that identifies the problem type. + /// Optional. A short, human-readable summary of the problem type. + /// Optional. The HTTP status code generated by the server. + /// Optional. A detailed explanation specific to this occurrence of the problem. + /// Optional. A URI reference that identifies the specific occurrence of the problem. + /// The created . + public ProblemDetailsDto Create( + string? type = null, + string? title = null, + int? status = null, + string? detail = null, + string? instance = null) + { + return new ProblemDetailsDto + { + Type = type ?? "https://tools.ietf.org/html/rfc4918#section-11.2", + Title = title ?? _faker.Lorem.Word(), + Status = status ?? _faker.Random.Int(400, 599), + Detail = detail ?? _faker.Lorem.Sentence(), + Instance = instance + }; + } + + /// + /// Creates a list of 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/DTO/Configuration/EncryptionSettingsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Configuration/EncryptionSettingsDtoFixture.cs new file mode 100644 index 00000000..38c39d50 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Configuration/EncryptionSettingsDtoFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Configuration; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Configuration; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class EncryptionSettingsDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The secret key used to encrypt data. + /// The created . + public EncryptionSettingsDto Create( + string? secretKey = null) + { + return new EncryptionSettingsDto + { + SecretKey = secretKey ?? _faker.Random.String2(44, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=") + }; + } + + /// + /// Creates a list of 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/DTO/Configuration/ServerConfigurationDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Configuration/ServerConfigurationDtoFixture.cs new file mode 100644 index 00000000..f07bfccd --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Configuration/ServerConfigurationDtoFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Configuration; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Configuration; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ServerConfigurationDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The remote API server path version. + /// Optional. The remote API server path. + /// Optional. The remote API server port. + /// The created . + public ServerConfigurationDto Create( + char? apiVersion = null, + string? baseAddress = null, + ushort? port = null) + { + return new ServerConfigurationDto + { + ApiVersion = apiVersion ?? _faker.Random.Char('1', '9'), + BaseAddress = baseAddress ?? "http://localhost", + Port = port ?? _faker.Random.UShort() + }; + } + + /// + /// Creates a list of 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/DTO/FileSystemManagement/BlobDataDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/BlobDataDtoFixture.cs new file mode 100644 index 00000000..2f1a331c --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/BlobDataDtoFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class BlobDataDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The binary data as a byte array. + /// Optional. The content type (MIME type) of the blob data. + /// The created . + public BlobDataDto Create( + byte[]? data = null, + string? contentType = null) + { + return new BlobDataDto + { + Data = data ?? _faker.Random.Bytes(32), + ContentType = contentType ?? _faker.System.MimeType() + }; + } + + /// + /// Creates a list of 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/DTO/FileSystemManagement/DirectoryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/DirectoryDtoFixture.cs new file mode 100644 index 00000000..ce8f3e32 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/DirectoryDtoFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class DirectoryDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The full path to the directory. + /// Optional. The name of the directory. + /// Optional. The children items of the directory. + /// Whether the directory should include children items, or an empty collection. + /// The created . + public DirectoryDto Create( + string? path = null, + string? name = null, + List? items = null, + bool includeItems = false) + { + string generatedPath = _faker.System.DirectoryPath(); + return new DirectoryDto + { + Path = path ?? generatedPath, + Name = name ?? Path.GetFileName(generatedPath), + DateCreated = _faker.Date.Past(), + DateModified = _faker.Date.Recent(), + Items = includeItems ? (items ?? []) : [] + }; + } + + /// + /// Creates a list of 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/DTO/FileSystemManagement/FileDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileDtoFixture.cs new file mode 100644 index 00000000..fc636ac0 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileDtoFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class FileDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The full path to the file. + /// Optional. The name of the file. + /// Optional. The size of the file, in bytes. + /// A configured instance. + public FileDto Create( + string? path = null, + string? name = null, + long? size = null) + { + string generatedPath = _faker.System.FilePath(); + return new FileDto + { + Path = path ?? generatedPath, + Name = name ?? Path.GetFileName(generatedPath), + DateCreated = _faker.Date.Past(), + DateModified = _faker.Date.Recent(), + Size = size ?? _faker.Random.Long(0, 10_000_000) + }; + } + + /// + /// 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/DTO/FileSystemManagement/FileSystemTreeNodeDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTreeNodeDtoFixture.cs new file mode 100644 index 00000000..513aaae0 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTreeNodeDtoFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Enums.FileSystem; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class FileSystemTreeNodeDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The full path of the file or directory. + /// Optional. The name of the file or directory. + /// Optional. The type of the item, indicating whether it is a file, directory, or drive. + /// A configured instance. + public FileSystemTreeNodeDto Create( + string? path = null, + string? name = null, + FileSystemItemType? itemType = null) + { + string generatedPath = _faker.System.FilePath(); + return new FileSystemTreeNodeDto + { + Path = path ?? generatedPath, + Name = name ?? Path.GetFileName(generatedPath), + ItemType = itemType ?? _faker.PickRandom(), + IsExpanded = _faker.Random.Bool(), + ChildrenLoaded = _faker.Random.Bool(), + Children = [] + }; + } + + /// + /// 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/DTO/FileSystemManagement/FileSystemTypeDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTypeDtoFixture.cs new file mode 100644 index 00000000..e4c61cb2 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTypeDtoFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Enums.FileSystem; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class FileSystemTypeDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional file system platform type. + /// A configured instance. + public FileSystemTypeDto Create( + PlatformType? platformType = null) + { + return new FileSystemTypeDto + { + PlatformType = platformType ?? _faker.PickRandom() + }; + } + + /// + /// 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/DTO/FileSystemManagement/PathExistsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathExistsDtoFixture.cs new file mode 100644 index 00000000..8b65f0bb --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathExistsDtoFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class PathExistsDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional value indicating whether a file system path exists or not. + /// A configured instance. + public PathExistsDto Create( + bool? exists = null) + { + return new PathExistsDto( + Exists: exists ?? _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/DTO/FileSystemManagement/PathSegmentDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSegmentDtoFixture.cs new file mode 100644 index 00000000..99d78637 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSegmentDtoFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class PathSegmentDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The returned path. + /// A configured instance. + public PathSegmentDto Create( + string? path = null) + { + return new PathSegmentDto + { + Path = path ?? _faker.System.FilePath() + }; + } + + /// + /// 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/DTO/FileSystemManagement/PathSeparatorDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSeparatorDtoFixture.cs new file mode 100644 index 00000000..c96d8615 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSeparatorDtoFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class PathSeparatorDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional file system path separator. + /// A configured instance. + public PathSeparatorDto Create( + string? separator = null) + { + return new PathSeparatorDto( + Separator: separator ?? (_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/DTO/FileSystemManagement/PathValidDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathValidDtoFixture.cs new file mode 100644 index 00000000..3bf00678 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathValidDtoFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class PathValidDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional value indicating whether a file system path is valid or not. + /// A configured instance. + public PathValidDto Create( + bool? isValid = null) + { + return new PathValidDto( + IsValid: isValid ?? _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/DTO/Libraries/BookLiteDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/BookLiteDtoFixture.cs new file mode 100644 index 00000000..c9332206 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/BookLiteDtoFixture.cs @@ -0,0 +1,56 @@ +#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 BookLiteDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the book. + /// Optional. The title of the book. + /// Optional. The release year of the book. + /// Optional. The path of the image representing the cover of the book. + /// Whether the release year should be included, or forced to . + /// Whether the cover path should be included, or forced to . + /// The created . + public BookLiteDto Create( + Guid? id = null, + string? title = null, + int? releaseYear = null, + string? coverPath = null, + bool includeReleaseYear = false, + bool includeCoverPath = false) + { + return new BookLiteDto + { + Id = id ?? _faker.Random.Guid(), + Title = title ?? _faker.Lorem.Sentence(3), + ReleaseYear = includeReleaseYear ? (releaseYear ?? _faker.Random.Int(1900, 2024)) : null, + CoverPath = includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null + }; + } + + /// + /// Creates a list of 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/DTO/Libraries/LibraryScanJobProgressDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanJobProgressDtoFixture.cs new file mode 100644 index 00000000..8419793d --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanJobProgressDtoFixture.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanJobProgressDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional number of completed items of the media library scan job. + /// Optional total number of items of the media library scan job. + /// Optional current operation being performed by the media library scan job. + /// Optional completion ratio of the media library scan job, as a percentage. + /// A configured instance. + public LibraryScanJobProgressDto Create( + int? completedItems = null, + int? totalItems = null, + string? currentOperation = null, + decimal? progressPercentage = null) + { + int completed = completedItems ?? _faker.Random.Int(0, 100); + int total = totalItems ?? _faker.Random.Int(completed, 100); + return new LibraryScanJobProgressDto + { + CompletedItems = completed, + TotalItems = total, + CurrentOperation = currentOperation ?? _faker.Hacker.Verb(), + ProgressPercentage = progressPercentage ?? (total > 0 ? (decimal)completed / total * 100 : 0) + }; + } + + /// + /// 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/DTO/Libraries/LibraryScanProgressDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanProgressDtoFixture.cs new file mode 100644 index 00000000..08af8992 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanProgressDtoFixture.cs @@ -0,0 +1,66 @@ +#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 generating test data. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanProgressDtoFixture +{ + private readonly Faker _faker = new(); + + private readonly LibraryScanJobProgressDtoFixture _libraryScanJobProgressDtoFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional unique identifier of the media library scan. + /// Optional unique identifier of the user initiating the media library scan. + /// Optional unique identifier of the media library that is scanned. + /// Optional number of completed jobs of the media library scan job. + /// Optional total number of jobs of the media library scan job. + /// Optional status of the media library scan. + /// Whether the current job progress should be included, or forced to . + /// A configured instance. + public LibraryScanProgressDto Create( + Guid? scanId = null, + Guid? userId = null, + Guid? libraryId = null, + int? completedJobs = null, + int? totalJobs = null, + string? status = null, + bool includeCurrentJobProgress = false) + { + int completed = completedJobs ?? _faker.Random.Int(0, 10); + int total = totalJobs ?? _faker.Random.Int(completed, 10); + return new LibraryScanProgressDto + { + ScanId = scanId ?? Guid.NewGuid(), + UserId = userId ?? Guid.NewGuid(), + LibraryId = libraryId ?? Guid.NewGuid(), + CompletedJobs = completed, + TotalJobs = total, + CurrentJobProgress = includeCurrentJobProgress ? _libraryScanJobProgressDtoFixture.Create() : null, + Status = status ?? _faker.PickRandom("Running", "Completed", "Failed"), + OverallProgressPercentage = total > 0 ? (decimal)completed / total * 100 : 0 + }; + } + + /// + /// 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/DTO/Libraries/PaginatedBookLiteDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/PaginatedBookLiteDtoFixture.cs new file mode 100644 index 00000000..8bf4938f --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/PaginatedBookLiteDtoFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class PaginatedBookLiteDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional collection of lightweight book elements. + /// Optional current page number in a paginated collection. + /// Optional number of items to include per page in paginated results. + /// Optional total number of elements available in the paginated result set. + /// Optional total number of pages based on the elements available and per page. + /// A configured instance. + public PaginatedBookLiteDto Create( + IReadOnlyList? data = null, + int? currentPage = null, + int? perPage = null, + int? count = null, + int? numberOfPages = null) + { + return new PaginatedBookLiteDto + { + Data = data ?? [], + CurrentPage = currentPage ?? _faker.Random.Int(1, 10), + PerPage = perPage ?? _faker.Random.Int(1, 100), + Count = count ?? _faker.Random.Int(0, 1000), + NumberOfPages = numberOfPages ?? _faker.Random.Int(1, 100) + }; + } + + /// + /// 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/DTO/Themes/ThemeLayoutPageDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeLayoutPageDtoFixture.cs new file mode 100644 index 00000000..5632286e --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeLayoutPageDtoFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ThemeLayoutPageDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The title of the page, displayed by the themed shell. + /// Optional. The rendered HTML content of the page section. + /// Optional. The rendered script element of the page section, when the template defines one. + /// The created . + public ThemeLayoutPageDto Create( + string? title = null, + string? content = null, + string? script = null) + { + return new ThemeLayoutPageDto( + title ?? _faker.Lorem.Word(), + content ?? _faker.Lorem.Paragraph(), + script ?? _faker.Lorem.Word()); + } + + /// + /// Creates a list of 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/DTO/Themes/ThemeNavEntryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavEntryDtoFixture.cs new file mode 100644 index 00000000..76cc62a7 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavEntryDtoFixture.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ThemeNavEntryDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional label of the entry. + /// Optional URL of the link, or for a submenu. + /// Whether to set , or when . + /// Optional CSS classes of the link. + /// Whether to set , or when . + /// Optional child links of a submenu. + /// The created . + public ThemeNavEntryDto Create( + string? label = null, + string? url = null, + bool includeUrl = false, + string? cssClass = null, + bool includeCssClass = false, + IReadOnlyList? children = null) + { + return new ThemeNavEntryDto( + Label: label ?? _faker.Lorem.Word(), + Url: includeUrl ? (url ?? _faker.Internet.Url()) : null, + CssClass: includeCssClass ? (cssClass ?? _faker.Lorem.Word()) : null, + Children: children ?? []); + } + + /// + /// 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/Themes/ThemeNavSectionDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavSectionDtoFixture.cs new file mode 100644 index 00000000..348b85b0 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavSectionDtoFixture.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ThemeNavSectionDtoFixture +{ + private readonly Faker _faker = new(); + private readonly ThemeNavEntryDtoFixture _themeNavEntryDtoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional label of the section. + /// Optional entries of the section. + /// The created . + public ThemeNavSectionDto Create( + string? label = null, + IReadOnlyList? items = null) + { + return new ThemeNavSectionDto( + Label: label ?? _faker.Lorem.Word(), + Items: items ?? [_themeNavEntryDtoFixture.Create()]); + } + + /// + /// 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/Themes/ThemePageRenderResultDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageRenderResultDtoFixture.cs new file mode 100644 index 00000000..647af988 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageRenderResultDtoFixture.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ThemePageRenderResultDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional rendered HTML content of the page section. + /// Optional rendered script element of the page section. + /// A configured instance. + public ThemePageRenderResultDto Create( + string? content = null, + string? script = null) + { + return new ThemePageRenderResultDto( + Content: content ?? _faker.Lorem.Paragraph(), + Script: script ?? _faker.Lorem.Paragraph() + ); + } + + /// + /// 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/DTO/UsersManagement/UserDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserDtoFixture.cs new file mode 100644 index 00000000..e6fb93e8 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserDtoFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class UserDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the user. + /// Optional username of the user. + /// A configured instance. + public UserDto Create( + Guid? id = null, + string? username = null) + { + return new UserDto( + Id: id ?? Guid.NewGuid(), + Username: username ?? _faker.Internet.UserName() + ); + } + + /// + /// 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/Authorization/UpdateRoleRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateRoleRequestFixture.cs new file mode 100644 index 00000000..8c6d4dda --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateRoleRequestFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class UpdateRoleRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the role. + /// Optional name of the role. + /// Optional collection of permission identifiers. + /// A configured instance. + public UpdateRoleRequest Create( + Guid? roleId = null, + string? roleName = null, + List? permissions = null) + { + return new UpdateRoleRequest( + RoleId: roleId ?? Guid.NewGuid(), + RoleName: roleName ?? _faker.Commerce.Department(), + Permissions: permissions ?? [Guid.NewGuid(), Guid.NewGuid()] + ); + } + + /// + /// 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/Authorization/UpdateUserRoleAndPermissionsRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateUserRoleAndPermissionsRequestFixture.cs new file mode 100644 index 00000000..b3f910af --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateUserRoleAndPermissionsRequestFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserRoleAndPermissionsRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the user. + /// Optional identifier of the role assigned to the user. + /// Optional collection of permission identifiers assigned to the user. + /// A configured instance. + public UpdateUserRoleAndPermissionsRequest Create( + Guid? userId = null, + Guid? roleId = null, + List? permissions = null) + { + return new UpdateUserRoleAndPermissionsRequest( + UserId: userId ?? Guid.NewGuid(), + RoleId: roleId ?? Guid.NewGuid(), + Permissions: permissions ?? [Guid.NewGuid(), Guid.NewGuid()] + ); + } + + /// + /// 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/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksViewRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksViewRequestFixture.cs new file mode 100644 index 00000000..85ef74c6 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksViewRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class GetBooksViewRequestFixture +{ + /// + /// Creates a new instance. + /// + /// Optional unique identifier of the media library whose books are browsed. + /// A configured instance. + public GetBooksViewRequest Create( + Guid? libraryId = null) + { + return new GetBooksViewRequest( + LibraryId: libraryId + ); + } + + /// + /// Creates multiple instances. + /// + /// 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/Themes/DeleteThemeRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/DeleteThemeRequestFixture.cs new file mode 100644 index 00000000..fdd4991b --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/DeleteThemeRequestFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeRequestFixture +{ + /// + /// Creates a new instance. + /// + /// Optional manifest id of the theme to delete. + /// A configured instance. + public DeleteThemeRequest Create( + string? themeId = null) + { + return new DeleteThemeRequest( + ThemeId: themeId + ); + } + + /// + /// Creates multiple instances. + /// + /// 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/Themes/GetThemeArchiveRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeArchiveRequestFixture.cs new file mode 100644 index 00000000..2790427b --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeArchiveRequestFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class GetThemeArchiveRequestFixture +{ + /// + /// Creates a new instance. + /// + /// Optional manifest id of the theme to download. + /// A configured instance. + public GetThemeArchiveRequest Create( + string? themeId = null) + { + return new GetThemeArchiveRequest( + ThemeId: themeId + ); + } + + /// + /// Creates multiple instances. + /// + /// 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/Themes/GetThemeAssetRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeAssetRequestFixture.cs new file mode 100644 index 00000000..a0e2c25c --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeAssetRequestFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class GetThemeAssetRequestFixture +{ + /// + /// Creates a new instance. + /// + /// Optional manifest id of the theme. + /// Optional asset path relative to the theme pack root. + /// A configured instance. + public GetThemeAssetRequest Create( + string? themeId = null, + string? path = null) + { + return new GetThemeAssetRequest( + ThemeId: themeId, + Path: path + ); + } + + /// + /// Creates multiple instances. + /// + /// 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/Themes/RestoreThemeRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/RestoreThemeRequestFixture.cs new file mode 100644 index 00000000..d90e2661 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/RestoreThemeRequestFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeRequestFixture +{ + /// + /// Creates a new instance. + /// + /// Optional manifest id of the bundled theme to restore. + /// A configured instance. + public RestoreThemeRequest Create( + string? themeId = null) + { + return new RestoreThemeRequest( + ThemeId: themeId + ); + } + + /// + /// Creates multiple instances. + /// + /// 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/Themes/SetCurrentThemeRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/SetCurrentThemeRequestFixture.cs new file mode 100644 index 00000000..9da2f514 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/SetCurrentThemeRequestFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeRequestFixture +{ + /// + /// Creates a new instance. + /// + /// Optional manifest id of the theme to activate. + /// A configured instance. + public SetCurrentThemeRequest Create( + string? themeId = null) + { + return new SetCurrentThemeRequest( + ThemeId: themeId + ); + } + + /// + /// Creates multiple instances. + /// + /// 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/Responses/Authorization/GetAuthorizationResponseFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/Authorization/GetAuthorizationResponseFixture.cs new file mode 100644 index 00000000..e6f47bde --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/Authorization/GetAuthorizationResponseFixture.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Lumina.Presentation.Web.Common.Responses.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class GetAuthorizationResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional unique identifier of the user. + /// Optional role associated to the user. + /// Optional collection of permissions associated to the user. + /// A configured instance. + public GetAuthorizationResponse Create( + Guid? userId = null, + string? role = null, + AuthorizationPermission[]? permissions = null) + { + return new GetAuthorizationResponse( + UserId: userId ?? Guid.NewGuid(), + Role: role ?? _faker.Name.JobTitle(), + Permissions: permissions ?? [AuthorizationPermission.CanViewUsers] + ); + } + + /// + /// 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/Responses/UsersManagement/ChangePasswordResponseFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/ChangePasswordResponseFixture.cs new file mode 100644 index 00000000..2144d5b3 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/ChangePasswordResponseFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Responses.UsersManagement; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. Whether the password was changed or not. + /// The created . + public ChangePasswordResponse Create( + bool? isPasswordChanged = null) + { + return new ChangePasswordResponse(isPasswordChanged ?? _faker.Random.Bool()); + } + + /// + /// Creates a list of 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/Responses/UsersManagement/RecoverPasswordResponseFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/RecoverPasswordResponseFixture.cs new file mode 100644 index 00000000..ccd88f54 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/RecoverPasswordResponseFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Responses.UsersManagement; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. Whether the password was reset or not. + /// The created . + public RecoverPasswordResponse Create( + bool? isPasswordReset = null) + { + return new RecoverPasswordResponse(isPasswordReset ?? _faker.Random.Bool()); + } + + /// + /// Creates a list of 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/Responses/UsersManagement/RegisterResponseFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/RegisterResponseFixture.cs new file mode 100644 index 00000000..da00e31c --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/RegisterResponseFixture.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Responses.UsersManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class RegisterResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional username of the registered user. + /// Optional TOTP secret used for two-factor authentication. + /// A configured instance. + public RegisterResponse Create( + string? username = null, + string? totpSecret = null) + { + return new RegisterResponse( + Username: username ?? _faker.Internet.UserName(), + TotpSecret: totpSecret ?? _faker.Random.AlphaNumeric(16) + ); + } + + /// + /// 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.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs new file mode 100644 index 00000000..bc029b1f --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.AddRole; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; +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; +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.Admin.Authorization.Roles.AddRole; + +/// +/// Contains integration tests for the /{culture}/admin/api-create-role route served by the class. +/// +[ExcludeFromCodeCoverage] +public class AddRoleEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly AddRoleRequestFixture _addRoleRequestFixture = new(); + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly RolePermissionsDtoFixture _rolePermissionsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AddRoleEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task AddRole_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldForwardRoleAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AddRoleRequest request = _addRoleRequestFixture.Create(); + _apiFactory.ApiClientStub.RegisterPostResponse("auth/roles", _rolePermissionsDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/admin/api-create-role") + { + Content = JsonContent.Create(request) + }; + createRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + createRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + 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.PostRequests, postRequest => postRequest.Endpoint == "auth/roles"); + } + + [Fact] + public async Task AddRole_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AddRoleRequest request = _addRoleRequestFixture.Create(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/admin/api-create-role") + { + Content = JsonContent.Create(request) + }; + createRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + createRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs new file mode 100644 index 00000000..963ad8f2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs @@ -0,0 +1,89 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; +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; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; + +/// +/// Contains integration tests for the /{culture}/admin/api-delete-role/{roleId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteRoleEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeleteRoleEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DeleteRole_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldForwardDeleteAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + Guid roleId = Guid.NewGuid(); + string expectedEndpoint = $"auth/roles/{roleId}"; + _apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedEndpoint); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/admin/api-delete-role/{roleId}") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + 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.DeleteEndpointsCalled, endpoint => endpoint == expectedEndpoint); + } + + [Fact] + public async Task DeleteRole_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + Guid roleId = Guid.NewGuid(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/admin/api-delete-role/{roleId}") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + 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()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs new file mode 100644 index 00000000..50c497e1 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRolePermissions; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +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; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.GetRolePermissions; + +/// +/// Contains integration tests for the /{culture}/admin/api-get-permissions-by-role-id/{roleId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetRolePermissionsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly RolePermissionsDtoFixture _rolePermissionsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetRolePermissionsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetRolePermissions_WhenCalledByAuthenticatedAdmin_ShouldReturnRolePermissionsJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + Guid roleId = Guid.NewGuid(); + RolePermissionsDto expectedResponse = _rolePermissionsDtoFixture.Create(); + _apiFactory.ApiClientStub.RegisterGetResponse($"auth/roles/{roleId}/permissions", expectedResponse); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/admin/api-get-permissions-by-role-id/{roleId}"); + 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()); + Assert.Equal(expectedResponse.Permissions.Length, json.RootElement.GetProperty("data").GetProperty("permissions").GetArrayLength()); + } + + [Fact] + public async Task GetRolePermissions_WhenCalledByNonAdminUser_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/admin/api-get-permissions-by-role-id/" + Guid.NewGuid()); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs new file mode 100644 index 00000000..34b80bc2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.UpdateRole; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; +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; +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.Admin.Authorization.Roles.UpdateRole; + +/// +/// Contains integration tests for the /{culture}/admin/api-update-role route served by the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateRoleEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly RolePermissionsDtoFixture _rolePermissionsDtoFixture = new(); + private readonly UpdateRoleRequestFixture _updateRoleRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdateRoleEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateRole_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldForwardUpdateAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + UpdateRoleRequest request = _updateRoleRequestFixture.Create(); + _apiFactory.ApiClientStub.RegisterPutResponse("auth/roles", _rolePermissionsDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-role") + { + 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 == "auth/roles"); + } + + [Fact] + public async Task UpdateRole_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + UpdateRoleRequest request = _updateRoleRequestFixture.Create(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-role") + { + 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); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs new file mode 100644 index 00000000..def9fd02 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.Admin.ManagePermissions; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +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; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.ManagePermissions; + +/// +/// Contains integration tests for the /{culture}/admin/manage-permissions route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ManagePermissionsViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly PermissionDtoFixture _permissionDtoFixture = new(); + private readonly RoleDtoFixture _roleDtoFixture = new(); + private readonly UserDtoFixture _userDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ManagePermissionsViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ManagePermissions_WhenCalledByAuthenticatedAdmin_ShouldRenderPermissionsManagementPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + UserDto[] expectedUsers = [.. _userDtoFixture.CreateMany()]; + RoleDto[] expectedRoles = [.. _roleDtoFixture.CreateMany()]; + PermissionDto[] expectedPermissions = [.. _permissionDtoFixture.CreateMany()]; + _apiFactory.ApiClientStub.RegisterGetResponse("auth/users", expectedUsers); + _apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles); + _apiFactory.ApiClientStub.RegisterGetResponse("auth/permissions", expectedPermissions); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-permissions"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } + + [Fact] + public async Task ManagePermissions_WhenCalledByNonAdminUser_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/admin/manage-permissions"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs new file mode 100644 index 00000000..53bf006b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.ManageRoles; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +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; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.ManageRoles; + +/// +/// Contains integration tests for the /{culture}/admin/manage-roles route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ManageRolesViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly PermissionDtoFixture _permissionDtoFixture = new(); + private readonly RoleDtoFixture _roleDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ManageRolesViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ManageRoles_WhenCalledByAuthenticatedAdmin_ShouldRenderRolesManagementPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + RoleDto[] expectedRoles = [.. _roleDtoFixture.CreateMany()]; + PermissionDto[] expectedPermissions = [.. _permissionDtoFixture.CreateMany()]; + _apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles); + _apiFactory.ApiClientStub.RegisterGetResponse("auth/permissions", expectedPermissions); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-roles"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } + + [Fact] + public async Task ManageRoles_WhenCalledByNonAdminUser_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/admin/manage-roles"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs new file mode 100644 index 00000000..1078a03c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DeleteTheme; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.DeleteTheme; + +/// +/// Contains integration tests for the /{culture}/admin/themes/api-delete-theme/{themeId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeleteThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DeleteTheme_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldDeleteThemeAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + const string THEME_ID = "test-theme"; + _apiFactory.ApiClientStub.RegisterDeleteSuccess($"themes/{THEME_ID}"); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/admin/themes/api-delete-theme/{THEME_ID}") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + 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.DeleteEndpointsCalled, endpoint => endpoint == $"themes/{THEME_ID}"); + } + + [Fact] + public async Task DeleteTheme_WhenCalledWithEmptyThemeId_ShouldReturnBadRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, "/en-us/admin/themes/api-delete-theme/%20") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs new file mode 100644 index 00000000..a4f93086 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DownloadTheme; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.DownloadTheme; + +/// +/// Contains integration tests for the /{culture}/admin/themes/api-download-theme/{themeId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class DownloadThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly BlobDataDtoFixture _blobDataDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DownloadThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DownloadTheme_WhenCalledByAuthenticatedAdmin_ShouldReturnThemeArchive() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + byte[] expectedBytes = [0x50, 0x4B, 0x03, 0x04, 0x01, 0x02]; + _apiFactory.ApiClientStub.RegisterBlobResponse(_blobDataDtoFixture.Create(data: expectedBytes, contentType: "application/zip")); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage downloadRequest = new(HttpMethod.Get, "/en-us/admin/themes/api-download-theme/test-theme"); + downloadRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(downloadRequest); + byte[] content = await response.Content.ReadAsByteArrayAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("application/zip", response.Content.Headers.ContentType!.MediaType); + Assert.Equal(expectedBytes, content); + } + + [Fact] + public async Task DownloadTheme_WhenCalledWithEmptyThemeId_ShouldReturnBadRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage downloadRequest = new(HttpMethod.Get, "/en-us/admin/themes/api-download-theme/%20"); + downloadRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(downloadRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs new file mode 100644 index 00000000..38c8b797 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs @@ -0,0 +1,69 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.GetThemes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +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.Admin.Themes.GetThemes; + +/// +/// Contains integration tests for the /{culture}/admin/themes/api-get-themes route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + private readonly ThemeSettingsResponseDtoFixture _themeSettingsResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetThemesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetThemes_WhenCalledByAuthenticatedAdmin_ShouldReturnThemesFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + ThemeResponseDto[] expectedThemes = [.. _themeResponseDtoFixture.CreateMany()]; + ThemeResponseDto currentTheme = _themeResponseDtoFixture.Create(themeId: "current-theme"); + ThemeSettingsResponseDto expectedSettings = _themeSettingsResponseDtoFixture.Create(); + _apiFactory.ApiClientStub.RegisterGetResponse("themes", expectedThemes); + _apiFactory.ApiClientStub.RegisterGetResponse("themes/current", currentTheme); + _apiFactory.ApiClientStub.RegisterGetResponse("themes/settings", expectedSettings); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/themes/api-get-themes"); + 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(expectedThemes.Length, data.GetProperty("themes").GetArrayLength()); + Assert.Equal("current-theme", data.GetProperty("currentThemeId").GetString()); + Assert.Equal(expectedSettings.MaxArchiveBytes, data.GetProperty("maxArchiveBytes").GetInt64()); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "themes"); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "themes/current"); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "themes/settings"); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs new file mode 100644 index 00000000..ea838726 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs @@ -0,0 +1,96 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.InstallTheme; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +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.Admin.Themes.InstallTheme; + +/// +/// Contains integration tests for the /{culture}/admin/themes/api-install-theme route served by the class. +/// +[ExcludeFromCodeCoverage] +public class InstallThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public InstallThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task InstallTheme_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldForwardUploadAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string fileName = "theme.zip"; + _apiFactory.ApiClientStub.RegisterPostResponse("themes", _themeResponseDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage installRequest = new(HttpMethod.Post, "/en-us/admin/themes/api-install-theme") + { + Content = CreateMultipartContent(fileName) + }; + installRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + installRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(installRequest); + 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.PostRequests, postRequest => postRequest.Endpoint == "themes" && postRequest.Data as string == fileName); + } + + [Fact] + public async Task InstallTheme_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage installRequest = new(HttpMethod.Post, "/en-us/admin/themes/api-install-theme") + { + Content = CreateMultipartContent("theme.zip") + }; + installRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(installRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "themes"); + } + + /// + /// Builds a multipart form content carrying a single file part. + /// + /// The name of the uploaded file. + /// The multipart form content. + private static MultipartFormDataContent CreateMultipartContent(string fileName) + { + MultipartFormDataContent form = []; + ByteArrayContent fileContent = new([0x50, 0x4B, 0x03, 0x04]); + fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/zip"); + form.Add(fileContent, "archive", fileName); + return form; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs new file mode 100644 index 00000000..37b2a082 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.RestoreTheme; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +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; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.RestoreTheme; + +/// +/// Contains integration tests for the /{culture}/admin/themes/api-restore-theme/{themeId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RestoreThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RestoreTheme_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldRestoreThemeAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + const string THEME_ID = "test-theme"; + _apiFactory.ApiClientStub.RegisterPostResponse($"themes/{THEME_ID}/restore", _themeResponseDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/admin/themes/api-restore-theme/{THEME_ID}") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + 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.PostRequests, postRequest => postRequest.Endpoint == $"themes/{THEME_ID}/restore"); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs new file mode 100644 index 00000000..ec36ed94 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Requests.Themes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.SetCurrentTheme; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +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.Admin.Themes.SetCurrentTheme; + +/// +/// Contains integration tests for the /{culture}/admin/themes/api-set-current-theme route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SetCurrentThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SetCurrentTheme_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldSetCurrentThemeAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + const string THEME_ID = "test-theme"; + _apiFactory.ApiClientStub.RegisterPutResponse("themes/current", _themeResponseDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage setCurrentThemeRequest = new(HttpMethod.Put, "/en-us/admin/themes/api-set-current-theme") + { + Content = JsonContent.Create(new SetCurrentThemeRequest(THEME_ID)) + }; + setCurrentThemeRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + setCurrentThemeRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + setCurrentThemeRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(setCurrentThemeRequest); + 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 == "themes/current"); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs new file mode 100644 index 00000000..f9ab2759 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes; + +/// +/// Contains integration tests for the /{culture}/admin/manage-themes route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ThemesIndexViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ThemesIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ThemesIndex_WhenCalledByAuthenticatedAdmin_ShouldRenderThemesManagementPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + ThemeResponseDto[] expectedThemes = [.. _themeResponseDtoFixture.CreateMany()]; + ThemeResponseDto currentTheme = _themeResponseDtoFixture.Create(themeId: "current-theme"); + _apiFactory.ApiClientStub.RegisterGetResponse("themes", expectedThemes); + _apiFactory.ApiClientStub.RegisterGetResponse("themes/current", currentTheme); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-themes"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "themes"); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "themes/current"); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs new file mode 100644 index 00000000..781e3dd4 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserPermissions; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +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; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserPermissions; + +/// +/// Contains integration tests for the /{culture}/admin/api-get-permissions-by-user-id/{userId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserPermissionsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly PermissionDtoFixture _permissionDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetUserPermissionsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetUserPermissions_WhenCalledByAuthenticatedAdmin_ShouldReturnUserPermissionsJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + Guid userId = Guid.NewGuid(); + PermissionDto[] expectedPermissions = [.. _permissionDtoFixture.CreateMany()]; + _apiFactory.ApiClientStub.RegisterGetResponse($"auth/users/{userId}/permissions", expectedPermissions); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/admin/api-get-permissions-by-user-id/{userId}"); + 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()); + Assert.Equal(expectedPermissions.Length, json.RootElement.GetProperty("data").GetArrayLength()); + } + + [Fact] + public async Task GetUserPermissions_WhenCalledByNonAdminUser_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/admin/api-get-permissions-by-user-id/" + Guid.NewGuid()); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs new file mode 100644 index 00000000..d2dab495 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserRole; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +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; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserRole; + +/// +/// Contains integration tests for the /{culture}/admin/api-get-role-by-user-id/{userId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserRoleEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly RoleDtoFixture _roleDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetUserRoleEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetUserRole_WhenCalledByAuthenticatedAdmin_ShouldReturnUserRoleJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + Guid userId = Guid.NewGuid(); + RoleDto expectedRole = _roleDtoFixture.Create(); + _apiFactory.ApiClientStub.RegisterGetResponse($"auth/users/{userId}/role", expectedRole); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/admin/api-get-role-by-user-id/{userId}"); + 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()); + Assert.Equal(expectedRole.RoleName, json.RootElement.GetProperty("data").GetProperty("roleName").GetString()); + } + + [Fact] + public async Task GetUserRole_WhenCalledByNonAdminUser_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/admin/api-get-role-by-user-id/" + Guid.NewGuid()); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs new file mode 100644 index 00000000..90843ed4 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs @@ -0,0 +1,94 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Common.Responses.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.UpdateUserRoleAndPermissions; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; +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; +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.Admin.UsersManagement.Authorization.UpdateUserRoleAndPermissions; + +/// +/// Contains integration tests for the /{culture}/admin/api-update-user-authorization route served by the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly UpdateUserRoleAndPermissionsRequestFixture _updateUserRoleAndPermissionsRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdateUserRoleAndPermissionsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateUserRoleAndPermissions_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldForwardUpdateAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(); + string expectedEndpoint = $"auth/users/{request.UserId}/role-and-permissions"; + GetAuthorizationResponse expectedResponse = _getAuthorizationResponseFixture.Create(userId: request.UserId); + _apiFactory.ApiClientStub.RegisterPutResponse(expectedEndpoint, expectedResponse); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-user-authorization") + { + 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 UpdateUserRoleAndPermissions_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-user-authorization") + { + 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); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs new file mode 100644 index 00000000..c1ff40b9 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +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.FileSystemManagement.Directories.GetDirectories; + +/// +/// Contains integration tests for the /directories/api-get-directories route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoriesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly DirectoryDtoFixture _directoryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetDirectoriesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetDirectories_WhenCalledByAuthenticatedUser_ShouldReturnDirectoriesFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string path = @"C:\Users\test"; + DirectoryDto[] expectedDirectories = [_directoryDtoFixture.Create(path: path, name: "test")]; + string expectedEndpoint = $"directories/get-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements=True"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedDirectories); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/directories/api-get-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements=true"); + 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()); + Assert.Equal(expectedDirectories.Length, json.RootElement.GetProperty("data").GetArrayLength()); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs new file mode 100644 index 00000000..07c7e66c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Drives.GetDrives; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +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.FileSystemManagement.Drives.GetDrives; + +/// +/// Contains integration tests for the /drives/api-get-drives route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetDrivesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly FileSystemTreeNodeDtoFixture _fileSystemTreeNodeDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetDrivesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetDrives_WhenCalledByAuthenticatedUser_ShouldReturnDrivesFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + FileSystemTreeNodeDto[] expectedDrives = [_fileSystemTreeNodeDtoFixture.Create(path: "C:\\", name: "C:")]; + _apiFactory.ApiClientStub.RegisterGetResponse("drives/get-drives", expectedDrives); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/drives/api-get-drives"); + 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()); + Assert.Equal(expectedDrives.Length, json.RootElement.GetProperty("data").GetProperty("drives").GetArrayLength()); + Assert.Contains("drives/get-drives", _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs new file mode 100644 index 00000000..f2153bc0 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.FileSystem; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.FileSystem.GetType; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +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.FileSystemManagement.FileSystem.GetType; + +/// +/// Contains integration tests for the /file-system/api-get-type route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetTypeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly FileSystemTypeDtoFixture _fileSystemTypeDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetTypeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetType_WhenCalledByAuthenticatedUser_ShouldReturnFileSystemTypeFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetResponse("file-system/get-type", _fileSystemTypeDtoFixture.Create(platformType: PlatformType.Windows)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/file-system/api-get-type"); + 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()); + Assert.Equal(nameof(PlatformType.Windows), json.RootElement.GetProperty("data").GetProperty("platformType").GetString()); + Assert.Contains("file-system/get-type", _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs new file mode 100644 index 00000000..cc2ccee9 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Files.GetFiles; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +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.FileSystemManagement.Files.GetFiles; + +/// +/// Contains integration tests for the /files/api-get-files route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetFilesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly FileDtoFixture _fileDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetFilesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetFiles_WhenCalledByAuthenticatedUser_ShouldReturnFilesFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string path = @"C:\Users\test"; + FileDto[] expectedFiles = [_fileDtoFixture.Create(path: path, name: "book.pdf")]; + string expectedEndpoint = $"files/get-files?path={Uri.EscapeDataString(path)}&includeHiddenElements=True"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedFiles); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/files/api-get-files?path={Uri.EscapeDataString(path)}&includeHiddenElements=true"); + 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()); + Assert.Equal(expectedFiles.Length, json.RootElement.GetProperty("data").GetArrayLength()); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs new file mode 100644 index 00000000..b391ad50 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +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.FileSystemManagement.Files.GetTreeFiles; + +/// +/// Contains integration tests for the /files/api-get-tree-files route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetTreeFilesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly FileSystemTreeNodeDtoFixture _fileSystemTreeNodeDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetTreeFilesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetTreeFiles_WhenCalledByAuthenticatedUser_ShouldReturnFileSystemTreeFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string path = @"C:\Users\test"; + FileSystemTreeNodeDto[] expectedNodes = [_fileSystemTreeNodeDtoFixture.Create(path: path, name: "test")]; + string expectedEndpoint = $"files/get-tree-files?path={Uri.EscapeDataString(path)}&includeHiddenElements=True"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedNodes); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/files/api-get-tree-files?path={Uri.EscapeDataString(path)}&includeHiddenElements=true"); + 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()); + Assert.Equal(expectedNodes.Length, json.RootElement.GetProperty("data").GetArrayLength()); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs new file mode 100644 index 00000000..835e0471 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.CheckPathExists; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +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.FileSystemManagement.Path.CheckPathExists; + +/// +/// Contains integration tests for the /path/api-check-path-exists route served by the class. +/// +[ExcludeFromCodeCoverage] +public class CheckPathExistsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PathExistsDtoFixture _pathExistsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public CheckPathExistsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task CheckPathExists_WhenCalledByAuthenticatedUser_ShouldReturnExistenceFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string path = @"C:\Users\test"; + string expectedEndpoint = $"path/check-path-exists?path={Uri.EscapeDataString(path)}&includeHiddenElements=True"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _pathExistsDtoFixture.Create(exists: true)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-check-path-exists?path={Uri.EscapeDataString(path)}&includeHiddenElements=true"); + 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()); + Assert.True(json.RootElement.GetProperty("data").GetProperty("exists").GetBoolean()); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs new file mode 100644 index 00000000..f3c3d81e --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathParent; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +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.FileSystemManagement.Path.GetPathParent; + +/// +/// Contains integration tests for the /path/api-get-path-parent route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathParentEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PathSegmentDtoFixture _pathSegmentDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPathParentEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetPathParent_WhenCalledByAuthenticatedUser_ShouldReturnPathSegmentsFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string path = @"C:\Users\test"; + PathSegmentDto[] expectedSegments = [_pathSegmentDtoFixture.Create(path: @"C:\Users")]; + string expectedEndpoint = $"path/get-path-parent?path={Uri.EscapeDataString(path)}"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedSegments); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-get-path-parent?path={Uri.EscapeDataString(path)}"); + 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()); + Assert.Equal(expectedSegments.Length, json.RootElement.GetProperty("data").GetProperty("pathSegments").GetArrayLength()); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs new file mode 100644 index 00000000..5aa67b41 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathRoot; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +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.FileSystemManagement.Path.GetPathRoot; + +/// +/// Contains integration tests for the /path/api-get-path-root route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathRootEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PathSegmentDtoFixture _pathSegmentDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPathRootEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetPathRoot_WhenCalledByAuthenticatedUser_ShouldReturnPathRootFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string path = @"C:\Users\test"; + string expectedEndpoint = $"path/get-path-root?path={Uri.EscapeDataString(path)}"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _pathSegmentDtoFixture.Create(path: @"C:\")); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-get-path-root?path={Uri.EscapeDataString(path)}"); + 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()); + Assert.Equal(@"C:\", json.RootElement.GetProperty("data").GetProperty("root").GetProperty("path").GetString()); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs new file mode 100644 index 00000000..c3d971da --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +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.FileSystemManagement.Path.GetPathSeparator; + +/// +/// Contains integration tests for the /path/api-get-path-separator route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathSeparatorEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PathSeparatorDtoFixture _pathSeparatorDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPathSeparatorEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetPathSeparator_WhenCalledByAuthenticatedUser_ShouldReturnPathSeparatorFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedSeparator = "\\"; + _apiFactory.ApiClientStub.RegisterGetResponse("path/get-path-separator", _pathSeparatorDtoFixture.Create(separator: expectedSeparator)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/path/api-get-path-separator"); + 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()); + Assert.Equal(expectedSeparator, json.RootElement.GetProperty("data").GetProperty("pathSeparator").GetString()); + Assert.Contains("path/get-path-separator", _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs new file mode 100644 index 00000000..9099673a --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.SplitPath; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +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.FileSystemManagement.Path.SplitPath; + +/// +/// Contains integration tests for the /path/api-split route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SplitPathEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PathSegmentDtoFixture _pathSegmentDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SplitPathEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SplitPath_WhenCalledByAuthenticatedUser_ShouldReturnPathSegmentsFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string path = @"C:\Users\test"; + PathSegmentDto[] expectedSegments = + [ + _pathSegmentDtoFixture.Create(path: @"C:\"), + _pathSegmentDtoFixture.Create(path: "Users"), + _pathSegmentDtoFixture.Create(path: "test") + ]; + string expectedEndpoint = $"path/split?path={Uri.EscapeDataString(path)}"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedSegments); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-split?path={Uri.EscapeDataString(path)}"); + 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()); + Assert.Equal(expectedSegments.Length, json.RootElement.GetProperty("data").GetProperty("pathSegments").GetArrayLength()); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs new file mode 100644 index 00000000..01313cdc --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.ValidatePath; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +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.FileSystemManagement.Path.ValidatePath; + +/// +/// Contains integration tests for the /path/api-validate route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ValidatePathEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PathValidDtoFixture _pathValidDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ValidatePathEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ValidatePath_WhenCalledByAuthenticatedUser_ShouldReturnValidityFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string path = @"C:\Users\test"; + string expectedEndpoint = $"path/validate?path={Uri.EscapeDataString(path)}"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _pathValidDtoFixture.Create(isValid: true)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-validate?path={Uri.EscapeDataString(path)}"); + 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()); + Assert.True(json.RootElement.GetProperty("data").GetProperty("isValid").GetBoolean()); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs new file mode 100644 index 00000000..60fab458 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Home; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Home; + +/// +/// Contains integration tests for the /{culture}/error route served by the class. +/// +[ExcludeFromCodeCoverage] +public class HomeErrorEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public HomeErrorEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task HomeError_WhenCalledByAuthenticatedUser_ShouldRenderErrorPage() + { + // Arrange + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/error"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("text-danger", content); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs new file mode 100644 index 00000000..09b1028f --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Home; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Home; + +/// +/// Contains integration tests for the /{culture}/not-found route served by the class. +/// +[ExcludeFromCodeCoverage] +public class HomeNotFoundViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public HomeNotFoundViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task HomeNotFoundView_WhenCalledByAuthenticatedUser_ShouldRenderNotFoundPage() + { + // Arrange + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/not-found"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs new file mode 100644 index 00000000..86ca4fb6 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Home; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Home; + +/// +/// Contains integration tests for the /{culture}/privacy route served by the class. +/// +[ExcludeFromCodeCoverage] +public class HomePrivacyEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public HomePrivacyEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task HomePrivacy_WhenCalledByAuthenticatedUser_ShouldRenderPrivacyPage() + { + // Arrange + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/privacy"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("Privacy Policy", content); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs new file mode 100644 index 00000000..63ef8b49 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.AddLibrary; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.AddLibrary; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/item route served by the class. +/// +[ExcludeFromCodeCoverage] +public class AddLibraryViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AddLibraryViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task AddLibraryView_WhenCalledByAuthenticatedUser_ShouldRenderLibraryAddingView() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage/item"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs new file mode 100644 index 00000000..7e85cdb0 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.CancelLibrariesScan; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.CancelLibrariesScan; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-cancel-libraries-scan route served by the class. +/// +[ExcludeFromCodeCoverage] +public class CancelLibrariesScanEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public CancelLibrariesScanEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task CancelLibrariesScan_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldCancelScansAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostResponseFactory("libraries/scans/cancel", _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage cancelRequest = CreateCancelRequest("/en-us/libraries/manage/api-cancel-libraries-scan"); + cancelRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(cancelRequest); + 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.PostRequests, postRequest => postRequest.Endpoint == "libraries/scans/cancel"); + } + + /// + /// Builds the cancel request that posts an empty JSON body to the given . + /// + /// The URL of the cancel endpoint. + /// The configured cancel request. + private static HttpRequestMessage CreateCancelRequest(string url) + { + HttpRequestMessage cancelRequest = new(HttpMethod.Post, url) + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + cancelRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + cancelRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return cancelRequest; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs new file mode 100644 index 00000000..93b3b4aa --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.CancelLibraryScan; +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; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.CancelLibraryScan; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/{{libraryId}}/api-cancel-library-scan/{{scanId}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class CancelLibraryScanEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public CancelLibraryScanEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task CancelLibraryScan_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldCancelScanAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + Guid scanId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterPostResponseFactory($"libraries/{libraryId}/scans/{scanId}/cancel", _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage cancelRequest = CreateCancelRequest($"/en-us/libraries/manage/{libraryId}/api-cancel-library-scan/{scanId}"); + cancelRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(cancelRequest); + 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.PostRequests, postRequest => postRequest.Endpoint == $"libraries/{libraryId}/scans/{scanId}/cancel"); + } + + /// + /// Builds the cancel request that posts an empty JSON body to the given . + /// + /// The URL of the cancel endpoint. + /// The configured cancel request. + private static HttpRequestMessage CreateCancelRequest(string url) + { + HttpRequestMessage cancelRequest = new(HttpMethod.Post, url) + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + cancelRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + cancelRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return cancelRequest; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs new file mode 100644 index 00000000..16c5b86f --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.DeleteLibrary; +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; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.DeleteLibrary; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-item/{{id}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteLibraryEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeleteLibraryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DeleteLibrary_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldDeleteLibraryAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}"); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = CreateDeleteRequest(libraryId); + deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + 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.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}"); + } + + /// + /// Builds the delete request for the library identified by . + /// + /// The Id of the library to delete. + /// The configured delete request. + private static HttpRequestMessage CreateDeleteRequest(Guid libraryId) + { + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/libraries/manage/api-item/{libraryId}") + { + // the front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return deleteRequest; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs new file mode 100644 index 00000000..08ea87d2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.EditLibrary; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +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.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.EditLibrary; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/item/{{id}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class EditLibraryViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly LibraryDtoFixture _libraryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public EditLibraryViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task EditLibraryView_WhenCalledByAuthenticatedUser_ShouldRenderLibraryEditingView() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + LibraryDto expectedLibrary = _libraryDtoFixture.Create(id: libraryId, title: "Books", libraryType: "Book"); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", expectedLibrary); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/item/{libraryId}"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + Assert.Contains($"libraries/{libraryId}", _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs new file mode 100644 index 00000000..028e6e65 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetEnabledLibraries; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +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.GetEnabledLibraries; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-get-enabled-libraries route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetEnabledLibrariesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly LibraryDtoFixture _libraryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetEnabledLibrariesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetEnabledLibraries_WhenCalledByAuthenticatedUser_ShouldReturnEnabledLibrariesJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + LibraryDto[] expectedLibraries = + [ + _libraryDtoFixture.Create(id: Guid.NewGuid(), title: "Books", libraryType: "Book"), + _libraryDtoFixture.Create(id: Guid.NewGuid(), title: "Movies", libraryType: "Video") + ]; + _apiFactory.ApiClientStub.RegisterGetResponse("libraries/enabled", expectedLibraries); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/libraries/manage/api-get-enabled-libraries"); + 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(2, data.GetArrayLength()); + Assert.Equal("Books", data[0].GetProperty("title").GetString()); + } + + [Fact] + public async Task GetEnabledLibraries_WhenCalled_ShouldRequestEnabledLibrariesFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetResponse("libraries/enabled", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/libraries/manage/api-get-enabled-libraries"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Contains("libraries/enabled", _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..7ff6e394 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetMetadataProviders; +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.GetMetadataProviders; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-get-metadata-providers/{{libraryId}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetMetadataProvidersEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly LibraryMetadataProviderDtoFixture _libraryMetadataProviderDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetMetadataProvidersEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetMetadataProviders_WhenCalledByAuthenticatedUser_ShouldReturnMetadataProvidersJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + LibraryMetadataProviderDto[] expectedProviders = + [ + _libraryMetadataProviderDtoFixture.Create(name: "Metadata Provider One", isEnabled: true, rank: 1), + _libraryMetadataProviderDtoFixture.Create(name: "Metadata Provider Two", isEnabled: false, rank: 2) + ]; + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/metadata-providers", expectedProviders); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-metadata-providers/{libraryId}"); + 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(2, data.GetArrayLength()); + Assert.Equal("Metadata Provider One", data[0].GetProperty("name").GetString()); + } + + [Fact] + public async Task GetMetadataProviders_WhenCalled_ShouldRequestMetadataProvidersFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/metadata-providers", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-metadata-providers/{libraryId}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Contains($"libraries/{libraryId}/metadata-providers", _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs new file mode 100644 index 00000000..4d1fcea0 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetRunningLibraryScans; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +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.GetRunningLibraryScans; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-get-running-library-scans route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetRunningLibraryScansEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly LibraryScanProgressDtoFixture _libraryScanProgressDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetRunningLibraryScansEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetRunningLibraryScans_WhenCalledByAuthenticatedUser_ShouldReturnRunningLibraryScansJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + LibraryScanProgressDto[] expectedScans = + [ + _libraryScanProgressDtoFixture.Create(includeCurrentJobProgress: true), + _libraryScanProgressDtoFixture.Create() + ]; + _apiFactory.ApiClientStub.RegisterGetResponse("libraries/scans/running", expectedScans); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/libraries/manage/api-get-running-library-scans"); + 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(2, data.GetArrayLength()); + Assert.Equal(JsonValueKind.Object, data[0].GetProperty("currentJobProgress").ValueKind); + } + + [Fact] + public async Task GetRunningLibraryScans_WhenCalled_ShouldRequestRunningLibraryScansFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetResponse("libraries/scans/running", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/libraries/manage/api-get-running-library-scans"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Contains("libraries/scans/running", _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} 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 new file mode 100644 index 00000000..e36f0c3d --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.Index; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.Index; + +/// +/// Contains integration tests for the /{culture}/libraries/manage route served by the class. +/// +[ExcludeFromCodeCoverage] +public class LibrariesIndexViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public LibrariesIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task LibrariesIndexView_WhenCalledByAuthenticatedUser_ShouldRenderLibrariesManagementView() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} 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 new file mode 100644 index 00000000..6765f340 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs @@ -0,0 +1,71 @@ +#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 /{culture}/libraries/manage/api-reorder-metadata-providers route served by 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/ScanLibraries/ScanLibrariesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs new file mode 100644 index 00000000..f9dda266 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ScanLibraries; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +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; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ScanLibraries; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-scan-libraries route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ScanLibrariesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ScanLibraryDtoFixture _scanLibraryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ScanLibrariesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ScanLibraries_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldInitiateScanAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + ScanLibraryDto[] expectedScans = + [ + _scanLibraryDtoFixture.Create(libraryId: libraryId) + ]; + _apiFactory.ApiClientStub.RegisterPostResponse("libraries/scans", expectedScans); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage scanRequest = CreateScanRequest("/en-us/libraries/manage/api-scan-libraries"); + scanRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(scanRequest); + 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.Equal(1, json.RootElement.GetProperty("data").GetArrayLength()); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries/scans"); + } + + /// + /// Builds the scan request that posts an empty JSON body to the given . + /// + /// The URL of the scan endpoint. + /// The configured scan request. + private static HttpRequestMessage CreateScanRequest(string url) + { + HttpRequestMessage scanRequest = new(HttpMethod.Post, url) + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + scanRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + scanRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return scanRequest; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs new file mode 100644 index 00000000..e615d08e --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ScanLibrary; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +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; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ScanLibrary; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-scan-library/{{id}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ScanLibraryEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ScanLibraryDtoFixture _scanLibraryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ScanLibraryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ScanLibrary_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldInitiateScanAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + ScanLibraryDto expectedScan = _scanLibraryDtoFixture.Create(libraryId: libraryId); + _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{libraryId}/scans", expectedScan); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage scanRequest = CreateScanRequest($"/en-us/libraries/manage/api-scan-library/{libraryId}"); + scanRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(scanRequest); + 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.Equal(libraryId, json.RootElement.GetProperty("data").GetProperty("libraryId").GetGuid()); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == $"libraries/{libraryId}/scans"); + } + + /// + /// Builds the scan request that posts an empty JSON body to the given . + /// + /// The URL of the scan endpoint. + /// The configured scan request. + private static HttpRequestMessage CreateScanRequest(string url) + { + HttpRequestMessage scanRequest = new(HttpMethod.Post, url) + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + scanRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + scanRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return scanRequest; + } +} 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 new file mode 100644 index 00000000..093e89a2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs @@ -0,0 +1,71 @@ +#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 /{culture}/libraries/manage/api-set-metadata-provider-enabled route served by 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/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs new file mode 100644 index 00000000..6d694754 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.EditBook; +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.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.EditBook; + +/// +/// Contains integration tests for the /{culture}/library/written-content-library/books-library/books/{{id}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class EditBookViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public EditBookViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task EditBook_WhenCalledByAuthenticatedUser_ShouldRenderEditBookPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/{Guid.NewGuid()}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + Assert.Contains("A book", content); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs new file mode 100644 index 00000000..3e3ac35e --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +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.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems; + +/// +/// Contains integration tests for the /{culture}/library/written-content-library/books-library/books/api-get-library-items route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryItemsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PaginatedBookLiteDtoFixture _paginatedBookLiteDtoFixture = new(); + private readonly BookLiteDtoFixture _bookLiteDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibraryItemsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraryItems_WhenCalledByAuthenticatedUser_ShouldReturnBooksFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + string searchTerm = "Harry"; + PaginatedBookLiteDto expectedResponse = _paginatedBookLiteDtoFixture.Create(data: [_bookLiteDtoFixture.Create(title: "Harry Potter")]); + string expectedEndpoint = $"books/lite?libraryId={libraryId}¤tPage=1&perPage=20&searchTerm={searchTerm}&shouldIgnoreThePrefixForAlphaPicker=True"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedResponse); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/api-get-library-items?libraryId={libraryId}¤tPage=1&perPage=20&searchTerm={searchTerm}&shouldIgnoreThePrefixForAlphaPicker=true"); + 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()); + Assert.Equal(expectedResponse.Data.Count, json.RootElement.GetProperty("data").GetProperty("data").GetArrayLength()); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs new file mode 100644 index 00000000..2661e493 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +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.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index; + +/// +/// Contains integration tests for the /{culture}/library/written-content-library/books-library/books route served by the class. +/// +[ExcludeFromCodeCoverage] +public class BooksIndexViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly LibraryDtoFixture _libraryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public BooksIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task BooksIndex_WhenCalledByAuthenticatedUserWithLibraryId_ShouldRenderBooksPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + LibraryDto expectedLibrary = _libraryDtoFixture.Create(id: libraryId, title: "Books"); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", expectedLibrary); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books?libraryId={libraryId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + Assert.Contains("search-input", content); + Assert.Contains($"libraries/{libraryId}", _apiFactory.ApiClientStub.GetEndpointsCalled); + } + + [Fact] + public async Task BooksIndex_WhenCalledByAuthenticatedUserWithoutLibraryId_ShouldRedirectToHome() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/library/written-content-library/books-library/books"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("/en-us", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs new file mode 100644 index 00000000..65bcc2b6 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPluginSettings; +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.Plugins.GetPluginSettings; + +/// +/// Contains integration tests for the /{culture}/admin/manage-plugins/api-get-plugin-settings/{pluginId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetPluginSettingsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PluginSettingsDtoFixture _pluginSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPluginSettingsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetPluginSettings_WhenCalledByAuthenticatedAdmin_ShouldReturnPluginSettingsFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid pluginId = Guid.NewGuid(); + PluginSettingsDto expectedSettings = _pluginSettingsDtoFixture.Create(pluginId: pluginId); + string expectedEndpoint = $"plugins/{pluginId}/settings"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedSettings); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/admin/manage-plugins/api-get-plugin-settings/{pluginId}"); + 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()); + Assert.Equal(pluginId, json.RootElement.GetProperty("data").GetProperty("pluginId").GetGuid()); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == expectedEndpoint); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs new file mode 100644 index 00000000..01346b29 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Plugins.Index; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Plugins.Index; + +/// +/// Contains integration tests for the /{culture}/admin/manage-plugins route served by the class. +/// +[ExcludeFromCodeCoverage] +public class PluginsIndexViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PluginDtoFixture _pluginDtoFixture = new(); + private readonly PluginSettingsDtoFixture _pluginSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public PluginsIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task PluginsIndex_WhenCalledByAuthenticatedAdmin_ShouldRenderPluginsManagementPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + PluginDto[] expectedPlugins = [_pluginDtoFixture.Create(name: "OpenLibrary")]; + string settingsEndpoint = $"plugins/{expectedPlugins[0].Id}/settings"; + _apiFactory.ApiClientStub.RegisterGetResponse("plugins", expectedPlugins); + _apiFactory.ApiClientStub.RegisterGetResponse(settingsEndpoint, _pluginSettingsDtoFixture.Create(pluginId: expectedPlugins[0].Id)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-plugins"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "plugins"); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == settingsEndpoint); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs new file mode 100644 index 00000000..f5801bd9 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Themes.ThemeAssets; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Themes.ThemeAssets; + +/// +/// Contains integration tests for the /theme-assets/{themeId}/{path} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeAssetsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly BlobDataDtoFixture _blobDataDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ThemeAssetsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ThemeAssets_WhenCalledWithValidThemeAndPath_ShouldReturnAsset() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + byte[] expectedBytes = [0x89, 0x50, 0x4E, 0x47]; + _apiFactory.ApiClientStub.RegisterBlobResponse(_blobDataDtoFixture.Create(data: expectedBytes, contentType: "image/png")); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage assetRequest = new(HttpMethod.Get, "/theme-assets/test-theme/assets/logo.png"); + assetRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await client.SendAsync(assetRequest); + byte[] content = await response.Content.ReadAsByteArrayAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("image/png", response.Content.Headers.ContentType!.MediaType); + Assert.Equal(expectedBytes, content); + } + + [Fact] + public async Task ThemeAssets_WhenCalledWithEmptyPath_ShouldReturnBadRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/theme-assets/test-theme/"); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs new file mode 100644 index 00000000..751b5e03 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.AccessDenied; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.AccessDenied; + +/// +/// Contains integration tests for the /{culture}/auth/access-denied route served by the class. +/// +[ExcludeFromCodeCoverage] +public class AccessDeniedViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AccessDeniedViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task AccessDeniedView_WhenCalled_ShouldRenderAccessDeniedPage() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/access-denied"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs new file mode 100644 index 00000000..88dea4da --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.ChangePassword; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +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.UsersManagement.Authentication.ChangePassword; + +/// +/// Contains integration tests for the /{culture}/auth/api-change-password route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ChangePasswordRequestFixture _changePasswordRequestFixture = new(); + private readonly ChangePasswordResponseFixture _changePasswordResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ChangePasswordEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ChangePassword_WhenCalledByAuthenticatedUser_ShouldChangePasswordForCurrentUser() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + ChangePasswordResponse expectedResponse = _changePasswordResponseFixture.Create(isPasswordChanged: true); + _apiFactory.ApiClientStub.RegisterPostResponse("auth/change-password", expectedResponse); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + ChangePasswordRequest request = _changePasswordRequestFixture.Create(currentPassword: "OldPass123!", newPassword: "NewPass123!", newPasswordConfirm: "NewPass123!"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(CreateChangePasswordRequest(request, webClient.AntiforgeryToken)); + 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()); + (string Endpoint, object? Data) postRequest = _apiFactory.ApiClientStub.PostRequests.Single(postRequest => postRequest.Endpoint == "auth/change-password"); + ChangePasswordRequest sentRequest = Assert.IsType(postRequest.Data); + Assert.Equal("testuser", sentRequest.Username); + } + + /// + /// Builds the change password request that sends the given to the change password endpoint. + /// + /// The change password request to send. + /// The antiforgery token to include in the request. + /// The configured change password request. + private static HttpRequestMessage CreateChangePasswordRequest(ChangePasswordRequest request, string antiforgeryToken) + { + HttpRequestMessage changePasswordRequest = new(HttpMethod.Post, "/en-us/auth/api-change-password") + { + Content = JsonContent.Create(request) + }; + changePasswordRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + changePasswordRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + changePasswordRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return changePasswordRequest; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs new file mode 100644 index 00000000..c82a4497 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.ChangePassword; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.ChangePassword; + +/// +/// Contains integration tests for the /{culture}/auth/change-password route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ChangePasswordViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ChangePasswordView_WhenCalledByAuthenticatedUser_ShouldRenderChangePasswordPage() + { + // Arrange + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/auth/change-password"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("change-password-form", content); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs new file mode 100644 index 00000000..b0457f9e --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Logout; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.Logout; + +/// +/// Contains integration tests for the /{culture}/auth/logout route served by the class. +/// +[ExcludeFromCodeCoverage] +public class LogoutEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public LogoutEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task Logout_WhenCalledByAuthenticatedUser_ShouldSignOutAndRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/auth/logout"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs new file mode 100644 index 00000000..dd0909c4 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +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.UsersManagement.Authentication.RecoverPassword; + +/// +/// Contains integration tests for the /{culture}/auth/api-recover-password route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture = new(); + private readonly RecoverPasswordResponseFixture _recoverPasswordResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RecoverPasswordEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RecoverPassword_WhenCalledWithValidData_ShouldResetPassword() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + RecoverPasswordResponse expectedResponse = _recoverPasswordResponseFixture.Create(isPasswordReset: true); + _apiFactory.ApiClientStub.RegisterPostResponse("auth/recover-password", expectedResponse); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(username: "testuser", totpCode: "123456"); + + // Act + HttpResponseMessage response = await client.SendAsync(CreateRecoverPasswordRequest(request, antiforgeryToken)); + 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.True(json.RootElement.GetProperty("data").GetProperty("isPasswordReset").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "auth/recover-password"); + } + + /// + /// Builds the recover password request that sends the given to the recover password endpoint. + /// + /// The recover password request to send. + /// The antiforgery token to include in the request. + /// The configured recover password request. + private static HttpRequestMessage CreateRecoverPasswordRequest(RecoverPasswordRequest request, string antiforgeryToken) + { + HttpRequestMessage recoverPasswordRequest = new(HttpMethod.Post, "/en-us/auth/api-recover-password") + { + Content = JsonContent.Create(request) + }; + recoverPasswordRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + recoverPasswordRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + recoverPasswordRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return recoverPasswordRequest; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs new file mode 100644 index 00000000..be8a1c62 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; + +/// +/// Contains integration tests for the /{culture}/auth/recover-password route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RecoverPasswordViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RecoverPasswordView_WhenCalled_ShouldRenderRecoverPasswordPage() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/recover-password"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("recover-password-form", content); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs new file mode 100644 index 00000000..4a23234f --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs @@ -0,0 +1,103 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Register; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +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.UsersManagement.Authentication.Register; + +/// +/// Contains integration tests for the /{culture}/auth/api-register route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly RegisterRequestFixture _registerRequestFixture = new(); + private readonly RegisterResponseFixture _registerResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RegisterEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task Register_WhenCalledWithValidData_ShouldRegisterAccount() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + RegisterResponse expectedResponse = _registerResponseFixture.Create(username: "newuser"); + _apiFactory.ApiClientStub.RegisterPostResponse("auth/register", expectedResponse); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + RegisterRequest request = _registerRequestFixture.Create(username: "newuser", password: "Abcd123$", passwordConfirm: "Abcd123$"); + + // Act + HttpResponseMessage response = await client.SendAsync(CreateRegisterRequest(request, antiforgeryToken)); + 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.Equal("newuser", json.RootElement.GetProperty("data").GetProperty("username").GetString()); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "auth/register"); + } + + [Fact] + public async Task Register_WhenRegistrationTypeIsAdmin_ShouldCallInitializationEndpoint() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + RegisterResponse expectedResponse = _registerResponseFixture.Create(username: "admin"); + _apiFactory.ApiClientStub.RegisterPostResponse("initialization", expectedResponse); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + RegisterRequest request = _registerRequestFixture.Create(username: "admin", password: "Abcd123$", passwordConfirm: "Abcd123$", registrationType: "Admin"); + + // Act + HttpResponseMessage response = await client.SendAsync(CreateRegisterRequest(request, antiforgeryToken)); + 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.PostRequests, postRequest => postRequest.Endpoint == "initialization"); + } + + /// + /// Builds the register request that sends the given to the register endpoint. + /// + /// The register request to send. + /// The antiforgery token to include in the request. + /// The configured register request. + private static HttpRequestMessage CreateRegisterRequest(RegisterRequest request, string antiforgeryToken) + { + HttpRequestMessage registerRequest = new(HttpMethod.Post, "/en-us/auth/api-register") + { + Content = JsonContent.Create(request) + }; + registerRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + registerRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + registerRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return registerRequest; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs new file mode 100644 index 00000000..ccc43887 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Register; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.Register; + +/// +/// Contains integration tests for the /{culture}/auth/register route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RegisterViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RegisterView_WhenCalled_ShouldRenderRegisterPage() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/register"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("register-account-form", content); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs new file mode 100644 index 00000000..a60be659 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Maintenance.ApplicationSetup; + +/// +/// Contains security tests for the /initialization route. +/// +[ExcludeFromCodeCoverage] +public class CheckInitializationEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public CheckInitializationEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task CheckInitialization_WhenCalledWithoutAuthentication_ShouldBeAccessible() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/initialization"); + + // Assert + // the initialization check is anonymous, so it must never demand authentication or leak any internal data + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs new file mode 100644 index 00000000..c6235d7d --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs @@ -0,0 +1,92 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Maintenance.ApplicationSetup; + +/// +/// Contains security tests for the /initialization route. +/// +[ExcludeFromCodeCoverage] +public class SetupApplicationEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly RegistrationRequestFixture _registrationRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public SetupApplicationEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task SetupApplication_WhenCalledWithoutAuthentication_ShouldBeAccessible() + { + // Arrange + RegistrationRequest request = _registrationRequestFixture.Create( + username: $"testuser_{Guid.NewGuid()}", + password: "TestPass123!", + passwordConfirm: "TestPass123!", + use2fa: false + ); + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // the setup endpoint is anonymous, so it must never demand authentication; the admin account is created once, so + // the request either creates it or reports that it already exists, depending on the shared database state of the class + Assert.True(response.StatusCode == HttpStatusCode.Created || response.StatusCode == HttpStatusCode.Conflict); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("admin'--")] // comment injection + [InlineData("' UNION SELECT * FROM Users--")] // union injection + [InlineData("'; DROP TABLE Users--")] // destructive injection + public async Task SetupApplication_WithSQLInjectionAttempt_ShouldRemainSecure(string maliciousUsername) + { + // Arrange + // note: the setup validator only checks that the username is not empty, so the malicious value reaches the handler, + // where it is used as a literal username in parameterized queries; the security guarantee is that it never + // executes as SQL or leaks the query internals + RegistrationRequest request = _registrationRequestFixture.Create( + username: maliciousUsername, + password: "TestPass123!", + passwordConfirm: "TestPass123!", + use2fa: false + ); + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // the malicious username is treated as literal data (the setup either creates the admin or reports that one already exists), + // so the request must never fail with an unhandled exception or leak the query internals + Assert.True(response.StatusCode == HttpStatusCode.Created || response.StatusCode == HttpStatusCode.Conflict); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", 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/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs new file mode 100644 index 00000000..6de8855b --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs @@ -0,0 +1,139 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.AddRole; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; +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; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Authorization.Roles.AddRole; + +/// +/// Contains security tests for the /{culture}/admin/api-create-role route served by the class. +/// +[ExcludeFromCodeCoverage] +public class AddRoleEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly AddRoleRequestFixture _addRoleRequestFixture = new(); + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly RolePermissionsDtoFixture _rolePermissionsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AddRoleEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task AddRole_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/admin/api-create-role") + { + Content = JsonContent.Create(_addRoleRequestFixture.Create()) + }; + createRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + createRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(createRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "auth/roles"); + } + + [Fact] + public async Task AddRole_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/admin/api-create-role") + { + Content = JsonContent.Create(_addRoleRequestFixture.Create()) + }; + createRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "auth/roles"); + } + + [Fact] + public async Task AddRole_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/admin/api-create-role") + { + Content = JsonContent.Create(_addRoleRequestFixture.Create()) + }; + createRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + createRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Theory] + [InlineData("'; DROP TABLE Roles--")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task AddRole_WithInjectionInRoleName_ShouldRemainSecure(string maliciousRoleName) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AddRoleRequest request = _addRoleRequestFixture.Create(roleName: maliciousRoleName); + _apiFactory.ApiClientStub.RegisterPostResponse("auth/roles", _rolePermissionsDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/admin/api-create-role") + { + Content = JsonContent.Create(request) + }; + createRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + createRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs new file mode 100644 index 00000000..fb2ed8cf --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs @@ -0,0 +1,136 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; +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; +using System.Net; +using System.Net.Http.Headers; +using System.Text; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; + +/// +/// Contains security tests for the /{culture}/admin/api-delete-role/{roleId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteRoleEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeleteRoleEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DeleteRole_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + Guid roleId = Guid.NewGuid(); + HttpRequestMessage deleteRequest = CreateDeleteRequest(roleId); + deleteRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"auth/roles/{roleId}"); + } + + [Fact] + public async Task DeleteRole_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + Guid roleId = Guid.NewGuid(); + HttpRequestMessage deleteRequest = CreateDeleteRequest(roleId); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"auth/roles/{roleId}"); + } + + [Fact] + public async Task DeleteRole_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid()); + 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()); + } + + [Theory] + [InlineData("'; DROP TABLE Roles--")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task DeleteRole_WithInjectionInRoleId_ShouldRemainSecure(string maliciousRoleId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/admin/api-delete-role/{Uri.EscapeDataString(maliciousRoleId)}") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled); + } + + /// + /// Builds a DELETE request for the role deletion route with the JSON content type required by the antiforgery validation. + /// + /// The identifier of the role to delete. + /// The configured DELETE request. + private static HttpRequestMessage CreateDeleteRequest(Guid roleId) + { + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/admin/api-delete-role/{roleId}") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return deleteRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs new file mode 100644 index 00000000..9da9e71a --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRolePermissions; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +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; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Authorization.Roles.GetRolePermissions; + +/// +/// Contains security tests for the /{culture}/admin/api-get-permissions-by-role-id/{roleId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetRolePermissionsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly RolePermissionsDtoFixture _rolePermissionsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetRolePermissionsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetRolePermissions_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/api-get-permissions-by-role-id/" + Guid.NewGuid()); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("auth/login", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetRolePermissions_WhenCalledByNonAdminUser_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/admin/api-get-permissions-by-role-id/" + Guid.NewGuid()); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetRolePermissions_WhenCalledByAdminUser_ShouldReturnRolePermissionsData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + Guid roleId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterGetResponse($"auth/roles/{roleId}/permissions", _rolePermissionsDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-permissions-by-role-id/" + roleId); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs new file mode 100644 index 00000000..1cd600ba --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs @@ -0,0 +1,139 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.UpdateRole; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; +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; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Authorization.Roles.UpdateRole; + +/// +/// Contains security tests for the /{culture}/admin/api-update-role route served by the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateRoleEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly RolePermissionsDtoFixture _rolePermissionsDtoFixture = new(); + private readonly UpdateRoleRequestFixture _updateRoleRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdateRoleEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateRole_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-role") + { + Content = JsonContent.Create(_updateRoleRequestFixture.Create()) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + 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 == "auth/roles"); + } + + [Fact] + public async Task UpdateRole_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-role") + { + Content = JsonContent.Create(_updateRoleRequestFixture.Create()) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "auth/roles"); + } + + [Fact] + public async Task UpdateRole_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-role") + { + Content = JsonContent.Create(_updateRoleRequestFixture.Create()) + }; + 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); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Theory] + [InlineData("'; DROP TABLE Roles--")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateRole_WithInjectionInRoleName_ShouldRemainSecure(string maliciousRoleName) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + UpdateRoleRequest request = _updateRoleRequestFixture.Create(roleName: maliciousRoleName); + _apiFactory.ApiClientStub.RegisterPutResponse("auth/roles", _rolePermissionsDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-role") + { + 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 + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs new file mode 100644 index 00000000..2730d614 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.Admin.ManagePermissions; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +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; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.ManagePermissions; + +/// +/// Contains security tests for the /{culture}/admin/manage-permissions route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ManagePermissionsViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly PermissionDtoFixture _permissionDtoFixture = new(); + private readonly RoleDtoFixture _roleDtoFixture = new(); + private readonly UserDtoFixture _userDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ManagePermissionsViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ManagePermissions_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/manage-permissions"); + + // 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 == "auth/users"); + } + + [Fact] + public async Task ManagePermissions_WhenCalledByNonAdminUser_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/admin/manage-permissions"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task ManagePermissions_WhenCalledByAdminUser_ShouldReturnPermissionsPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + UserDto[] expectedUsers = [.. _userDtoFixture.CreateMany()]; + RoleDto[] expectedRoles = [.. _roleDtoFixture.CreateMany()]; + PermissionDto[] expectedPermissions = [.. _permissionDtoFixture.CreateMany()]; + _apiFactory.ApiClientStub.RegisterGetResponse("auth/users", expectedUsers); + _apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles); + _apiFactory.ApiClientStub.RegisterGetResponse("auth/permissions", expectedPermissions); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-permissions"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs new file mode 100644 index 00000000..9e28575c --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.ManageRoles; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +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; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.ManageRoles; + +/// +/// Contains security tests for the /{culture}/admin/manage-roles route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ManageRolesViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly PermissionDtoFixture _permissionDtoFixture = new(); + private readonly RoleDtoFixture _roleDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ManageRolesViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ManageRoles_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/manage-roles"); + + // 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 == "auth/roles"); + } + + [Fact] + public async Task ManageRoles_WhenCalledByNonAdminUser_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/admin/manage-roles"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task ManageRoles_WhenCalledByAdminUser_ShouldReturnRolesPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + RoleDto[] expectedRoles = [.. _roleDtoFixture.CreateMany()]; + PermissionDto[] expectedPermissions = [.. _permissionDtoFixture.CreateMany()]; + _apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles); + _apiFactory.ApiClientStub.RegisterGetResponse("auth/permissions", expectedPermissions); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-roles"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs new file mode 100644 index 00000000..298207ca --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DeleteTheme; +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.Text; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Themes.DeleteTheme; + +/// +/// Contains security tests for the /{culture}/admin/themes/api-delete-theme/{themeId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeleteThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DeleteTheme_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage deleteRequest = CreateDeleteRequest("test-theme"); + deleteRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == "themes/test-theme"); + } + + [Fact] + public async Task DeleteTheme_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = CreateDeleteRequest("test-theme"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == "themes/test-theme"); + } + + /// + /// Builds a DELETE request for the theme deletion route with the JSON content type required by the antiforgery validation. + /// + /// The manifest id of the theme to delete. + /// The configured DELETE request. + private static HttpRequestMessage CreateDeleteRequest(string themeId) + { + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/admin/themes/api-delete-theme/{themeId}") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return deleteRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs new file mode 100644 index 00000000..846c8c05 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DownloadTheme; +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; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Themes.DownloadTheme; + +/// +/// Contains security tests for the /{culture}/admin/themes/api-download-theme/{themeId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class DownloadThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DownloadThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DownloadTheme_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage downloadRequest = new(HttpMethod.Get, "/en-us/admin/themes/api-download-theme/test-theme"); + downloadRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await client.SendAsync(downloadRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs new file mode 100644 index 00000000..b50c4f80 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.GetThemes; +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; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Themes.GetThemes; + +/// +/// Contains security tests for the /{culture}/admin/themes/api-get-themes route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetThemesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetThemes_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/themes/api-get-themes"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await client.SendAsync(getRequest); + + // 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 == "themes"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs new file mode 100644 index 00000000..7e232089 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.InstallTheme; +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; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Themes.InstallTheme; + +/// +/// Contains security tests for the /{culture}/admin/themes/api-install-theme route served by the class. +/// +[ExcludeFromCodeCoverage] +public class InstallThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public InstallThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task InstallTheme_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage installRequest = new(HttpMethod.Post, "/en-us/admin/themes/api-install-theme") + { + Content = CreateMultipartContent("theme.zip") + }; + installRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(installRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "themes"); + } + + [Fact] + public async Task InstallTheme_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage installRequest = new(HttpMethod.Post, "/en-us/admin/themes/api-install-theme") + { + Content = CreateMultipartContent("theme.zip") + }; + installRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(installRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "themes"); + } + + /// + /// Builds a multipart form content carrying a single file part. + /// + /// The name of the uploaded file. + /// The multipart form content. + private static MultipartFormDataContent CreateMultipartContent(string fileName) + { + MultipartFormDataContent form = []; + ByteArrayContent fileContent = new([0x50, 0x4B, 0x03, 0x04]); + fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/zip"); + form.Add(fileContent, "archive", fileName); + return form; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs new file mode 100644 index 00000000..93238c02 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.RestoreTheme; +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.Text; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Themes.RestoreTheme; + +/// +/// Contains security tests for the /{culture}/admin/themes/api-restore-theme/{themeId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RestoreThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RestoreTheme_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage restoreRequest = CreateRestoreRequest("test-theme"); + restoreRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "themes/test-theme/restore"); + } + + [Fact] + public async Task RestoreTheme_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest("test-theme"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "themes/test-theme/restore"); + } + + /// + /// Builds a POST request for the theme restore route with the JSON content type required by the antiforgery validation. + /// + /// The manifest id of the bundled theme to restore. + /// The configured POST request. + private static HttpRequestMessage CreateRestoreRequest(string themeId) + { + HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/admin/themes/api-restore-theme/{themeId}") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return restoreRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs new file mode 100644 index 00000000..6d790938 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Themes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.SetCurrentTheme; +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.Admin.Themes.SetCurrentTheme; + +/// +/// Contains security tests for the /{culture}/admin/themes/api-set-current-theme route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SetCurrentThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SetCurrentTheme_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage setCurrentThemeRequest = CreateSetCurrentThemeRequest(); + setCurrentThemeRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(setCurrentThemeRequest); + + // 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 == "themes/current"); + } + + [Fact] + public async Task SetCurrentTheme_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage setCurrentThemeRequest = CreateSetCurrentThemeRequest(); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(setCurrentThemeRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "themes/current"); + } + + /// + /// Builds a PUT request for the set current theme route with the JSON content type required by the antiforgery validation. + /// + /// The configured PUT request. + private static HttpRequestMessage CreateSetCurrentThemeRequest() + { + HttpRequestMessage setCurrentThemeRequest = new(HttpMethod.Put, "/en-us/admin/themes/api-set-current-theme") + { + Content = JsonContent.Create(new SetCurrentThemeRequest("test-theme")) + }; + setCurrentThemeRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + setCurrentThemeRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return setCurrentThemeRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs new file mode 100644 index 00000000..bf2c0de5 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes; +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.Admin.Themes; + +/// +/// Contains security tests for the /{culture}/admin/manage-themes route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ThemesIndexViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ThemesIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ThemesIndex_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/manage-themes"); + + // 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 == "themes"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs new file mode 100644 index 00000000..4463b697 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserPermissions; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +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; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserPermissions; + +/// +/// Contains security tests for the /{culture}/admin/api-get-permissions-by-user-id/{userId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserPermissionsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly PermissionDtoFixture _permissionDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetUserPermissionsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetUserPermissions_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/api-get-permissions-by-user-id/" + Guid.NewGuid()); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("auth/login", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetUserPermissions_WhenCalledByNonAdminUser_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/admin/api-get-permissions-by-user-id/" + Guid.NewGuid()); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetUserPermissions_WhenCalledByAdminUser_ShouldReturnUserPermissionsData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + Guid userId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterGetResponse($"auth/users/{userId}/permissions", new PermissionDto[] { _permissionDtoFixture.Create() }); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-permissions-by-user-id/" + userId); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs new file mode 100644 index 00000000..ac609df2 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserRole; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +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; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserRole; + +/// +/// Contains security tests for the /{culture}/admin/api-get-role-by-user-id/{userId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserRoleEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly RoleDtoFixture _roleDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetUserRoleEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetUserRole_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/api-get-role-by-user-id/" + Guid.NewGuid()); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("auth/login", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetUserRole_WhenCalledByNonAdminUser_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/admin/api-get-role-by-user-id/" + Guid.NewGuid()); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetUserRole_WhenCalledByAdminUser_ShouldReturnUserRoleData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + Guid userId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterGetResponse($"auth/users/{userId}/role", _roleDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-role-by-user-id/" + userId); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs new file mode 100644 index 00000000..befdd67e --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs @@ -0,0 +1,137 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.UpdateUserRoleAndPermissions; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; +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; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.UsersManagement.Authorization.UpdateUserRoleAndPermissions; + +/// +/// Contains security tests for the /{culture}/admin/api-update-user-authorization route served by the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly UpdateUserRoleAndPermissionsRequestFixture _updateUserRoleAndPermissionsRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdateUserRoleAndPermissionsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateUserRoleAndPermissions_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-user-authorization") + { + Content = JsonContent.Create(_updateUserRoleAndPermissionsRequestFixture.Create()) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + 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.StartsWith("auth/users/", StringComparison.OrdinalIgnoreCase)); + } + + [Fact] + public async Task UpdateUserRoleAndPermissions_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-user-authorization") + { + Content = JsonContent.Create(_updateUserRoleAndPermissionsRequestFixture.Create()) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint.StartsWith("auth/users/", StringComparison.OrdinalIgnoreCase)); + } + + [Fact] + public async Task UpdateUserRoleAndPermissions_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-user-authorization") + { + Content = JsonContent.Create(_updateUserRoleAndPermissionsRequestFixture.Create()) + }; + 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); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Theory] + [InlineData("'; DROP TABLE Roles--")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateUserRoleAndPermissions_WithInjectionInRoleId_ShouldRemainSecure(string maliciousRoleId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + string jsonBody = $"{{\"userId\":\"{Guid.NewGuid()}\",\"roleId\":\"{maliciousRoleId}\",\"permissions\":[]}}"; + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-user-authorization") + { + Content = new StringContent(jsonBody, Encoding.UTF8, "application/json") + }; + 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 + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.Empty(_apiFactory.ApiClientStub.PutRequests); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs new file mode 100644 index 00000000..789cf711 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; +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; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; + +/// +/// Contains security tests for the /directories/api-get-directories route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoriesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetDirectoriesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetDirectories_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/directories/api-get-directories"); + + // 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.StartsWith("directories/get-directories", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("'; DROP TABLE Directories--")] // destructive SQL injection + [InlineData("' OR '1'='1")] // basic SQL injection + public async Task GetDirectories_WhenCalledWithInjectionInPath_ShouldRemainSecure(string maliciousPath) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedEndpoint = $"directories/get-directories?path={Uri.EscapeDataString(maliciousPath)}&includeHiddenElements=False"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/directories/api-get-directories?path={Uri.EscapeDataString(maliciousPath)}&includeHiddenElements=false"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs new file mode 100644 index 00000000..3f8b7848 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Drives.GetDrives; +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.FileSystemManagement.Drives.GetDrives; + +/// +/// Contains security tests for the /drives/api-get-drives route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetDrivesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetDrivesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetDrives_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/drives/api-get-drives"); + + // 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 == "drives/get-drives"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs new file mode 100644 index 00000000..3974eea3 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.FileSystem.GetType; +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.FileSystemManagement.FileSystem.GetType; + +/// +/// Contains security tests for the /file-system/api-get-type route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetTypeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetTypeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetType_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/file-system/api-get-type"); + + // 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 == "file-system/get-type"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs new file mode 100644 index 00000000..82d98650 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Files.GetFiles; +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; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Files.GetFiles; + +/// +/// Contains security tests for the /files/api-get-files route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetFilesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetFilesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetFiles_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/files/api-get-files"); + + // 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.StartsWith("files/get-files", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("'; DROP TABLE Files--")] // destructive SQL injection + [InlineData("' OR '1'='1")] // basic SQL injection + public async Task GetFiles_WhenCalledWithInjectionInPath_ShouldRemainSecure(string maliciousPath) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedEndpoint = $"files/get-files?path={Uri.EscapeDataString(maliciousPath)}&includeHiddenElements=False"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/files/api-get-files?path={Uri.EscapeDataString(maliciousPath)}&includeHiddenElements=false"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs new file mode 100644 index 00000000..fb4dbeaf --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles; +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.FileSystemManagement.Files.GetTreeFiles; + +/// +/// Contains security tests for the /files/api-get-tree-files route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetTreeFilesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetTreeFilesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetTreeFiles_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/files/api-get-tree-files"); + + // 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.StartsWith("files/get-tree-files", StringComparison.Ordinal)); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs new file mode 100644 index 00000000..a4d3b46a --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.CheckPathExists; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Path.CheckPathExists; + +/// +/// Contains security tests for the /path/api-check-path-exists route served by the class. +/// +[ExcludeFromCodeCoverage] +public class CheckPathExistsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PathExistsDtoFixture _pathExistsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public CheckPathExistsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task CheckPathExists_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/path/api-check-path-exists"); + + // 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.StartsWith("path/check-path-exists", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("'; DROP TABLE Paths--")] // destructive SQL injection + [InlineData("' OR '1'='1")] // basic SQL injection + public async Task CheckPathExists_WhenCalledWithInjectionInPath_ShouldRemainSecure(string maliciousPath) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedEndpoint = $"path/check-path-exists?path={Uri.EscapeDataString(maliciousPath)}&includeHiddenElements=False"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _pathExistsDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-check-path-exists?path={Uri.EscapeDataString(maliciousPath)}&includeHiddenElements=false"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs new file mode 100644 index 00000000..9b24a184 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathParent; +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; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Path.GetPathParent; + +/// +/// Contains security tests for the /path/api-get-path-parent route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathParentEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPathParentEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetPathParent_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/path/api-get-path-parent"); + + // 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.StartsWith("path/get-path-parent", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("'; DROP TABLE Paths--")] // destructive SQL injection + [InlineData("' OR '1'='1")] // basic SQL injection + public async Task GetPathParent_WhenCalledWithInjectionInPath_ShouldRemainSecure(string maliciousPath) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedEndpoint = $"path/get-path-parent?path={Uri.EscapeDataString(maliciousPath)}"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-get-path-parent?path={Uri.EscapeDataString(maliciousPath)}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs new file mode 100644 index 00000000..772f7cdc --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathRoot; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Path.GetPathRoot; + +/// +/// Contains security tests for the /path/api-get-path-root route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathRootEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PathSegmentDtoFixture _pathSegmentDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPathRootEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetPathRoot_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/path/api-get-path-root"); + + // 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.StartsWith("path/get-path-root", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("'; DROP TABLE Paths--")] // destructive SQL injection + [InlineData("' OR '1'='1")] // basic SQL injection + public async Task GetPathRoot_WhenCalledWithInjectionInPath_ShouldRemainSecure(string maliciousPath) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedEndpoint = $"path/get-path-root?path={Uri.EscapeDataString(maliciousPath)}"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _pathSegmentDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-get-path-root?path={Uri.EscapeDataString(maliciousPath)}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs new file mode 100644 index 00000000..6a7666c1 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator; +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.FileSystemManagement.Path.GetPathSeparator; + +/// +/// Contains security tests for the /path/api-get-path-separator route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathSeparatorEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPathSeparatorEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetPathSeparator_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/path/api-get-path-separator"); + + // 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 == "path/get-path-separator"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs new file mode 100644 index 00000000..cd358c66 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.SplitPath; +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; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Path.SplitPath; + +/// +/// Contains security tests for the /path/api-split route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SplitPathEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SplitPathEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SplitPath_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/path/api-split"); + + // 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.StartsWith("path/split", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("'; DROP TABLE Paths--")] // destructive SQL injection + [InlineData("' OR '1'='1")] // basic SQL injection + public async Task SplitPath_WhenCalledWithInjectionInPath_ShouldRemainSecure(string maliciousPath) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedEndpoint = $"path/split?path={Uri.EscapeDataString(maliciousPath)}"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-split?path={Uri.EscapeDataString(maliciousPath)}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs new file mode 100644 index 00000000..19a5fb43 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.ValidatePath; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Path.ValidatePath; + +/// +/// Contains security tests for the /path/api-validate route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ValidatePathEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PathValidDtoFixture _pathValidDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ValidatePathEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ValidatePath_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/path/api-validate"); + + // 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.StartsWith("path/validate", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("'; DROP TABLE Paths--")] // destructive SQL injection + [InlineData("' OR '1'='1")] // basic SQL injection + public async Task ValidatePath_WhenCalledWithInjectionInPath_ShouldRemainSecure(string maliciousPath) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedEndpoint = $"path/validate?path={Uri.EscapeDataString(maliciousPath)}"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _pathValidDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-validate?path={Uri.EscapeDataString(maliciousPath)}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs new file mode 100644 index 00000000..c26abcbd --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Home; +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.Home; + +/// +/// Contains security tests for the /{culture}/error route served by the class. +/// +[ExcludeFromCodeCoverage] +public class HomeErrorEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public HomeErrorEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task HomeError_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/error"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs new file mode 100644 index 00000000..c5e19386 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Home; +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.Home; + +/// +/// Contains security tests for the /{culture} and / routes served by the class. +/// +[ExcludeFromCodeCoverage] +public class HomeIndexEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public HomeIndexEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task Home_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us"); + + // Assert + // the home page requires authentication, so an anonymous request must be redirected to the login page + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("Exception", content, System.StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task Home_WhenCalledWithoutCulture_ShouldRedirectToDefaultCulture() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/"); + + // Assert + // the culture-less root must never demand authentication or leak internals, only redirect to the default culture + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("/en-us/", response.Headers.Location!.ToString()); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("Exception", content, System.StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs new file mode 100644 index 00000000..53c25060 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Home; +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.Home; + +/// +/// Contains security tests for the /{culture}/not-found route served by the class. +/// +[ExcludeFromCodeCoverage] +public class HomeNotFoundViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public HomeNotFoundViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task HomeNotFoundView_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/not-found"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs new file mode 100644 index 00000000..46954637 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Home; +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.Home; + +/// +/// Contains security tests for the /{culture}/privacy route served by the class. +/// +[ExcludeFromCodeCoverage] +public class HomePrivacyEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public HomePrivacyEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task HomePrivacy_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/privacy"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} 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 new file mode 100644 index 00000000..2779c0fd --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.AddLibrary; +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.AddLibrary; + +/// +/// Contains security tests for the /{culture}/libraries/manage/item route served by the class. +/// +[ExcludeFromCodeCoverage] +public class AddLibraryViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AddLibraryViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task AddLibraryView_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage/item"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs new file mode 100644 index 00000000..15f4ce80 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.CancelLibrariesScan; +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.Text; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.CancelLibrariesScan; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-cancel-libraries-scan route served by the class. +/// +[ExcludeFromCodeCoverage] +public class CancelLibrariesScanEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public CancelLibrariesScanEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task CancelLibrariesScan_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage cancelRequest = CreateCancelRequest(); + cancelRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(cancelRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries/scans/cancel"); + } + + [Fact] + public async Task CancelLibrariesScan_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage cancelRequest = CreateCancelRequest(); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(cancelRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries/scans/cancel"); + } + + /// + /// Builds the cancel request that posts an empty JSON body to the cancel libraries scan endpoint. + /// + /// The configured cancel request. + private static HttpRequestMessage CreateCancelRequest() + { + HttpRequestMessage cancelRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-cancel-libraries-scan") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + cancelRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + cancelRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return cancelRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs new file mode 100644 index 00000000..41ee3f42 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.CancelLibraryScan; +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.Text; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.CancelLibraryScan; + +/// +/// Contains security tests for the /{culture}/libraries/manage/{{libraryId}}/api-cancel-library-scan/{{scanId}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class CancelLibraryScanEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public CancelLibraryScanEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task CancelLibraryScan_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + Guid libraryId = Guid.NewGuid(); + Guid scanId = Guid.NewGuid(); + HttpRequestMessage cancelRequest = CreateCancelRequest($"/en-us/libraries/manage/{libraryId}/api-cancel-library-scan/{scanId}"); + cancelRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(cancelRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == $"libraries/{libraryId}/scans/{scanId}/cancel"); + } + + [Fact] + public async Task CancelLibraryScan_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + Guid libraryId = Guid.NewGuid(); + Guid scanId = Guid.NewGuid(); + HttpRequestMessage cancelRequest = CreateCancelRequest($"/en-us/libraries/manage/{libraryId}/api-cancel-library-scan/{scanId}"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(cancelRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == $"libraries/{libraryId}/scans/{scanId}/cancel"); + } + + /// + /// Builds the cancel request that posts an empty JSON body to the given . + /// + /// The URL of the cancel endpoint. + /// The configured cancel request. + private static HttpRequestMessage CreateCancelRequest(string url) + { + HttpRequestMessage cancelRequest = new(HttpMethod.Post, url) + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + cancelRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + cancelRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return cancelRequest; + } +} 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 new file mode 100644 index 00000000..7222c593 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.EditLibrary; +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.EditLibrary; + +/// +/// Contains security tests for the /{culture}/libraries/manage/item/{{id}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class EditLibraryViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public EditLibraryViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task EditLibraryView_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + Guid libraryId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await client.GetAsync($"/en-us/libraries/manage/item/{libraryId}"); + + // 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 == $"libraries/{libraryId}"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs new file mode 100644 index 00000000..5fbcb785 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetEnabledLibraries; +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; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetEnabledLibraries; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-get-enabled-libraries route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetEnabledLibrariesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetEnabledLibrariesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetEnabledLibraries_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/libraries/manage/api-get-enabled-libraries"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await client.SendAsync(getRequest); + + // 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 == "libraries/enabled"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs new file mode 100644 index 00000000..e79104e2 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraries; +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; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetLibraries; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-get-libraries route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibrariesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibrariesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraries_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/libraries/manage/api-get-libraries"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await client.SendAsync(getRequest); + + // 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 == "libraries"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..3092267b --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetMetadataProviders; +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; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetMetadataProviders; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-get-metadata-providers/{{libraryId}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetMetadataProvidersEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetMetadataProvidersEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetMetadataProviders_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + Guid libraryId = Guid.NewGuid(); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-metadata-providers/{libraryId}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await client.SendAsync(getRequest); + + // 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 == $"libraries/{libraryId}/metadata-providers"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs new file mode 100644 index 00000000..06a1dc01 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetRunningLibraryScans; +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; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetRunningLibraryScans; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-get-running-library-scans route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetRunningLibraryScansEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetRunningLibraryScansEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetRunningLibraryScans_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/libraries/manage/api-get-running-library-scans"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await client.SendAsync(getRequest); + + // 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 == "libraries/scans/running"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs new file mode 100644 index 00000000..c176096d --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.Index; +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.Index; + +/// +/// Contains security tests for the /{culture}/libraries/manage route served by the class. +/// +[ExcludeFromCodeCoverage] +public class LibrariesIndexViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public LibrariesIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task LibrariesIndexView_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} 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 new file mode 100644 index 00000000..c4f3a860 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs @@ -0,0 +1,89 @@ +#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 /{culture}/libraries/manage/api-reorder-metadata-providers route served by 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/ScanLibraries/ScanLibrariesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs new file mode 100644 index 00000000..f2704f51 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ScanLibraries; +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.Text; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.ScanLibraries; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-scan-libraries route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ScanLibrariesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ScanLibrariesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ScanLibraries_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage scanRequest = CreateScanRequest(); + scanRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(scanRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries/scans"); + } + + [Fact] + public async Task ScanLibraries_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage scanRequest = CreateScanRequest(); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(scanRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries/scans"); + } + + /// + /// Builds the scan request that posts an empty JSON body to the scan libraries endpoint. + /// + /// The configured scan request. + private static HttpRequestMessage CreateScanRequest() + { + HttpRequestMessage scanRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-scan-libraries") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + scanRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + scanRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return scanRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs new file mode 100644 index 00000000..5bbbfeb5 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ScanLibrary; +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.Text; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.ScanLibrary; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-scan-library/{{id}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ScanLibraryEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ScanLibraryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ScanLibrary_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + Guid libraryId = Guid.NewGuid(); + HttpRequestMessage scanRequest = CreateScanRequest($"/en-us/libraries/manage/api-scan-library/{libraryId}"); + scanRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(scanRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == $"libraries/{libraryId}/scans"); + } + + [Fact] + public async Task ScanLibrary_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + Guid libraryId = Guid.NewGuid(); + HttpRequestMessage scanRequest = CreateScanRequest($"/en-us/libraries/manage/api-scan-library/{libraryId}"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(scanRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == $"libraries/{libraryId}/scans"); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Libraries--")] // destructive injection + public async Task ScanLibrary_WithInjectionInId_ShouldNotLeakOrError(string maliciousId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage scanRequest = CreateScanRequest($"/en-us/libraries/manage/api-scan-library/{Uri.EscapeDataString(maliciousId)}"); + scanRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(scanRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // note: the {id} route parameter is Guid-typed, so the malicious value fails model binding and never reaches + // the handler; the Web application reports the binding failure as a 200 response carrying success=false + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint.StartsWith("libraries/", StringComparison.Ordinal)); + } + + /// + /// Builds the scan request that posts an empty JSON body to the given . + /// + /// The URL of the scan endpoint. + /// The configured scan request. + private static HttpRequestMessage CreateScanRequest(string url) + { + HttpRequestMessage scanRequest = new(HttpMethod.Post, url) + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + scanRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + scanRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return scanRequest; + } +} 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 new file mode 100644 index 00000000..a328ed61 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs @@ -0,0 +1,93 @@ +#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 /{culture}/libraries/manage/api-set-metadata-provider-enabled route served by 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/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs new file mode 100644 index 00000000..333c37f5 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.EditBook; +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.WrittenContentLibrary.BookLibrary.Books.EditBook; + +/// +/// Contains security tests for the /{culture}/library/written-content-library/books-library/books/{{id}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class EditBookViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public EditBookViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task EditBook_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync($"/en-us/library/written-content-library/books-library/books/{Guid.NewGuid()}"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs new file mode 100644 index 00000000..762ab1e0 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +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; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems; + +/// +/// Contains security tests for the /{culture}/library/written-content-library/books-library/books/api-get-library-items route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryItemsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PaginatedBookLiteDtoFixture _paginatedBookLiteDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibraryItemsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraryItems_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync($"/en-us/library/written-content-library/books-library/books/api-get-library-items?libraryId={Guid.NewGuid()}"); + + // 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.StartsWith("books/lite", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("'; DROP TABLE Books--")] // destructive SQL injection + [InlineData("' OR '1'='1")] // basic SQL injection + public async Task GetLibraryItems_WhenCalledWithInjectionInSearchTerm_ShouldRemainSecure(string maliciousSearchTerm) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + string expectedEndpoint = $"books/lite?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}&shouldIgnoreThePrefixForAlphaPicker=False"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _paginatedBookLiteDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/api-get-library-items?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}&shouldIgnoreThePrefixForAlphaPicker=false"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs new file mode 100644 index 00000000..4784adfb --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index; +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.WrittenContentLibrary.BookLibrary.Books.Index; + +/// +/// Contains security tests for the /{culture}/library/written-content-library/books-library/books route served by the class. +/// +[ExcludeFromCodeCoverage] +public class BooksIndexViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public BooksIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task BooksIndex_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync($"/en-us/library/written-content-library/books-library/books?libraryId={Guid.NewGuid()}"); + + // 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.StartsWith("libraries/", StringComparison.Ordinal)); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs new file mode 100644 index 00000000..e2e0c6d1 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPluginSettings; +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.Text.Json; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.GetPluginSettings; + +/// +/// Contains security tests for the /{culture}/admin/manage-plugins/api-get-plugin-settings/{pluginId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetPluginSettingsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPluginSettingsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetPluginSettings_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + Guid pluginId = Guid.NewGuid(); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/admin/manage-plugins/api-get-plugin-settings/{pluginId}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await client.SendAsync(getRequest); + + // 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 == $"plugins/{pluginId}/settings"); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Plugins--")] // destructive injection + public async Task GetPluginSettings_WithInjectionInPluginId_ShouldNotLeakOrError(string maliciousPluginId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/admin/manage-plugins/api-get-plugin-settings/{Uri.EscapeDataString(maliciousPluginId)}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // note: the {pluginId} route parameter is Guid-typed, so the malicious value fails model binding and never + // reaches the handler; the Web application reports the binding failure as a 200 response carrying success=false + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("plugins/", StringComparison.Ordinal)); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs new file mode 100644 index 00000000..bd107f1b --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Plugins.Index; +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.Plugins.Index; + +/// +/// Contains security tests for the /{culture}/admin/manage-plugins route served by the class. +/// +[ExcludeFromCodeCoverage] +public class PluginsIndexViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public PluginsIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task PluginsIndex_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/manage-plugins"); + + // 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 == "plugins"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs new file mode 100644 index 00000000..c79c35ba --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Themes.ThemeAssets; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Themes.ThemeAssets; + +/// +/// Contains security tests for the /theme-assets/{themeId}/{path} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeAssetsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly BlobDataDtoFixture _blobDataDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ThemeAssetsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ThemeAssets_WhenCalledWithoutAuthentication_ShouldServeAsset() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + byte[] expectedBytes = [0x89, 0x50, 0x4E, 0x47]; + _apiFactory.ApiClientStub.RegisterBlobResponse(_blobDataDtoFixture.Create(data: expectedBytes, contentType: "image/png")); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/theme-assets/test-theme/assets/logo.png"); + byte[] content = await response.Content.ReadAsByteArrayAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("image/png", response.Content.Headers.ContentType!.MediaType); + Assert.Equal(expectedBytes, content); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Themes--")] // destructive injection + public async Task ThemeAssets_WithInjectionInThemeId_ShouldNotLeakOrError(string maliciousThemeId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterBlobResponse(_blobDataDtoFixture.Create(data: [0x01], contentType: "application/octet-stream")); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync($"/theme-assets/{Uri.EscapeDataString(maliciousThemeId)}/assets/logo.png"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("..\\..\\appsettings.json")] // path traversal + public async Task ThemeAssets_WithInjectionInPath_ShouldNotLeakOrError(string maliciousPath) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterBlobResponse(_blobDataDtoFixture.Create(data: [0x01], contentType: "application/octet-stream")); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync($"/theme-assets/test-theme/assets/{Uri.EscapeDataString(maliciousPath)}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs new file mode 100644 index 00000000..00d4459d --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Tools.Language.SetLanguage; +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.Tools.Language.SetLanguage; + +/// +/// Contains security tests for the /{culture}/tools/language/set-language route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SetLanguageEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SetLanguageEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SetLanguage_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/tools/language/set-language?newCulture=de-DE"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs new file mode 100644 index 00000000..7947bd26 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.AccessDenied; +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.UsersManagement.Authentication.AccessDenied; + +/// +/// Contains security tests for the /{culture}/auth/access-denied route served by the class. +/// +[ExcludeFromCodeCoverage] +public class AccessDeniedViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AccessDeniedViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task AccessDeniedView_WhenCalledWithoutAuthentication_ShouldRenderAccessDeniedPage() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/access-denied"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs new file mode 100644 index 00000000..40e78d53 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs @@ -0,0 +1,154 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.ChangePassword; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; +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; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.ChangePassword; + +/// +/// Contains security tests for the /{culture}/auth/api-change-password route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ChangePasswordRequestFixture _changePasswordRequestFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ChangePasswordEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ChangePassword_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + ChangePasswordRequest request = _changePasswordRequestFixture.Create(); + HttpRequestMessage changePasswordRequest = new(HttpMethod.Post, "/en-us/auth/api-change-password") + { + Content = JsonContent.Create(request) + }; + changePasswordRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + changePasswordRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + changePasswordRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(changePasswordRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "auth/change-password"); + } + + [Fact] + public async Task ChangePassword_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + ChangePasswordRequest request = _changePasswordRequestFixture.Create(); + HttpRequestMessage changePasswordRequest = new(HttpMethod.Post, "/en-us/auth/api-change-password") + { + Content = JsonContent.Create(request) + }; + changePasswordRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + changePasswordRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(changePasswordRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "auth/change-password"); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("admin'--")] // comment injection + [InlineData("' UNION SELECT * FROM Users--")] // union injection + [InlineData("'; DROP TABLE Users--")] // destructive injection + [InlineData("{{7*7}}")] // template injection + public async Task ChangePassword_WithInjectionAttemptInNewPassword_ShouldRemainSecure(string maliciousNewPassword) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostException("auth/change-password", new ApiException(_problemDetailsDtoFixture.Create(title: "General.Failure", detail: "OperationFailed"), HttpStatusCode.Forbidden, "auth/change-password")); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + ChangePasswordRequest request = _changePasswordRequestFixture.Create(currentPassword: "OldPass123!", newPassword: maliciousNewPassword, newPasswordConfirm: maliciousNewPassword); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(CreateChangePasswordRequest(request, webClient.AntiforgeryToken)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.DoesNotContain("SQL", content); + Assert.DoesNotContain("Exception", 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); + } + + [Fact] + public async Task ChangePassword_WhenApiReturnsError_ShouldReturnCleanError() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostException("auth/change-password", new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Failure", detail: "OperationFailed"), + HttpStatusCode.Conflict)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + ChangePasswordRequest request = _changePasswordRequestFixture.Create(); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(CreateChangePasswordRequest(request, webClient.AntiforgeryToken)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Builds the change password request that sends the given to the change password endpoint. + /// + /// The change password request to send. + /// The antiforgery token to include in the request. + /// The configured change password request. + private static HttpRequestMessage CreateChangePasswordRequest(ChangePasswordRequest request, string antiforgeryToken) + { + HttpRequestMessage changePasswordRequest = new(HttpMethod.Post, "/en-us/auth/api-change-password") + { + Content = JsonContent.Create(request) + }; + changePasswordRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + changePasswordRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + changePasswordRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return changePasswordRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs new file mode 100644 index 00000000..23bd174c --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.ChangePassword; +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.UsersManagement.Authentication.ChangePassword; + +/// +/// Contains security tests for the /{culture}/auth/change-password route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ChangePasswordViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ChangePasswordView_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/change-password"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs new file mode 100644 index 00000000..300c5e01 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login; +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.UsersManagement.Authentication.Login; + +/// +/// Contains security tests for the /{culture}/auth/login/{returnUrl?} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class LoginViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public LoginViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task LoginView_WhenCalledWithoutAuthentication_ShouldRenderLoginPage() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/login"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("login-form", content); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs new file mode 100644 index 00000000..7e0374f8 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Logout; +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.UsersManagement.Authentication.Logout; + +/// +/// Contains security tests for the /{culture}/auth/logout route served by the class. +/// +[ExcludeFromCodeCoverage] +public class LogoutEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public LogoutEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task Logout_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/logout"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs new file mode 100644 index 00000000..4a26f5b3 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs @@ -0,0 +1,130 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; +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; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; + +/// +/// Contains security tests for the /{culture}/auth/api-recover-password route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RecoverPasswordEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("admin'--")] // comment injection + [InlineData("' UNION SELECT * FROM Users--")] // union injection + [InlineData("'; DROP TABLE Users--")] // destructive injection + [InlineData("{{7*7}}")] // template injection + public async Task RecoverPassword_WithInjectionAttemptInUsername_ShouldRemainSecure(string maliciousUsername) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostException("auth/recover-password", new ApiException(_problemDetailsDtoFixture.Create(title: "General.Failure", detail: "RecoveryFailed"), HttpStatusCode.Forbidden, "auth/recover-password")); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(username: maliciousUsername, totpCode: "123456"); + + // Act + HttpResponseMessage response = await client.SendAsync(CreateRecoverPasswordRequest(request, antiforgeryToken)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.DoesNotContain("SQL", content); + Assert.DoesNotContain("Exception", 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); + } + + [Fact] + public async Task RecoverPassword_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(username: "testuser", totpCode: "123456"); + HttpRequestMessage recoverPasswordRequest = new(HttpMethod.Post, "/en-us/auth/api-recover-password") + { + Content = JsonContent.Create(request) + }; + recoverPasswordRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + + // Act + HttpResponseMessage response = await client.SendAsync(recoverPasswordRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "auth/recover-password"); + } + + [Fact] + public async Task RecoverPassword_WhenApiReturnsError_ShouldReturnCleanError() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostException("auth/recover-password", new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Failure", detail: "RecoveryFailed"), + HttpStatusCode.Conflict)); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(username: "testuser", totpCode: "123456"); + + // Act + HttpResponseMessage response = await client.SendAsync(CreateRecoverPasswordRequest(request, antiforgeryToken)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Builds the recover password request that sends the given to the recover password endpoint. + /// + /// The recover password request to send. + /// The antiforgery token to include in the request. + /// The configured recover password request. + private static HttpRequestMessage CreateRecoverPasswordRequest(RecoverPasswordRequest request, string antiforgeryToken) + { + HttpRequestMessage recoverPasswordRequest = new(HttpMethod.Post, "/en-us/auth/api-recover-password") + { + Content = JsonContent.Create(request) + }; + recoverPasswordRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + recoverPasswordRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + recoverPasswordRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return recoverPasswordRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs new file mode 100644 index 00000000..8f2cbdd7 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; +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.UsersManagement.Authentication.RecoverPassword; + +/// +/// Contains security tests for the /{culture}/auth/recover-password route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RecoverPasswordViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RecoverPasswordView_WhenCalledWithoutAuthentication_ShouldRenderRecoverPasswordPage() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/recover-password"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs new file mode 100644 index 00000000..85a1546a --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs @@ -0,0 +1,130 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Register; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; +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; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.Register; + +/// +/// Contains security tests for the /{culture}/auth/api-register route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly RegisterRequestFixture _registerRequestFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RegisterEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("admin'--")] // comment injection + [InlineData("' UNION SELECT * FROM Users--")] // union injection + [InlineData("'; DROP TABLE Users--")] // destructive injection + [InlineData("{{7*7}}")] // template injection + public async Task Register_WithInjectionAttemptInUsername_ShouldRemainSecure(string maliciousUsername) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostException("auth/register", new ApiException(_problemDetailsDtoFixture.Create(title: "General.Failure", detail: "RegistrationFailed"), HttpStatusCode.Forbidden, "auth/register")); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + RegisterRequest request = _registerRequestFixture.Create(username: maliciousUsername, password: "Abcd123$", passwordConfirm: "Abcd123$"); + + // Act + HttpResponseMessage response = await client.SendAsync(CreateRegisterRequest(request, antiforgeryToken)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.DoesNotContain("SQL", content); + Assert.DoesNotContain("Exception", 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); + } + + [Fact] + public async Task Register_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + RegisterRequest request = _registerRequestFixture.Create(username: "newuser", password: "Abcd123$", passwordConfirm: "Abcd123$"); + HttpRequestMessage registerRequest = new(HttpMethod.Post, "/en-us/auth/api-register") + { + Content = JsonContent.Create(request) + }; + registerRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + + // Act + HttpResponseMessage response = await client.SendAsync(registerRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "auth/register"); + } + + [Fact] + public async Task Register_WhenApiReturnsError_ShouldReturnCleanError() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostException("auth/register", new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Failure", detail: "RegistrationFailed"), + HttpStatusCode.Conflict)); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + RegisterRequest request = _registerRequestFixture.Create(username: "newuser", password: "Abcd123$", passwordConfirm: "Abcd123$"); + + // Act + HttpResponseMessage response = await client.SendAsync(CreateRegisterRequest(request, antiforgeryToken)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Builds the register request that sends the given to the register endpoint. + /// + /// The register request to send. + /// The antiforgery token to include in the request. + /// The configured register request. + private static HttpRequestMessage CreateRegisterRequest(RegisterRequest request, string antiforgeryToken) + { + HttpRequestMessage registerRequest = new(HttpMethod.Post, "/en-us/auth/api-register") + { + Content = JsonContent.Create(request) + }; + registerRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + registerRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + registerRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return registerRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs new file mode 100644 index 00000000..6f18a19f --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Register; +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.UsersManagement.Authentication.Register; + +/// +/// Contains security tests for the /{culture}/auth/register route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RegisterViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RegisterView_WhenCalledWithoutAuthentication_ShouldRenderRegisterPage() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/register"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +}