Implements tests for commit 1aa427b1e2

This commit is contained in:
BinaryAlley committed 2026-10-28 13:39:12 +02:00
1 parent e52081533a
commit 8b8d077c6a
6 files changed
+305 -16

No files matched your search

@@ -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);
@@ -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;
}
}