mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Implements tests for commit 1aa427b1e2
This commit is contained in:
1 parent
e52081533a
commit
8b8d077c6a
6 files changed
+305
-16
No files matched your search
+52
@@ -41,7 +41,9 @@ using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -151,6 +153,56 @@ public class UpdateTrackEndpointTests : IClassFixture<AuthenticatedLuminaApiFact
|
||||
Assert.Equal(originalPath, storedTrack.Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateTrack_WhenRequestBodyCarriesAFilePath_ShouldIgnoreItAndPreserveTheStoredPath()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
string originalPath = Path.Combine(s_contentRootPath, "bohemian-rhapsody.flac");
|
||||
string attemptedPath = Path.Combine(Path.GetTempPath(), "lumina-outside-content-root", "etc", "hosts");
|
||||
(Guid artistId, Guid albumId, Guid trackId) = await SeedArtistGraphAsync(libraryId, originalPath);
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create(
|
||||
metadata: _musicTrackMetadataDtoFixture.Create(title: "Somebody to Love"),
|
||||
moods: [],
|
||||
isrcs: [],
|
||||
contributors: [],
|
||||
ratings: [],
|
||||
includeDiscNumber: false,
|
||||
includeScript: false,
|
||||
includeKey: false,
|
||||
includeBpm: false,
|
||||
includeWork: false,
|
||||
includeMusicBrainzRecordingId: false,
|
||||
includeMusicBrainzTrackId: false);
|
||||
JsonSerializerOptions serializationOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
JsonObject body = JsonSerializer.SerializeToNode(request, serializationOptions)!.AsObject();
|
||||
body["path"] = attemptedPath;
|
||||
using StringContent jsonContent = new(body.ToJsonString(serializationOptions), Encoding.UTF8, "application/json");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", jsonContent);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
TrackResponse? trackResponse = JsonSerializer.Deserialize<TrackResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(trackResponse);
|
||||
// the posted file system path is ignored, because a track path is set only when the track is created by the scanner
|
||||
Assert.Equal(originalPath, trackResponse!.Path);
|
||||
Assert.NotEqual(attemptedPath, trackResponse.Path);
|
||||
Assert.Equal("Somebody to Love", trackResponse.Metadata!.Title);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
TrackEntity storedTrack = dbContext.Tracks.Single(track => track.Id == trackId);
|
||||
Assert.Equal(originalPath, storedTrack.Path);
|
||||
Assert.NotEqual(attemptedPath, storedTrack.Path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateTrack_WhenCalledByAdminOnAnotherUsersLibrary_ShouldUpdateTrack()
|
||||
{
|
||||
|
||||
+68
@@ -8,11 +8,15 @@ using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
@@ -24,6 +28,11 @@ namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioL
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private static readonly JsonSerializerOptions s_jsonOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdateMusicTrackRequestFixture _updateMusicTrackRequestFixture = new();
|
||||
private readonly MusicTrackDtoFixture _musicTrackDtoFixture = new();
|
||||
@@ -66,6 +75,41 @@ public class SaveMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}" && putRequest.Data is UpdateMusicTrackRequest forwarded && forwarded.Metadata!.Title == request.Metadata!.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicTrack_WhenPostedBodyCarriesAFilePath_ShouldNotForwardAFilePathToTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
string attemptedPath = Path.Combine(Path.GetTempPath(), "lumina-outside-content-root", "etc", "hosts");
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId);
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", expectedTrack);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId, albumId, trackId, libraryId, request, attemptedPath);
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
|
||||
(string Endpoint, object? Data) forwardedRequest = Assert.Single(
|
||||
_apiFactory.ApiClientStub.PutRequests,
|
||||
putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
UpdateMusicTrackRequest forwarded = Assert.IsType<UpdateMusicTrackRequest>(forwardedRequest.Data);
|
||||
Assert.Equal(request.Metadata!.Title, forwarded.Metadata!.Title);
|
||||
// The Web request type has no file system path, so the posted path is dropped before the API call.
|
||||
using JsonDocument forwardedJson = JsonDocument.Parse(JsonSerializer.Serialize(forwarded, s_jsonOptions));
|
||||
Assert.False(forwardedJson.RootElement.TryGetProperty("path", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicTrack_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
@@ -123,4 +167,28 @@ public class SaveMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return saveRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the save request that PUTs the given <paramref name="request"/>, carrying an extra file system path property,
|
||||
/// to the track identified by the route, with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The route Id of the artist the track belongs to.</param>
|
||||
/// <param name="albumId">The route Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The route Id of the track to save.</param>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="request">The track data to send.</param>
|
||||
/// <param name="attemptedPath">The file system path to inject into the posted body.</param>
|
||||
/// <returns>The configured save request.</returns>
|
||||
private static HttpRequestMessage CreateSaveRequest(Guid artistId, Guid albumId, Guid trackId, Guid libraryId, UpdateMusicTrackRequest request, string attemptedPath)
|
||||
{
|
||||
JsonObject body = JsonSerializer.SerializeToNode(request, s_jsonOptions)!.AsObject();
|
||||
body["path"] = attemptedPath;
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-save-track?libraryId={libraryId}")
|
||||
{
|
||||
Content = new StringContent(body.ToJsonString(s_jsonOptions), Encoding.UTF8, "application/json")
|
||||
};
|
||||
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return saveRequest;
|
||||
}
|
||||
}
|
||||
+56
-9
@@ -3,9 +3,10 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.Mu
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.UpdateTrack;
|
||||
@@ -13,16 +14,13 @@ 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.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.UpdateTrack;
|
||||
@@ -116,6 +114,54 @@ public class UpdateTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
Assert.Equal(maliciousTitle, storedTrack!.Title);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("C:\\Windows\\System32\\drivers\\etc\\hosts")] // Windows sensitive file
|
||||
[InlineData("/etc/passwd")] // Unix sensitive file
|
||||
public async Task UpdateTrack_WhenRequestBodyAttemptsToRedirectTheTrackFilePath_ShouldPreserveTheStoredPathAndNotLeakIt(string attemptedPath)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
SeedLibrary(libraryId, userId);
|
||||
string originalPath = Path.Combine(s_contentRootPath, "bohemian-rhapsody.flac");
|
||||
(Guid artistId, Guid albumId, Guid trackId) = SeedArtistGraph(libraryId, originalPath);
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create(
|
||||
moods: [],
|
||||
isrcs: [],
|
||||
contributors: [],
|
||||
ratings: []);
|
||||
JsonSerializerOptions serializationOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
JsonObject body = JsonSerializer.SerializeToNode(request, serializationOptions)!.AsObject();
|
||||
body["path"] = attemptedPath;
|
||||
using StringContent jsonContent = new(body.ToJsonString(serializationOptions), Encoding.UTF8, "application/json");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", jsonContent);
|
||||
|
||||
// Assert
|
||||
// A client can never point an existing track at an arbitrary host file: the posted path is ignored, the stored path is left untouched,
|
||||
// and the response must not report the attempted path nor leak database details.
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
TrackResponse? trackResponse = JsonSerializer.Deserialize<TrackResponse>(content, serializationOptions);
|
||||
Assert.NotNull(trackResponse);
|
||||
Assert.Equal(originalPath, trackResponse!.Path);
|
||||
Assert.NotEqual(attemptedPath, trackResponse.Path);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
TrackEntity? storedTrack = await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId);
|
||||
Assert.NotNull(storedTrack);
|
||||
Assert.Equal(originalPath, storedTrack!.Path);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
@@ -319,14 +365,15 @@ public class UpdateTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
/// Seeds an artist that owns a single album, which in turn owns a single track, all belonging to <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="trackPath">Optional. The file system path of the seeded track. Defaults to a file inside the test content root path.</param>
|
||||
/// <returns>The Ids of the seeded artist, album and track.</returns>
|
||||
private (Guid artistId, Guid albumId, Guid trackId) SeedArtistGraph(Guid libraryId)
|
||||
private (Guid artistId, Guid albumId, Guid trackId) SeedArtistGraph(Guid libraryId, string? trackPath = null)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: Path.Combine(s_contentRootPath, "bohemian-rhapsody.flac"), includeMetadata: false);
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: trackPath ?? Path.Combine(s_contentRootPath, "bohemian-rhapsody.flac"), includeMetadata: false);
|
||||
AlbumEntity album = _albumEntityFixture.Create(id: albumId, libraryId: libraryId, tracks: [track], includeMetadata: false);
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, albums: [album], includeContributors: false);
|
||||
dbContext.Artists.Add(artist);
|
||||
|
||||
+70
-3
@@ -6,13 +6,14 @@ using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Threading.Tasks;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.SaveMusicTrack;
|
||||
@@ -23,6 +24,11 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibr
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SaveMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private static readonly JsonSerializerOptions s_jsonOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdateMusicTrackRequestFixture _updateMusicTrackRequestFixture = new();
|
||||
private readonly MusicTrackDtoFixture _musicTrackDtoFixture = new();
|
||||
@@ -123,6 +129,44 @@ public class SaveMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}" && putRequest.Data is UpdateMusicTrackRequest forwarded && forwarded.Metadata!.Title == maliciousTitle);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("C:\\Windows\\System32\\drivers\\etc\\hosts")] // Windows sensitive file
|
||||
[InlineData("/etc/passwd")] // Unix sensitive file
|
||||
public async Task SaveMusicTrack_WhenPostedBodyAttemptsToSetTheFilePath_ShouldNotForwardAFilePathToTheApi(string attemptedPath)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
UpdateMusicTrackRequest request = _updateMusicTrackRequestFixture.Create();
|
||||
MusicTrackDto expectedTrack = _musicTrackDtoFixture.Create(id: trackId);
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", expectedTrack);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage saveRequest = CreateSaveRequest(artistId.ToString(), albumId.ToString(), trackId.ToString(), libraryId.ToString(), request, attemptedPath);
|
||||
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The Web request type has no file system path, so a posted path can never reach the API, and the response must not echo it
|
||||
// nor leak stack traces or database details.
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain(attemptedPath, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
(string Endpoint, object? Data) forwardedRequest = Assert.Single(
|
||||
_apiFactory.ApiClientStub.PutRequests,
|
||||
putRequest => putRequest.Endpoint == $"libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
|
||||
UpdateMusicTrackRequest forwarded = Assert.IsType<UpdateMusicTrackRequest>(forwardedRequest.Data);
|
||||
Assert.Equal(request.Metadata!.Title, forwarded.Metadata!.Title);
|
||||
using JsonDocument forwardedJson = JsonDocument.Parse(JsonSerializer.Serialize(forwarded, s_jsonOptions));
|
||||
Assert.False(forwardedJson.RootElement.TryGetProperty("path", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveMusicTrack_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
@@ -179,4 +223,27 @@ public class SaveMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return saveRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the save request that PUTs the given <paramref name="request"/>, carrying an extra file system path property, to the track identified by the route, with the owning library passed through the query string.
|
||||
/// </summary>
|
||||
/// <param name="artistId">The raw route value of the artist Id.</param>
|
||||
/// <param name="albumId">The raw route value of the album Id.</param>
|
||||
/// <param name="trackId">The raw route value of the track Id.</param>
|
||||
/// <param name="libraryId">The raw query value of the library Id.</param>
|
||||
/// <param name="request">The track data to send.</param>
|
||||
/// <param name="attemptedPath">The file system path to inject into the posted body.</param>
|
||||
/// <returns>The configured save request.</returns>
|
||||
private static HttpRequestMessage CreateSaveRequest(string artistId, string albumId, string trackId, string libraryId, UpdateMusicTrackRequest request, string attemptedPath)
|
||||
{
|
||||
JsonObject body = JsonSerializer.SerializeToNode(request, s_jsonOptions)!.AsObject();
|
||||
body["path"] = attemptedPath;
|
||||
HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/audio-library/music-library/artists/{Uri.EscapeDataString(artistId)}/albums/{Uri.EscapeDataString(albumId)}/tracks/{Uri.EscapeDataString(trackId)}/api-save-track?libraryId={Uri.EscapeDataString(libraryId)}")
|
||||
{
|
||||
Content = new StringContent(body.ToJsonString(s_jsonOptions), Encoding.UTF8, "application/json")
|
||||
};
|
||||
saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return saveRequest;
|
||||
}
|
||||
}
|
||||
+16
@@ -157,6 +157,22 @@ public class AudioMetadataDtoMappingTests
|
||||
Assert.Equal(trackDisambiguation, track.Disambiguation.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyTo_WhenApplyingAudioMetadata_ShouldPreserveTheTrackFilePath()
|
||||
{
|
||||
// Arrange
|
||||
(Artist artist, Album album, Track track) = CreateDomainArtist();
|
||||
string originalPath = track.Path;
|
||||
AudioMetadataDto dto = _audioMetadataDtoFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<Updated> result = dto.ApplyTo(artist, album, track, []);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(originalPath, track.Path);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a domain artist that owns a single album, which in turn owns a single track.
|
||||
/// </summary>
|
||||
|
||||
+43
-4
@@ -1,5 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
@@ -17,7 +16,6 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
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.Tracks.Commands.UpdateTrack;
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
@@ -31,6 +29,7 @@ using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -144,6 +143,45 @@ public class UpdateTrackCommandHandlerTests
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenStoredTrackPathIsOutsideTheLibraryContentLocations_ShouldUpdateTheTrackAndPreserveItsPath()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string storedPath = Path.Combine(Path.GetTempPath(), "lumina-handler-tests", "queen", "bohemian-rhapsody.flac");
|
||||
(ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId, storedPath);
|
||||
string libraryContentLocation = Path.Combine(Path.GetTempPath(), "lumina-handler-tests", "other-content-root");
|
||||
UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString());
|
||||
ArtistEntity? updatedArtist = null;
|
||||
TrackEntity? updatedTrack = null;
|
||||
_mockArtistRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<ArtistEntity?>(existingArtist));
|
||||
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
updatedArtist = callInfo.Arg<ArtistEntity>();
|
||||
updatedTrack = updatedArtist.Albums.SelectMany(album => album.Tracks).First(track => track.Id == trackId);
|
||||
return Result.Updated;
|
||||
});
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(contentLocations: [libraryContentLocation])));
|
||||
_mockTrackRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Result.From<TrackEntity?>(updatedTrack));
|
||||
|
||||
// Act
|
||||
Result<TrackResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(trackId, result.Value.Id);
|
||||
Assert.NotNull(updatedTrack);
|
||||
// The file system path is preserved by the update even when the stored path is outside the library content locations.
|
||||
Assert.Equal(storedPath, updatedTrack!.Path);
|
||||
Assert.Equal(storedPath, result.Value.Path);
|
||||
await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidatorFails_ShouldReturnValidationErrorsWithoutUpdating()
|
||||
{
|
||||
@@ -544,8 +582,9 @@ public class UpdateTrackCommandHandlerTests
|
||||
/// Creates an artist entity that owns a single album, which in turn owns a single track, all belonging to <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="trackPath">Optional. The file system path of the created track. A random path is generated when it is not supplied.</param>
|
||||
/// <returns>The created artist entity, together with the Ids of its album and track.</returns>
|
||||
private (ArtistEntity artist, Guid albumId, Guid trackId) CreateArtistWithTrack(Guid libraryId)
|
||||
private (ArtistEntity artist, Guid albumId, Guid trackId) CreateArtistWithTrack(Guid libraryId, string? trackPath = null)
|
||||
{
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
@@ -556,7 +595,7 @@ public class UpdateTrackCommandHandlerTests
|
||||
_albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
libraryId: libraryId,
|
||||
tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId)])
|
||||
tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: trackPath)])
|
||||
]);
|
||||
return (artist, albumId, trackId);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user