diff --git a/docs/technical/requests/library/audio-library/music-library/albums/UpdateAlbumCover.http b/docs/technical/requests/library/audio-library/music-library/albums/UpdateAlbumCover.http
new file mode 100644
index 00000000..147a43cf
--- /dev/null
+++ b/docs/technical/requests/library/audio-library/music-library/albums/UpdateAlbumCover.http
@@ -0,0 +1,10 @@
+PUT {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/{{$guid}}/cover
+Authorization: Bearer {{ACCESS_TOKEN}}
+Content-Type: multipart/form-data; boundary=LuminaBoundary
+
+--LuminaBoundary
+Content-Disposition: form-data; name="cover"; filename="cover.jpg"
+Content-Type: image/jpeg
+
+< ./cover.jpg
+--LuminaBoundary--
diff --git a/docs/technical/requests/library/audio-library/music-library/artists/UpdateArtistCover.http b/docs/technical/requests/library/audio-library/music-library/artists/UpdateArtistCover.http
new file mode 100644
index 00000000..a83a3218
--- /dev/null
+++ b/docs/technical/requests/library/audio-library/music-library/artists/UpdateArtistCover.http
@@ -0,0 +1,10 @@
+PUT {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{{$guid}}/cover
+Authorization: Bearer {{ACCESS_TOKEN}}
+Content-Type: multipart/form-data; boundary=LuminaBoundary
+
+--LuminaBoundary
+Content-Disposition: form-data; name="cover"; filename="cover.jpg"
+Content-Type: image/jpeg
+
+< ./cover.jpg
+--LuminaBoundary--
diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommand.cs
new file mode 100644
index 00000000..69f8d7da
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommand.cs
@@ -0,0 +1,24 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System.Diagnostics;
+using System.IO;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
+
+///
+/// Command for updating the cover image of an existing album.
+///
+/// The unique identifier of the media library the album belongs to, taken from the route.
+/// The unique identifier of the artist the album belongs to, taken from the route.
+/// The unique identifier of the album whose cover image is updated, taken from the route.
+/// The stream of the uploaded cover image file.
+/// The name of the uploaded cover image file.
+[DebuggerDisplay("AlbumId: {AlbumId} FileName: {FileName}")]
+public record UpdateAlbumCoverCommand(
+ string? LibraryId,
+ string? ArtistId,
+ string? AlbumId,
+ Stream? Cover,
+ string? FileName
+) : ICommand;
diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandler.cs
new file mode 100644
index 00000000..cc24503b
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandler.cs
@@ -0,0 +1,198 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
+using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
+
+///
+/// Handler for the command to update the cover image of an existing album.
+///
+public class UpdateAlbumCoverCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IMusicArtworkService _musicArtworkService;
+ private readonly IPathService _pathService;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected service for storing the artwork of a music library item.
+ /// Injected service for handling file system paths.
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected validator for application validation rules.
+ public UpdateAlbumCoverCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkService musicArtworkService, IPathService pathService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _musicArtworkService = musicArtworkService;
+ _pathService = pathService;
+ _authorizationService = authorizationService;
+ _currentUserService = currentUserService;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to update the cover image of an existing album.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the response carrying the relative path of the stored cover image, or an error message.
+ ///
+ public async Task> HandleAsync(UpdateAlbumCoverCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // The validator guarantees that the route identifiers are non-empty Guids before this point.
+ Guid libraryId = Guid.Parse(command.LibraryId!);
+ Guid artistId = Guid.Parse(command.ArtistId!);
+ Guid albumId = Guid.Parse(command.AlbumId!);
+
+ Result getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
+ if (getAlbumResult.IsFailure)
+ return getAlbumResult.Errors;
+ if (getAlbumResult.Value is null)
+ return DomainErrors.Music.AlbumNotFound;
+ AlbumEntity existingAlbum = getAlbumResult.Value;
+
+ // Resource scoping: the album must belong to the library and the artist named by the route, so that an album can never be edited through
+ // another library's or artist's route; the mismatch is reported as not found, without disclosing that the album exists elsewhere.
+ if (existingAlbum.LibraryId != libraryId || existingAlbum.ArtistId != artistId)
+ return DomainErrors.Music.AlbumNotFound;
+
+ // Admins can update the albums of all libraries; for everyone else, only the albums of the libraries they own.
+ bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync(
+ userId, new LibraryOwnershipPolicyContext(existingAlbum.LibraryId), cancellationToken).ConfigureAwait(false);
+ if (!canAccessLibrary)
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // The artwork is stored under the library and artist segments, so their names are resolved to keep the location consistent with the scanned artwork.
+ Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(existingAlbum.LibraryId, cancellationToken: cancellationToken).ConfigureAwait(false);
+ if (getLibraryResult.IsFailure)
+ return getLibraryResult.Errors;
+ if (getLibraryResult.Value is null)
+ return DomainErrors.Library.LibraryNotFound;
+ string libraryName = getLibraryResult.Value.Title;
+
+ Result getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(existingAlbum.ArtistId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
+ if (getArtistResult.IsFailure)
+ return getArtistResult.Errors;
+ string artistName = getArtistResult.Value?.Name ?? string.Empty;
+
+ // The artwork of the album is stored under the directory of its release type, mirroring the structure of the scanned files, so that a
+ // re-uploaded cover replaces the cover stored for the album at its standardized location instead of writing a second copy elsewhere.
+ Result> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Album, albumId, cancellationToken).ConfigureAwait(false);
+ if (getArtworkResult.IsFailure)
+ return getArtworkResult.Errors;
+ string? existingCoverPath = getArtworkResult.Value
+ .Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
+ .Select(artwork => artwork.FileName)
+ .FirstOrDefault();
+ string? releaseTypeName = ExtractReleaseTypeDirectoryName(existingCoverPath, artistName)
+ ?? (existingAlbum.ReleaseTypes.Count > 0 ? existingAlbum.ReleaseTypes[0].ReleaseType.ToString() : null);
+
+ Result storeArtworkResult = await _musicArtworkService.SaveAlbumArtworkAsync(
+ existingAlbum.LibraryId,
+ existingAlbum.Id,
+ libraryName,
+ artistName,
+ existingAlbum.Title,
+ command.Cover!,
+ command.FileName!,
+ releaseTypeName,
+ cancellationToken).ConfigureAwait(false);
+ if (storeArtworkResult.IsFailure)
+ return storeArtworkResult.Errors;
+
+ // The stored cover of the album is replaced as a whole: when the new cover is stored under a different name than the previous one
+ // (for example a png replacing a jpg), the previous file is removed, so that no orphaned artwork is left on disk without a reference.
+ if (!string.IsNullOrWhiteSpace(existingCoverPath) && existingCoverPath != storeArtworkResult.Value)
+ {
+ Result deleteResult = _musicArtworkService.DeleteStoredArtwork(existingCoverPath);
+ if (deleteResult.IsFailure)
+ return deleteResult.Errors;
+ }
+
+ // Map the newly stored cover image onto the artwork of the album, replacing the existing cover or adding a new one.
+ Result upsertResult = await _unitOfWork.MusicArtworkRepository.UpsertCoverAsync(
+ MusicArtworkOwnerType.Album, albumId, storeArtworkResult.Value, cancellationToken).ConfigureAwait(false);
+ if (upsertResult.IsFailure)
+ return upsertResult.Errors;
+
+ Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+ if (saveChangesResult.IsFailure)
+ return saveChangesResult.Errors;
+
+ return new UpdateAlbumCoverResponse(storeArtworkResult.Value);
+ }
+
+ ///
+ /// Resolves the name of the release type directory the artwork of an album is stored under, from the relative path of its existing cover.
+ ///
+ /// The relative path of the existing cover image of the album, or when the album has no cover.
+ /// The name of the artist of the album.
+ /// The name of the on-disk release type directory, or when the album does not use one.
+ private string? ExtractReleaseTypeDirectoryName(string? coverRelativePath, string artistName)
+ {
+ if (string.IsNullOrWhiteSpace(coverRelativePath))
+ return null;
+ // The path is media/music/{library}/{artist}[/{releaseType}]/{album}/{file}, so the segment right before the album directory is the release
+ // type directory when the album uses one, and the artist directory otherwise. An artist whose name happens to match a release type, like
+ // "Live", must not be mistaken for one, so the segment is only accepted as a release type when it is not the directory of the artist.
+ string[] segments = coverRelativePath.Split(_pathService.PathSeparator, StringSplitOptions.RemoveEmptyEntries);
+ if (segments.Length < 3)
+ return null;
+ string candidate = segments[^3];
+ if (IsArtistDirectory(candidate, artistName))
+ return null;
+ return Enum.TryParse(candidate, ignoreCase: true, out MusicReleaseType releaseType) && Enum.IsDefined(releaseType) ? candidate : null;
+ }
+
+ ///
+ /// Checks whether the provided path segment is the artwork directory of the artist of the album.
+ ///
+ /// The path segment to be checked.
+ /// The name of the artist of the album.
+ /// when the segment is the artwork directory of the artist, otherwise.
+ private bool IsArtistDirectory(string pathSegment, string artistName)
+ {
+ if (string.IsNullOrWhiteSpace(artistName))
+ return false;
+ Result artistSegmentResult = _pathService.SanitizeSegment(artistName);
+ return artistSegmentResult.IsSuccess
+ && string.Equals(pathSegment, artistSegmentResult.Value.Name, StringComparison.OrdinalIgnoreCase);
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandValidator.cs
new file mode 100644
index 00000000..8d9792eb
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandValidator.cs
@@ -0,0 +1,60 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+using System;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
+
+///
+/// Validates the needed validation rules for .
+///
+public class UpdateAlbumCoverCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public UpdateAlbumCoverCommandValidator()
+ {
+ // Validates the identifier of the media library the album belongs to, taken from the route.
+ RuleFor(command => command.LibraryId)
+ .NotEmpty()
+ .WithError(Errors.Library.LibraryIdCannotBeEmpty);
+
+ RuleFor(command => command.LibraryId)
+ .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
+ .When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
+ .WithError(Errors.Library.LibraryIdCannotBeEmpty);
+
+ // Validates the identifier of the artist the album belongs to, taken from the route.
+ RuleFor(command => command.ArtistId)
+ .NotEmpty()
+ .WithError(Errors.Music.ArtistIdCannotBeEmpty);
+
+ RuleFor(command => command.ArtistId)
+ .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty)
+ .When(command => command.ArtistId is not null && command.ArtistId.Length > 0)
+ .WithError(Errors.Music.ArtistIdCannotBeEmpty);
+
+ // Validates the identifier of the album whose cover image is updated, taken from the route.
+ RuleFor(command => command.AlbumId)
+ .NotEmpty()
+ .WithError(Errors.Music.AlbumIdCannotBeEmpty);
+
+ RuleFor(command => command.AlbumId)
+ .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty)
+ .When(command => command.AlbumId is not null && command.AlbumId.Length > 0)
+ .WithError(Errors.Music.AlbumIdCannotBeEmpty);
+
+ // Validates the uploaded cover image.
+ RuleFor(command => command.Cover)
+ .NotNull()
+ .WithError(Errors.Music.CoverCannotBeNull);
+
+ RuleFor(command => command.FileName)
+ .NotEmpty()
+ .When(command => command.Cover is not null)
+ .WithError(Errors.FileSystemManagement.FileNameCannotBeEmpty);
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommand.cs
new file mode 100644
index 00000000..98bb23f2
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommand.cs
@@ -0,0 +1,22 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System.Diagnostics;
+using System.IO;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
+
+///
+/// Command for updating the cover image of an existing artist.
+///
+/// The unique identifier of the media library this artist belongs to, taken from the route.
+/// The unique identifier of the artist whose cover image is updated, taken from the route.
+/// The stream of the uploaded cover image file.
+/// The name of the uploaded cover image file.
+[DebuggerDisplay("ArtistId: {ArtistId} FileName: {FileName}")]
+public record UpdateArtistCoverCommand(
+ string? LibraryId,
+ string? ArtistId,
+ Stream? Cover,
+ string? FileName
+) : ICommand;
diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandHandler.cs
new file mode 100644
index 00000000..7b84738e
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandHandler.cs
@@ -0,0 +1,144 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
+
+///
+/// Handler for the command to update the cover image of an existing artist.
+///
+public class UpdateArtistCoverCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IMusicArtworkService _musicArtworkService;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected service for storing the artwork of a music library item.
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected validator for application validation rules.
+ public UpdateArtistCoverCommandHandler(IUnitOfWork unitOfWork, IMusicArtworkService musicArtworkService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _musicArtworkService = musicArtworkService;
+ _authorizationService = authorizationService;
+ _currentUserService = currentUserService;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to update the cover image of an existing artist.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the response carrying the relative path of the stored cover image, or an error message.
+ ///
+ public async Task> HandleAsync(UpdateArtistCoverCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // The validator guarantees that the route identifiers are non-empty Guids before this point.
+ Guid libraryId = Guid.Parse(command.LibraryId!);
+ Guid artistId = Guid.Parse(command.ArtistId!);
+
+ Result getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
+ if (getArtistResult.IsFailure)
+ return getArtistResult.Errors;
+ if (getArtistResult.Value is null)
+ return DomainErrors.Music.ArtistNotFound;
+ ArtistEntity existingArtist = getArtistResult.Value;
+
+ // Resource scoping: the artist must belong to the library named by the route, so that an artist can never be edited through another
+ // library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library.
+ if (existingArtist.LibraryId != libraryId)
+ return DomainErrors.Music.ArtistNotFound;
+
+ // Admins can update the artists of all libraries; for everyone else, only the artists of the libraries they own.
+ bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync(
+ userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false);
+ if (!canAccessLibrary)
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // The artwork is stored under the library and artist segments, so their names are resolved to keep the location consistent with the scanned artwork.
+ Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(existingArtist.LibraryId, cancellationToken: cancellationToken).ConfigureAwait(false);
+ if (getLibraryResult.IsFailure)
+ return getLibraryResult.Errors;
+ if (getLibraryResult.Value is null)
+ return DomainErrors.Library.LibraryNotFound;
+ string libraryName = getLibraryResult.Value.Title;
+
+ // The existing cover of the artist is looked up, so that the previous file can be replaced as a whole instead of being left orphaned on disk.
+ Result> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnerAsync(MusicArtworkOwnerType.Artist, artistId, cancellationToken).ConfigureAwait(false);
+ if (getArtworkResult.IsFailure)
+ return getArtworkResult.Errors;
+ string? existingCoverPath = getArtworkResult.Value
+ .Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
+ .Select(artwork => artwork.FileName)
+ .FirstOrDefault();
+
+ Result storeArtworkResult = await _musicArtworkService.SaveArtistArtworkAsync(
+ existingArtist.LibraryId,
+ libraryName,
+ existingArtist.Name,
+ command.Cover!,
+ command.FileName!,
+ cancellationToken).ConfigureAwait(false);
+ if (storeArtworkResult.IsFailure)
+ return storeArtworkResult.Errors;
+
+ // The stored cover of the artist is replaced as a whole: when the new cover is stored under a different name than the previous one
+ // (for example a png replacing a jpg), the previous file is removed, so that no orphaned artwork is left on disk without a reference.
+ if (!string.IsNullOrWhiteSpace(existingCoverPath) && existingCoverPath != storeArtworkResult.Value)
+ {
+ Result deleteResult = _musicArtworkService.DeleteStoredArtwork(existingCoverPath);
+ if (deleteResult.IsFailure)
+ return deleteResult.Errors;
+ }
+
+ // Map the newly stored cover image onto the artwork of the artist, replacing the existing cover or adding a new one.
+ Result upsertResult = await _unitOfWork.MusicArtworkRepository.UpsertCoverAsync(
+ MusicArtworkOwnerType.Artist, artistId, storeArtworkResult.Value, cancellationToken).ConfigureAwait(false);
+ if (upsertResult.IsFailure)
+ return upsertResult.Errors;
+
+ Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+ if (saveChangesResult.IsFailure)
+ return saveChangesResult.Errors;
+
+ return new UpdateArtistCoverResponse(storeArtworkResult.Value);
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandValidator.cs
new file mode 100644
index 00000000..384522da
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandValidator.cs
@@ -0,0 +1,50 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+using System;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
+
+///
+/// Validates the needed validation rules for .
+///
+public class UpdateArtistCoverCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public UpdateArtistCoverCommandValidator()
+ {
+ // Validates the identifier of the media library the artist belongs to, taken from the route.
+ RuleFor(command => command.LibraryId)
+ .NotEmpty()
+ .WithError(Errors.Library.LibraryIdCannotBeEmpty);
+
+ RuleFor(command => command.LibraryId)
+ .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
+ .When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
+ .WithError(Errors.Library.LibraryIdCannotBeEmpty);
+
+ // Validates the identifier of the artist whose cover image is updated, taken from the route.
+ RuleFor(command => command.ArtistId)
+ .NotEmpty()
+ .WithError(Errors.Music.ArtistIdCannotBeEmpty);
+
+ RuleFor(command => command.ArtistId)
+ .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty)
+ .When(command => command.ArtistId is not null && command.ArtistId.Length > 0)
+ .WithError(Errors.Music.ArtistIdCannotBeEmpty);
+
+ // Validates the uploaded cover image.
+ RuleFor(command => command.Cover)
+ .NotNull()
+ .WithError(Errors.Music.CoverCannotBeNull);
+
+ RuleFor(command => command.FileName)
+ .NotEmpty()
+ .When(command => command.Cover is not null)
+ .WithError(Errors.FileSystemManagement.FileNameCannotBeEmpty);
+ }
+}
diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCoverResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCoverResponse.cs
new file mode 100644
index 00000000..eb6ca6a4
--- /dev/null
+++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCoverResponse.cs
@@ -0,0 +1,14 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+
+///
+/// Represents a response of an update album cover operation.
+///
+/// The relative path of the stored cover image.
+[DebuggerDisplay("CoverPath: {CoverPath}")]
+public record UpdateAlbumCoverResponse(
+ string CoverPath
+);
diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCoverResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCoverResponse.cs
new file mode 100644
index 00000000..dc45d9f9
--- /dev/null
+++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCoverResponse.cs
@@ -0,0 +1,14 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+
+///
+/// Represents a response of an update artist cover operation.
+///
+/// The relative path of the stored cover image.
+[DebuggerDisplay("CoverPath: {CoverPath}")]
+public record UpdateArtistCoverResponse(
+ string CoverPath
+);
diff --git a/src/Lumina.Domain/Common/Errors/Errors.Music.cs b/src/Lumina.Domain/Common/Errors/Errors.Music.cs
index d4cca16a..b636930d 100644
--- a/src/Lumina.Domain/Common/Errors/Errors.Music.cs
+++ b/src/Lumina.Domain/Common/Errors/Errors.Music.cs
@@ -65,5 +65,6 @@ public static partial class Errors
public static Error IsniValueCannotBeEmpty => Error.Validation(description: nameof(IsniValueCannotBeEmpty));
public static Error IsniValueMustBeMaximum20CharactersLong => Error.Validation(description: nameof(IsniValueMustBeMaximum20CharactersLong));
public static Error WorkTitleCannotBeEmpty => Error.Validation(description: nameof(WorkTitleCannotBeEmpty));
+ public static Error CoverCannotBeNull => Error.Validation(description: nameof(CoverCannotBeNull));
}
}
diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Albums.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Albums.cs
index dd1fafd4..2933c8f6 100644
--- a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Albums.cs
+++ b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Albums.cs
@@ -15,6 +15,7 @@ public static partial class ApiRoutes
public const string ADD_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums";
public const string GET_ALBUM_BY_ID = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}";
public const string UPDATE_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}";
+ public const string UPDATE_ALBUM_COVER = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover";
public const string DELETE_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}";
public const string GET_ALBUM_TRACKS = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks";
public const string GET_ALBUM_TRACKS_LITE = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite";
diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Artists.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Artists.cs
index b3d50a4a..d8c1bd07 100644
--- a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Artists.cs
+++ b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Artists.cs
@@ -15,6 +15,7 @@ public static partial class ApiRoutes
public const string GET_ARTISTS_LITE = "/libraries/{libraryId}/artists/lite";
public const string ADD_ARTIST = "/libraries/{libraryId}/artists";
public const string UPDATE_ARTIST = "/libraries/{libraryId}/artists/{artistId}";
+ public const string UPDATE_ARTIST_COVER = "/libraries/{libraryId}/artists/{artistId}/cover";
public const string DELETE_ARTIST = "/libraries/{libraryId}/artists/{artistId}";
}
}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpoint.cs
new file mode 100644
index 00000000..fc91b7ac
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpoint.cs
@@ -0,0 +1,82 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Common;
+using Microsoft.AspNetCore.Http;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
+
+///
+/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover route.
+///
+public class UpdateAlbumCoverEndpoint : BaseEndpoint
+{
+ private readonly ICommandHandler> _updateAlbumCoverCommandHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling update album cover commands.
+ public UpdateAlbumCoverEndpoint(ICommandHandler> updateAlbumCoverCommandHandler)
+ {
+ _updateAlbumCoverCommandHandler = updateAlbumCoverCommandHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.PUT);
+ Routes(ApiRoutes.Albums.UPDATE_ALBUM_COVER);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Updates the cover image of the album with the image uploaded in the multipart form of the request.
+ ///
+ /// The request object.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
+ {
+ // Take the identifiers from the route.
+ string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
+ string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString();
+ string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString();
+
+ IFormFile? cover = null;
+ if (HttpContext.Request.HasFormContentType)
+ {
+ try
+ {
+ // The cover is the first file of the multipart form; a multipart body without any file cannot be parsed as a form,
+ // so a malformed upload is treated as a missing cover, which the command validator reports.
+ cover = HttpContext.Request.Form.Files.Count > 0 ? HttpContext.Request.Form.Files[0] : null;
+ }
+ catch (InvalidDataException)
+ {
+ cover = null;
+ }
+ }
+
+ // The cover stream must stay open while the handler stores the image, and is disposed as soon as the handler returns.
+ UpdateAlbumCoverCommand command = new(libraryId, artistId, albumId, cover?.OpenReadStream(), cover?.FileName);
+ try
+ {
+ Result result = await _updateAlbumCoverCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+ finally
+ {
+ command.Cover?.Dispose();
+ }
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointSummary.cs
new file mode 100644
index 00000000..318c3267
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointSummary.cs
@@ -0,0 +1,108 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateAlbumCoverEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public UpdateAlbumCoverEndpointSummary()
+ {
+ Summary = "Updates the cover image of an album.";
+ Description = "Updates the cover image of the album identified by the route, with the image uploaded in the multipart form of the request.";
+
+ Response(200, "The relative path of the stored cover image is returned.",
+ example: new UpdateAlbumCoverResponse(
+ CoverPath: "/media/music/music-3f2504e0-4f89-41d3-9a0c-0305e82c3301/Queen-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/A Night at the Opera-7c1d2e3f-4a5b-6c7d-8e9f-0a1b2c3d4e5f/cover.jpg"
+ )
+ );
+
+ Response(401, "Authentication required.", "application/problem+json",
+ example: new[]
+ {
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "Authentication failed",
+ instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+
+ Response(404, "The request failed because the album or its media library does not exist.", "application/problem+json",
+ example: new[]
+ {
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
+ title = "General.NotFound",
+ status = 404,
+ detail = "AlbumNotFound",
+ instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover",
+ traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
+ title = "General.NotFound",
+ status = 404,
+ detail = "LibraryNotFound",
+ instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover",
+ traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
+ }
+ }
+ );
+
+ Response(422, "The request did not pass validation checks, either on the request itself or while storing the uploaded cover image.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc4918#section-11.2",
+ title = "General.Validation",
+ status = 422,
+ detail = "OneOrMoreValidationErrorsOccurred",
+ instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "LibraryIdCannotBeEmpty",
+ "ArtistIdCannotBeEmpty",
+ "AlbumIdCannotBeEmpty",
+ "CoverCannotBeNull",
+ "FileNameCannotBeEmpty",
+ "FileTooLarge",
+ "CoverFileMustBeAnImage"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpoint.cs
new file mode 100644
index 00000000..9439978d
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpoint.cs
@@ -0,0 +1,81 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Common;
+using Microsoft.AspNetCore.Http;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
+
+///
+/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/cover route.
+///
+public class UpdateArtistCoverEndpoint : BaseEndpoint
+{
+ private readonly ICommandHandler> _updateArtistCoverCommandHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling update artist cover commands.
+ public UpdateArtistCoverEndpoint(ICommandHandler> updateArtistCoverCommandHandler)
+ {
+ _updateArtistCoverCommandHandler = updateArtistCoverCommandHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.PUT);
+ Routes(ApiRoutes.Artists.UPDATE_ARTIST_COVER);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Updates the cover image of the artist with the image uploaded in the multipart form of the request.
+ ///
+ /// The request object.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
+ {
+ // Take the identifiers from the route.
+ string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
+ string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString();
+
+ IFormFile? cover = null;
+ if (HttpContext.Request.HasFormContentType)
+ {
+ try
+ {
+ // The cover is the first file of the multipart form; a multipart body without any file cannot be parsed as a form,
+ // so a malformed upload is treated as a missing cover, which the command validator reports.
+ cover = HttpContext.Request.Form.Files.Count > 0 ? HttpContext.Request.Form.Files[0] : null;
+ }
+ catch (InvalidDataException)
+ {
+ cover = null;
+ }
+ }
+
+ // The cover stream must stay open while the handler stores the image, and is disposed as soon as the handler returns.
+ UpdateArtistCoverCommand command = new(libraryId, artistId, cover?.OpenReadStream(), cover?.FileName);
+ try
+ {
+ Result result = await _updateArtistCoverCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+ finally
+ {
+ command.Cover?.Dispose();
+ }
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointSummary.cs
new file mode 100644
index 00000000..c3a39e0a
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointSummary.cs
@@ -0,0 +1,107 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateArtistCoverEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public UpdateArtistCoverEndpointSummary()
+ {
+ Summary = "Updates the cover image of an artist.";
+ Description = "Updates the cover image of the artist identified by the route, with the image uploaded in the multipart form of the request.";
+
+ Response(200, "The relative path of the stored cover image is returned.",
+ example: new UpdateArtistCoverResponse(
+ CoverPath: "/media/music/music-3f2504e0-4f89-41d3-9a0c-0305e82c3301/Queen-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/cover.jpg"
+ )
+ );
+
+ Response(401, "Authentication required.", "application/problem+json",
+ example: new[]
+ {
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "Authentication failed",
+ instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+
+ Response(404, "The request failed because the artist or its media library does not exist.", "application/problem+json",
+ example: new[]
+ {
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
+ title = "General.NotFound",
+ status = 404,
+ detail = "ArtistNotFound",
+ instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover",
+ traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
+ title = "General.NotFound",
+ status = 404,
+ detail = "LibraryNotFound",
+ instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover",
+ traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
+ }
+ }
+ );
+
+ Response(422, "The request did not pass validation checks, either on the request itself or while storing the uploaded cover image.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc4918#section-11.2",
+ title = "General.Validation",
+ status = 422,
+ detail = "OneOrMoreValidationErrorsOccurred",
+ instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "LibraryIdCannotBeEmpty",
+ "ArtistIdCannotBeEmpty",
+ "CoverCannotBeNull",
+ "FileNameCannotBeEmpty",
+ "FileTooLarge",
+ "CoverFileMustBeAnImage"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.sln b/src/Lumina.sln
index 23593842..2614a640 100644
--- a/src/Lumina.sln
+++ b/src/Lumina.sln
@@ -265,6 +265,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "albums", "albums", "{B4DF8E
..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracks.http = ..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracks.http
..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracksLite.http = ..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracksLite.http
..\docs\technical\requests\library\audio-library\music-library\albums\UpdateAlbum.http = ..\docs\technical\requests\library\audio-library\music-library\albums\UpdateAlbum.http
+ ..\docs\technical\requests\library\audio-library\music-library\albums\UpdateAlbumCover.http = ..\docs\technical\requests\library\audio-library\music-library\albums\UpdateAlbumCover.http
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "artists", "artists", "{F3818697-E304-491D-8BF3-4DAA1733B5F5}"
@@ -277,6 +278,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "artists", "artists", "{F381
..\docs\technical\requests\library\audio-library\music-library\artists\GetArtists.http = ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtists.http
..\docs\technical\requests\library\audio-library\music-library\artists\GetArtistsLite.http = ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtistsLite.http
..\docs\technical\requests\library\audio-library\music-library\artists\UpdateArtist.http = ..\docs\technical\requests\library\audio-library\music-library\artists\UpdateArtist.http
+ ..\docs\technical\requests\library\audio-library\music-library\artists\UpdateArtistCover.http = ..\docs\technical\requests\library\audio-library\music-library\artists\UpdateArtistCover.http
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tracks", "tracks", "{B1B657B1-60DC-4E22-89D2-6212154D6BA8}"
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandFixture.cs
new file mode 100644
index 00000000..b242c423
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandFixture.cs
@@ -0,0 +1,72 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+using System.Linq;
+using System.Text;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateAlbumCoverCommandFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the media library the album belongs to.
+ /// Optional. The Id of the artist the album belongs to.
+ /// Optional. The Id of the album whose cover is updated.
+ /// Optional. The stream of the uploaded cover image file.
+ /// Optional. The name of the uploaded cover image file.
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the artist Id should be included, or forced to .
+ /// Whether the album Id should be included, or forced to .
+ /// Whether the cover stream should be included, or forced to .
+ /// Whether the file name should be included, or forced to .
+ /// The created .
+ public UpdateAlbumCoverCommand Create(
+ string? libraryId = null,
+ string? artistId = null,
+ string? albumId = null,
+ Stream? cover = null,
+ string? fileName = null,
+ bool includeLibraryId = true,
+ bool includeArtistId = true,
+ bool includeAlbumId = true,
+ bool includeCover = true,
+ bool includeFileName = true)
+ {
+ return new UpdateAlbumCoverCommand(
+ includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
+ includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
+ includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null,
+ includeCover ? (cover ?? CreateCoverStream()) : null,
+ includeFileName ? (fileName ?? "cover.jpg") : 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())];
+ }
+
+ ///
+ /// Creates an in-memory stream carrying a minimal file payload.
+ ///
+ /// A non-empty in-memory stream.
+ private static Stream CreateCoverStream()
+ {
+ byte[] payload = Encoding.UTF8.GetBytes("fake cover payload");
+ return new MemoryStream(payload);
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandFixture.cs
new file mode 100644
index 00000000..6235be2d
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtistCover/UpdateArtistCoverCommandFixture.cs
@@ -0,0 +1,67 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+using System.Linq;
+using System.Text;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtistCover;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateArtistCoverCommandFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the media library the artist belongs to.
+ /// Optional. The Id of the artist whose cover is updated.
+ /// Optional. The stream of the uploaded cover image file.
+ /// Optional. The name of the uploaded cover image file.
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the artist Id should be included, or forced to .
+ /// Whether the cover stream should be included, or forced to .
+ /// Whether the file name should be included, or forced to .
+ /// The created .
+ public UpdateArtistCoverCommand Create(
+ string? libraryId = null,
+ string? artistId = null,
+ Stream? cover = null,
+ string? fileName = null,
+ bool includeLibraryId = true,
+ bool includeArtistId = true,
+ bool includeCover = true,
+ bool includeFileName = true)
+ {
+ return new UpdateArtistCoverCommand(
+ includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
+ includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null,
+ includeCover ? (cover ?? CreateCoverStream()) : null,
+ includeFileName ? (fileName ?? "cover.jpg") : 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())];
+ }
+
+ ///
+ /// Creates an in-memory stream carrying a minimal file payload.
+ ///
+ /// A non-empty in-memory stream.
+ private static Stream CreateCoverStream()
+ {
+ byte[] payload = Encoding.UTF8.GetBytes("fake cover payload");
+ return new MemoryStream(payload);
+ }
+}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCoverResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCoverResponseFixture.cs
new file mode 100644
index 00000000..1cd18954
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCoverResponseFixture.cs
@@ -0,0 +1,40 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateAlbumCoverResponseFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The relative path of the stored cover image.
+ /// The created .
+ public UpdateAlbumCoverResponse Create(string? coverPath = null)
+ {
+ return new UpdateAlbumCoverResponse(
+ coverPath ?? _faker.System.FilePath()
+ );
+ }
+
+ ///
+ /// 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/AudioLibrary/MusicLibrary/Artists/UpdateArtistCoverResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCoverResponseFixture.cs
new file mode 100644
index 00000000..0bdb8166
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCoverResponseFixture.cs
@@ -0,0 +1,40 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateArtistCoverResponseFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The relative path of the stored cover image.
+ /// The created .
+ public UpdateArtistCoverResponse Create(string? coverPath = null)
+ {
+ return new UpdateArtistCoverResponse(
+ coverPath ?? _faker.System.FilePath()
+ );
+ }
+
+ ///
+ /// 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/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointTests.cs
new file mode 100644
index 00000000..91ea5e92
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointTests.cs
@@ -0,0 +1,382 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
+using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateAlbumCoverEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private HttpClient _client;
+ private readonly AuthenticatedLuminaApiFactory _apiFactory;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true,
+ Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
+ };
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public UpdateAlbumCoverEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Fact]
+ public async Task UpdateAlbumCover_WhenCalledByOwnerWithValidImage_ShouldReplaceTheStoredCover()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumWithCoverAsync(userId, "/media/music/old-cover.jpg");
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", CreateCoverForm("cover.png"));
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ string storedPath = JsonSerializer.Deserialize(content, _jsonOptions)!.CoverPath;
+ Assert.False(string.IsNullOrWhiteSpace(storedPath));
+ Assert.Contains("cover.png", storedPath, StringComparison.OrdinalIgnoreCase);
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ MusicArtworkEntity coverArtwork = dbContext.MusicArtwork
+ .Single(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId && artwork.ArtworkType == ArtworkType.Cover);
+ Assert.Equal(storedPath, coverArtwork.FileName);
+ Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status);
+ }
+
+ [Fact]
+ public async Task UpdateAlbumCover_WhenAlbumHasNoExistingCover_ShouldCreateACoverArtwork()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", CreateCoverForm("cover.png"));
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ string storedPath = JsonSerializer.Deserialize(content, _jsonOptions)!.CoverPath;
+ Assert.False(string.IsNullOrWhiteSpace(storedPath));
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ MusicArtworkEntity coverArtwork = dbContext.MusicArtwork
+ .Single(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == albumId && artwork.ArtworkType == ArtworkType.Cover);
+ Assert.Equal(storedPath, coverArtwork.FileName);
+ }
+
+ [Fact]
+ public async Task UpdateAlbumCover_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId, _) = await SeedLibraryArtistAndAlbumAsync(userId);
+ string url = $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{Guid.NewGuid()}/cover";
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
+
+ // Assert
+ await AssertNotFoundAsync(response, "AlbumNotFound", url);
+ }
+
+ [Fact]
+ public async Task UpdateAlbumCover_WhenAlbumBelongsToAnotherLibrary_ShouldReturnAlbumNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (_, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
+ Guid otherLibraryId = Guid.NewGuid();
+ string url = $"/api/v1/libraries/{otherLibraryId}/artists/{artistId}/albums/{albumId}/cover";
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
+
+ // Assert
+ await AssertNotFoundAsync(response, "AlbumNotFound", url);
+ }
+
+ [Fact]
+ public async Task UpdateAlbumCover_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
+ {
+ // Arrange
+ Guid otherUserId = await SeedOtherUserAsync();
+ (Guid otherLibraryId, Guid otherArtistId, Guid otherAlbumId) = await SeedLibraryArtistAndAlbumAsync(otherUserId);
+ string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/albums/{otherAlbumId}/cover";
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
+
+ // Assert
+ await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
+ }
+
+ [Fact]
+ public async Task UpdateAlbumCover_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.PutAsync(url, CreateCoverForm("cover.png"));
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task UpdateAlbumCover_WhenNoFileIsUploaded_ShouldReturnUnprocessableEntityWithCoverCannotBeNull()
+ {
+ // Arrange
+ MultipartFormDataContent form = [];
+ form.Add(new StringContent("unrelated-field"), "unrelated-field");
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover";
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsync(url, form);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "CoverCannotBeNull");
+ }
+
+ [Fact]
+ public async Task UpdateAlbumCover_WhenAlbumIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{Guid.NewGuid()}/albums/not-a-guid/cover";
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "AlbumIdCannotBeEmpty");
+ }
+
+ ///
+ /// Creates a multipart form carrying a minimal PNG-like payload.
+ ///
+ /// The name of the uploaded file.
+ /// A configured instance.
+ private static MultipartFormDataContent CreateCoverForm(string fileName)
+ {
+ // The payload only needs to carry the PNG signature in its first bytes and exceed the header detection buffer.
+ byte[] payload = new byte[100];
+ payload[0] = 137;
+ payload[1] = 80;
+ payload[2] = 78;
+ payload[3] = 71;
+ payload[4] = 13;
+ payload[5] = 10;
+ payload[6] = 26;
+ payload[7] = 10;
+ MultipartFormDataContent form = [];
+ ByteArrayContent fileContent = new(payload);
+ fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
+ form.Add(fileContent, "cover", fileName);
+ return form;
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist and one of its albums that has no cover yet.
+ ///
+ /// The Id of the user that owns the library.
+ /// The Ids of the seeded library, artist and album.
+ private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId, albumId);
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist and one of its albums that already has a cover.
+ ///
+ /// The Id of the user that owns the library.
+ /// The relative path of the existing cover of the album.
+ /// The Ids of the seeded library, artist and album.
+ private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumWithCoverAsync(Guid userId, string existingCoverFileName)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
+ dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: albumId, artworkType: ArtworkType.Cover, ordinal: 0, fileName: existingCoverFileName, status: ArtworkStatus.Enriched));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId, albumId);
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id.
+ ///
+ /// The Id of the seeded user.
+ private async Task SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ return userId;
+ }
+
+ ///
+ /// Gets the Id of the currently authenticated test user.
+ ///
+ /// The Id of the authenticated test user.
+ private Guid GetCurrentUserId()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
+ return user.Id;
+ }
+
+ ///
+ /// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected problem detail.
+ /// The expected request instance path.
+ private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
+ {
+ await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
+ }
+
+ ///
+ /// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected HTTP status code.
+ /// The expected problem title.
+ /// The expected problem detail.
+ /// The expected request instance path.
+ /// The expected problem type URI.
+ private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
+ {
+ Assert.Equal(statusCode, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
+ Assert.Equal(expectedType, problemDetails["type"].GetString());
+ Assert.Equal(expectedTitle, problemDetails["title"].GetString());
+ Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+ }
+
+ ///
+ /// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
+ }
+
+ ///
+ /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ /// The validation error codes that must all be present.
+ private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
+ {
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
+ Assert.Equal("General.Validation", problemDetails["title"].GetString());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
+ Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+
+ Dictionary? errors = problemDetails["errors"].Deserialize>();
+ Assert.NotNull(errors);
+ Assert.Contains("General.Validation", errors.Keys);
+ Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
+ }
+
+ ///
+ /// Disposes API factory resources.
+ ///
+ public async Task DisposeAsync()
+ {
+ await _apiFactory.RemoveTestUserAsync();
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointTests.cs
new file mode 100644
index 00000000..ee8d938b
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointTests.cs
@@ -0,0 +1,391 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
+using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateArtistCoverEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private HttpClient _client;
+ private readonly AuthenticatedLuminaApiFactory _apiFactory;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true,
+ Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
+ };
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public UpdateArtistCoverEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Fact]
+ public async Task UpdateArtistCover_WhenCalledByOwnerWithValidImage_ShouldReplaceTheStoredCover()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId) = await SeedLibraryAndArtistWithCoverAsync(userId, "/media/music/old-artist-cover.jpg");
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/cover", CreateCoverForm("cover.png"));
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ string storedPath = JsonSerializer.Deserialize(content, _jsonOptions)!.CoverPath;
+ Assert.False(string.IsNullOrWhiteSpace(storedPath));
+ Assert.Contains("cover.png", storedPath, StringComparison.OrdinalIgnoreCase);
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ MusicArtworkEntity coverArtwork = dbContext.MusicArtwork
+ .Single(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artistId && artwork.ArtworkType == ArtworkType.Cover);
+ Assert.Equal(storedPath, coverArtwork.FileName);
+ Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status);
+ }
+
+ [Fact]
+ public async Task UpdateArtistCover_WhenArtistHasNoExistingCover_ShouldCreateACoverArtwork()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(userId);
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/cover", CreateCoverForm("cover.png"));
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ string storedPath = JsonSerializer.Deserialize(content, _jsonOptions)!.CoverPath;
+ Assert.False(string.IsNullOrWhiteSpace(storedPath));
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ MusicArtworkEntity coverArtwork = dbContext.MusicArtwork
+ .Single(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artistId && artwork.ArtworkType == ArtworkType.Cover);
+ Assert.Equal(storedPath, coverArtwork.FileName);
+ }
+
+ [Fact]
+ public async Task UpdateArtistCover_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ string url = $"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/cover";
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
+
+ // Assert
+ await AssertNotFoundAsync(response, "ArtistNotFound", url);
+ }
+
+ [Fact]
+ public async Task UpdateArtistCover_WhenArtistRequestedThroughDifferentLibrary_ShouldReturnArtistNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (_, Guid artistId) = await SeedLibraryAndArtistAsync(userId);
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{artistId}/cover";
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
+
+ // Assert
+ await AssertNotFoundAsync(response, "ArtistNotFound", url);
+ }
+
+ [Fact]
+ public async Task UpdateArtistCover_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
+ {
+ // Arrange
+ Guid otherUserId = await SeedOtherUserAsync();
+ (Guid otherLibraryId, Guid otherArtistId) = await SeedLibraryAndArtistAsync(otherUserId);
+ string url = $"/api/v1/libraries/{otherLibraryId}/artists/{otherArtistId}/cover";
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
+
+ // Assert
+ await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
+ }
+
+ [Fact]
+ public async Task UpdateArtistCover_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.PutAsync(url, CreateCoverForm("cover.png"));
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task UpdateArtistCover_WhenNoFileIsUploaded_ShouldReturnUnprocessableEntityWithCoverCannotBeNull()
+ {
+ // Arrange
+ MultipartFormDataContent form = [];
+ form.Add(new StringContent("unrelated-field"), "unrelated-field");
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover";
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsync(url, form);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "CoverCannotBeNull");
+ }
+
+ [Fact]
+ public async Task UpdateArtistCover_WhenArtistIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/not-a-guid/cover";
+
+ // Act
+ HttpResponseMessage response = await _client.PutAsync(url, CreateCoverForm("cover.png"));
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "ArtistIdCannotBeEmpty");
+ }
+
+ ///
+ /// Creates a multipart form carrying a minimal PNG-like payload.
+ ///
+ /// The name of the uploaded file.
+ /// A configured instance.
+ private static MultipartFormDataContent CreateCoverForm(string fileName)
+ {
+ // The payload only needs to carry the PNG signature in its first bytes and exceed the header detection buffer.
+ byte[] payload = new byte[100];
+ payload[0] = 137;
+ payload[1] = 80;
+ payload[2] = 78;
+ payload[3] = 71;
+ payload[4] = 13;
+ payload[5] = 10;
+ payload[6] = 26;
+ payload[7] = 10;
+ MultipartFormDataContent form = [];
+ ByteArrayContent fileContent = new(payload);
+ fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
+ form.Add(fileContent, "cover", fileName);
+ return form;
+ }
+
+ ///
+ /// Seeds a music library owned by .
+ ///
+ /// The Id of the user that owns the library.
+ /// The Id of the seeded library.
+ private async Task SeedLibraryAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
+ await dbContext.SaveChangesAsync();
+ return libraryId;
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist that has no cover yet.
+ ///
+ /// The Id of the user that owns the library.
+ /// The Ids of the seeded library and artist.
+ private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId);
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist that already has a cover.
+ ///
+ /// The Id of the user that owns the library.
+ /// The relative path of the existing cover of the artist.
+ /// The Ids of the seeded library and artist.
+ private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistWithCoverAsync(Guid userId, string existingCoverFileName)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: []));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
+ dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artistId, artworkType: ArtworkType.Cover, ordinal: 0, fileName: existingCoverFileName, status: ArtworkStatus.Enriched));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId);
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id.
+ ///
+ /// The Id of the seeded user.
+ private async Task SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ return userId;
+ }
+
+ ///
+ /// Gets the Id of the currently authenticated test user.
+ ///
+ /// The Id of the authenticated test user.
+ private Guid GetCurrentUserId()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
+ return user.Id;
+ }
+
+ ///
+ /// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected problem detail.
+ /// The expected request instance path.
+ private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
+ {
+ await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
+ }
+
+ ///
+ /// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected HTTP status code.
+ /// The expected problem title.
+ /// The expected problem detail.
+ /// The expected request instance path.
+ /// The expected problem type URI.
+ private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
+ {
+ Assert.Equal(statusCode, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
+ Assert.Equal(expectedType, problemDetails["type"].GetString());
+ Assert.Equal(expectedTitle, problemDetails["title"].GetString());
+ Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+ }
+
+ ///
+ /// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
+ }
+
+ ///
+ /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ /// The validation error codes that must all be present.
+ private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
+ {
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
+ Assert.Equal("General.Validation", problemDetails["title"].GetString());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
+ Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+
+ Dictionary? errors = problemDetails["errors"].Deserialize>();
+ Assert.NotNull(errors);
+ Assert.Contains("General.Validation", errors.Keys);
+ Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
+ }
+
+ ///
+ /// Disposes API factory resources.
+ ///
+ public async Task DisposeAsync()
+ {
+ await _apiFactory.RemoveTestUserAsync();
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointTests.cs
new file mode 100644
index 00000000..9f30b955
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCover/UpdateAlbumCoverEndpointTests.cs
@@ -0,0 +1,320 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
+using Lumina.Presentation.Api.SecurityTests.Common.Setup;
+using Microsoft.AspNetCore.Http;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+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.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbumCover;
+
+///
+/// Contains security tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateAlbumCoverEndpointTests : IClassFixture, IDisposable
+{
+ private readonly LuminaApiFactory _apiFactory;
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly List _seededUsernames = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public UpdateAlbumCoverEndpointTests(LuminaApiFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task UpdateAlbumCover_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ MultipartFormDataContent form = CreateCoverForm("cover.jpg");
+
+ // Act
+ HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", form);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", problemDetails["instance"].GetProperty("value").GetString());
+ }
+
+ [Fact]
+ public async Task UpdateAlbumCover_WhenUnauthorized_ShouldNotLeakSensitiveData()
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
+ MultipartFormDataContent form = CreateCoverForm("cover.jpg");
+
+ // Act
+ HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover", form);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ 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("'; DROP TABLE Albums; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ public async Task UpdateAlbumCover_WithSQLInjectionInLibraryRouteId_ShouldRemainSecure(string maliciousLibraryId)
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+ MultipartFormDataContent form = CreateCoverForm("cover.jpg");
+
+ // Act
+ HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover", form);
+
+ // Assert
+ await AssertCleanValidationErrorAsync(response, maliciousLibraryId, "LibraryIdCannotBeEmpty");
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Albums; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ public async Task UpdateAlbumCover_WithSQLInjectionInArtistRouteId_ShouldRemainSecure(string maliciousArtistId)
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+ MultipartFormDataContent form = CreateCoverForm("cover.jpg");
+
+ // Act
+ HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/cover", form);
+
+ // Assert
+ await AssertCleanValidationErrorAsync(response, maliciousArtistId, "ArtistIdCannotBeEmpty");
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Albums; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ public async Task UpdateAlbumCover_WithSQLInjectionInAlbumRouteId_ShouldRemainSecure(string maliciousAlbumId)
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+ MultipartFormDataContent form = CreateCoverForm("cover.jpg");
+
+ // Act
+ HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/cover", form);
+
+ // Assert
+ await AssertCleanValidationErrorAsync(response, maliciousAlbumId, "AlbumIdCannotBeEmpty");
+ }
+
+ [Fact]
+ public async Task UpdateAlbumCover_WhenAlbumDoesNotExist_ShouldReturnNotFoundWithoutLeakingInternals()
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+ MultipartFormDataContent form = CreateCoverForm("cover.jpg");
+
+ // Act
+ HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover", form);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
+ Assert.Equal("AlbumNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
+ }
+
+ [Fact]
+ public async Task UpdateAlbumCover_WithMaliciousFileName_ShouldNotCorruptOrLeakData()
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+ MultipartFormDataContent form = CreateCoverForm("..\\..\\evil.jpg");
+
+ // Act
+ HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/cover", form);
+
+ // Assert
+ // The album does not exist, so the handler returns a clean not found response before the uploaded file name is used.
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public async Task UpdateAlbumCover_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
+ {
+ // Arrange
+ HttpClient ownerClient = _apiFactory.CreateClient();
+ (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
+ _seededUsernames.Add(ownerUsername);
+ (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(ownerId);
+
+ HttpClient requesterClient = _apiFactory.CreateClient();
+ (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
+ _seededUsernames.Add(requesterUsername);
+ MultipartFormDataContent form = CreateCoverForm("cover.jpg");
+
+ // Act
+ HttpResponseMessage response = await requesterClient.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/cover", form);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", 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);
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
+ Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
+ }
+
+ [Fact]
+ public async Task UpdateAlbumCover_WhenResourceBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutLeakingOrModifyingIt()
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(actingUsername);
+ (Guid ownLibraryId, _, _) = await SeedLibraryArtistAndAlbumAsync(actingUserId);
+
+ // The resource lives in a library owned by another user, and is referenced through the acting user's own library route.
+ HttpClient victimClient = _apiFactory.CreateClient();
+ (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
+ _seededUsernames.Add(victimUsername);
+ (_, Guid victimArtistId, Guid victimAlbumId) = await SeedLibraryArtistAndAlbumAsync(victimUserId);
+ MultipartFormDataContent form = CreateCoverForm("cover.jpg");
+
+ // Act
+ HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}/cover", form);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
+ Assert.Equal("AlbumNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
+
+ // The other user's album is untouched.
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ AlbumEntity? storedAlbum = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == victimAlbumId);
+ Assert.NotNull(storedAlbum);
+ Assert.Equal("News of the World", storedAlbum.Title);
+ }
+
+ ///
+ /// Asserts that the response is a clean validation problem details that neither leaks internals nor echoes the injected payload.
+ ///
+ /// The HTTP response to assert.
+ /// The injected payload that must never be echoed back.
+ /// The validation error code expected in the response.
+ private static async Task AssertCleanValidationErrorAsync(HttpResponseMessage response, string injectedPayload, string expectedErrorCode)
+ {
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(injectedPayload, content, StringComparison.Ordinal);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+ Assert.Contains(expectedErrorCode, content, StringComparison.Ordinal);
+ }
+
+ ///
+ /// Creates a multipart form carrying a minimal cover payload with the specified file name.
+ ///
+ /// The name of the uploaded file.
+ /// A configured instance.
+ private static MultipartFormDataContent CreateCoverForm(string fileName)
+ {
+ MultipartFormDataContent form = [];
+ ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload"));
+ fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
+ form.Add(fileContent, "cover", fileName);
+ return form;
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist and one of its albums.
+ ///
+ /// The Id of the user that owns the library.
+ /// The Ids of the seeded library, artist and album.
+ private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "News of the World", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Security Audio Library", libraryType: LibraryType.Music, contentLocations: []));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId, albumId);
+ }
+
+ ///
+ /// Disposes API factory resources.
+ ///
+ public void Dispose()
+ {
+ foreach (string username in _seededUsernames)
+ _apiFactory.RemoveTestUser(username);
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointTests.cs
new file mode 100644
index 00000000..dab067a8
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtistCover/UpdateArtistCoverEndpointTests.cs
@@ -0,0 +1,298 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
+using Lumina.Presentation.Api.SecurityTests.Common.Setup;
+using Microsoft.AspNetCore.Http;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+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.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtistCover;
+
+///
+/// Contains security tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateArtistCoverEndpointTests : IClassFixture, IDisposable
+{
+ private readonly LuminaApiFactory _apiFactory;
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly List _seededUsernames = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public UpdateArtistCoverEndpointTests(LuminaApiFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task UpdateArtistCover_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ MultipartFormDataContent form = CreateCoverForm("cover.jpg");
+
+ // Act
+ HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/cover", form);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal($"/api/v1/libraries/{libraryId}/artists/{artistId}/cover", problemDetails["instance"].GetProperty("value").GetString());
+ }
+
+ [Fact]
+ public async Task UpdateArtistCover_WhenUnauthorized_ShouldNotLeakSensitiveData()
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
+ MultipartFormDataContent form = CreateCoverForm("cover.jpg");
+
+ // Act
+ HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover", form);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ 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("'; DROP TABLE Artists; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ public async Task UpdateArtistCover_WithSQLInjectionInLibraryRouteId_ShouldRemainSecure(string maliciousLibraryId)
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+ MultipartFormDataContent form = CreateCoverForm("cover.jpg");
+
+ // Act
+ HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/cover", form);
+
+ // Assert
+ await AssertCleanValidationErrorAsync(response, maliciousLibraryId, "LibraryIdCannotBeEmpty");
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Artists; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ public async Task UpdateArtistCover_WithSQLInjectionInArtistRouteId_ShouldRemainSecure(string maliciousArtistId)
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+ MultipartFormDataContent form = CreateCoverForm("cover.jpg");
+
+ // Act
+ HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/cover", form);
+
+ // Assert
+ await AssertCleanValidationErrorAsync(response, maliciousArtistId, "ArtistIdCannotBeEmpty");
+ }
+
+ [Fact]
+ public async Task UpdateArtistCover_WhenArtistDoesNotExist_ShouldReturnNotFoundWithoutLeakingInternals()
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+ MultipartFormDataContent form = CreateCoverForm("cover.jpg");
+
+ // Act
+ HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover", form);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
+ Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
+ }
+
+ [Fact]
+ public async Task UpdateArtistCover_WithMaliciousFileName_ShouldNotCorruptOrLeakData()
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+ MultipartFormDataContent form = CreateCoverForm("..\\..\\evil.jpg");
+
+ // Act
+ HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/cover", form);
+
+ // Assert
+ // The artist does not exist, so the handler returns a clean not found response before the uploaded file name is used.
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public async Task UpdateArtistCover_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
+ {
+ // Arrange
+ HttpClient ownerClient = _apiFactory.CreateClient();
+ (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
+ _seededUsernames.Add(ownerUsername);
+ (Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(ownerId);
+
+ HttpClient requesterClient = _apiFactory.CreateClient();
+ (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
+ _seededUsernames.Add(requesterUsername);
+ MultipartFormDataContent form = CreateCoverForm("cover.jpg");
+
+ // Act
+ HttpResponseMessage response = await requesterClient.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/cover", form);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", 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);
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
+ Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
+ }
+
+ [Fact]
+ public async Task UpdateArtistCover_WhenArtistBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutLeakingOrModifyingIt()
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(actingUsername);
+ (Guid ownLibraryId, _) = await SeedLibraryAndArtistAsync(actingUserId);
+
+ // The artist lives in a library owned by another user, and is referenced through the acting user's own library route.
+ HttpClient victimClient = _apiFactory.CreateClient();
+ (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
+ _seededUsernames.Add(victimUsername);
+ (_, Guid victimArtistId) = await SeedLibraryAndArtistAsync(victimUserId);
+ MultipartFormDataContent form = CreateCoverForm("cover.jpg");
+
+ // Act
+ HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/cover", form);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
+ Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
+
+ // The other user's artist is untouched.
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ ArtistEntity? storedArtist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == victimArtistId);
+ Assert.NotNull(storedArtist);
+ Assert.Equal("Queen", storedArtist.Name);
+ }
+
+ ///
+ /// Asserts that the response is a clean validation problem details that neither leaks internals nor echoes the injected payload.
+ ///
+ /// The HTTP response to assert.
+ /// The injected payload that must never be echoed back.
+ /// The validation error code expected in the response.
+ private static async Task AssertCleanValidationErrorAsync(HttpResponseMessage response, string injectedPayload, string expectedErrorCode)
+ {
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(injectedPayload, content, StringComparison.Ordinal);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+ Assert.Contains(expectedErrorCode, content, StringComparison.Ordinal);
+ }
+
+ ///
+ /// Creates a multipart form carrying a minimal cover payload with the specified file name.
+ ///
+ /// The name of the uploaded file.
+ /// A configured instance.
+ private static MultipartFormDataContent CreateCoverForm(string fileName)
+ {
+ MultipartFormDataContent form = [];
+ ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload"));
+ fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
+ form.Add(fileContent, "cover", fileName);
+ return form;
+ }
+
+ ///
+ /// Seeds a music library owned by , together with an artist.
+ ///
+ /// The Id of the user that owns the library.
+ /// The Ids of the seeded library and artist.
+ private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Security Audio Library", libraryType: LibraryType.Music, contentLocations: []));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, artistId);
+ }
+
+ ///
+ /// Disposes API factory resources.
+ ///
+ public void Dispose()
+ {
+ foreach (string username in _seededUsernames)
+ _apiFactory.RemoveTestUser(username);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandlerTests.cs
new file mode 100644
index 00000000..72575f3d
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbumCover/UpdateAlbumCoverCommandHandlerTests.cs
@@ -0,0 +1,722 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
+using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
+using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using NSubstitute;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbumCover;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class UpdateAlbumCoverCommandHandlerTests
+{
+ private const string STORED_COVER_PATH = "/media/music/library/artist/Album/album/cover.jpg";
+
+ private readonly IUnitOfWork _mockUnitOfWork;
+ private readonly IAlbumRepository _mockAlbumRepository;
+ private readonly IArtistRepository _mockArtistRepository;
+ private readonly ILibraryRepository _mockLibraryRepository;
+ private readonly IMusicArtworkRepository _mockMusicArtworkRepository;
+ private readonly IMusicArtworkService _mockMusicArtworkService;
+ private readonly IPathService _mockPathService;
+ private readonly IAuthorizationService _mockAuthorizationService;
+ private readonly ICurrentUserService _mockCurrentUserService;
+ private readonly IValidator _mockValidator;
+ private readonly UpdateAlbumCoverCommandHandler _sut;
+ private readonly Guid _userId;
+ private readonly UpdateAlbumCoverCommandFixture _updateAlbumCoverCommandFixture = new();
+ private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public UpdateAlbumCoverCommandHandlerTests()
+ {
+ _mockAlbumRepository = Substitute.For();
+ _mockArtistRepository = Substitute.For();
+ _mockLibraryRepository = Substitute.For();
+ _mockMusicArtworkRepository = Substitute.For();
+ _mockUnitOfWork = Substitute.For();
+ _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success);
+ _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
+ _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
+ _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
+ _mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository);
+ _mockMusicArtworkService = Substitute.For();
+ _mockPathService = Substitute.For();
+ _mockAuthorizationService = Substitute.For();
+ _mockCurrentUserService = Substitute.For();
+ _mockValidator = Substitute.For>();
+ _userId = Guid.NewGuid();
+
+ // Default stubs: the current user is authenticated, the library ownership policy allows access, the validator passes, the album has no artwork yet, and the artwork storage succeeds.
+ _mockCurrentUserService.UserId.Returns(_userId);
+ _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any())
+ .Returns(true);
+ _mockValidator.Validate(Arg.Any()).Returns([]);
+ // The stored artwork paths used by the tests are Unix separated, and sanitizing a name keeps it unchanged, as the real service does for valid names.
+ _mockPathService.PathSeparator.Returns('/');
+ _mockPathService.SanitizeSegment(Arg.Any())
+ .Returns(callInfo => PathSegment.Create(callInfo.Arg(), isDirectory: true, isDrive: false));
+ _mockMusicArtworkRepository.GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any())
+ .Returns(Result.From>([]));
+ _mockMusicArtworkRepository.UpsertCoverAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any())
+ .Returns(Result.From(Result.Updated));
+ _mockMusicArtworkService.SaveAlbumArtworkAsync(
+ Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(),
+ Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any())
+ .Returns(Result.From(STORED_COVER_PATH));
+ _mockMusicArtworkService.DeleteStoredArtwork(Arg.Any()).Returns(Result.From(Result.Deleted));
+
+ _sut = new UpdateAlbumCoverCommandHandler(_mockUnitOfWork, _mockMusicArtworkService, _mockPathService, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenValidatorFails_ShouldReturnValidationErrorsWithoutStoringArtwork()
+ {
+ // Arrange
+ UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
+ _mockValidator.Validate(Arg.Any()).Returns([Errors.Music.CoverCannotBeNull]);
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Music.CoverCannotBeNull, result.FirstError);
+ await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any());
+ await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any());
+ await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any());
+ await _mockMusicArtworkRepository.DidNotReceive().GetByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
+ {
+ // Arrange
+ UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
+ _mockCurrentUserService.UserId.Returns((Guid?)null);
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
+ await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any());
+ await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenAlbumRepositoryReturnsError_ShouldReturnFailureResult()
+ {
+ // Arrange
+ UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
+ _mockAlbumRepository.GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any())
+ .Returns(Errors.Library.LibraryIdCannotBeEmpty);
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
+ await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any());
+ await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundError()
+ {
+ // Arrange
+ UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
+ _mockAlbumRepository.GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any())
+ .Returns(Result.From(null));
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
+ await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any());
+ await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenAlbumBelongsToAnotherLibrary_ShouldReturnAlbumNotFoundError()
+ {
+ // Arrange
+ UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
+ // The stored album belongs to a different library than the one named by the route.
+ AlbumEntity existingAlbum = _albumEntityFixture.Create(id: Guid.Parse(command.AlbumId!), artistId: Guid.Parse(command.ArtistId!), libraryId: Guid.NewGuid());
+ _mockAlbumRepository.GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any())
+ .Returns(Result.From(existingAlbum));
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
+ await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenAlbumBelongsToAnotherArtist_ShouldReturnAlbumNotFoundError()
+ {
+ // Arrange
+ UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
+ // The stored album belongs to a different artist than the one named by the route.
+ AlbumEntity existingAlbum = _albumEntityFixture.Create(id: Guid.Parse(command.AlbumId!), artistId: Guid.NewGuid(), libraryId: Guid.Parse(command.LibraryId!));
+ _mockAlbumRepository.GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any())
+ .Returns(Result.From(existingAlbum));
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError);
+ await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedErrorWithoutStoringArtwork()
+ {
+ // Arrange
+ UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
+ SetupExistingAlbum(command);
+ _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any())
+ .Returns(false);
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
+ await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any());
+ await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenLibraryRepositoryReturnsError_ShouldReturnFailureResult()
+ {
+ // Arrange
+ UpdateAlbumCoverCommand command = _updateAlbumCoverCommandFixture.Create();
+ SetupExistingAlbum(command);
+ _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any())
+ .Returns(Errors.Library.LibraryIdCannotBeEmpty);
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
+ await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any());
+ await _mockMusicArtworkService.DidNotReceive().SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any