Renames project paths from Lumina to Nemera

This commit is contained in:
BinaryAlley committed 2026-11-27 15:34:43 +02:00
1 parent ce6fddb4c9
commit 0f659a4877
6450 files changed

No files matched your search

@@ -0,0 +1,242 @@
#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.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.AddAlbum;
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.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.AddAlbum;
/// <summary>
/// Contains security tests for the <see cref="AddAlbumEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddAlbumEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new();
private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="AddAlbumEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AddAlbumEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task AddAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", problemDetails["instance"].GetProperty("value").GetString());
}
[Fact]
public async Task AddAlbum_WhenUnauthorized_ShouldNotLeakSensitiveData()
{
// Arrange
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums", request);
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.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task AddAlbum_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums", request);
// Assert
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(maliciousLibraryId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task AddAlbum_WithSQLInjectionInArtistRouteId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
{
// Arrange
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums", request);
// Assert
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(maliciousArtistId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("ArtistIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task AddAlbum_WithSQLInjectionInBody_ShouldNotCorruptOrDeleteData(string maliciousTitle)
{
// Arrange
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
(Guid libraryId, Guid artistId) = await SeedLibraryArtistAndAlbumAsync(userId);
AddAlbumRequest request = _addAlbumRequestFixture.Create(
metadata: _musicAlbumMetadataDtoFixture.Create(title: maliciousTitle),
contributors: [],
ratings: [],
tracks: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request);
// Assert
// The malicious title passes validation, reaches the parameterized insert, and is persisted verbatim: if it were
// concatenated into raw SQL, the insert would fail and the album would not be created.
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(2, await dbContext.Albums.CountAsync(album => album.LibraryId == libraryId));
}
[Fact]
public async Task AddAlbum_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
_seededUsernames.Add(ownerUsername);
(Guid libraryId, Guid artistId) = await SeedLibraryArtistAndAlbumAsync(ownerId);
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(requesterUsername);
AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist that owns one album.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and artist.</returns>
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryArtistAndAlbumAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,259 @@
#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.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum;
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.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum;
/// <summary>
/// Contains security tests for the <see cref="DeleteAlbumEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteAlbumEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="DeleteAlbumEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeleteAlbumEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task DeleteAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task DeleteAlbum_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task DeleteAlbum_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task DeleteAlbum_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task DeleteAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
Guid otherUserId = await SeedOtherUserAsync();
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistWithTwoAlbumsAsync(otherUserId);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task DeleteAlbum_WhenAlbumBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutDeletingIt()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(actingUsername);
(Guid ownLibraryId, _, _) = await SeedLibraryArtistWithTwoAlbumsAsync(actingUserId);
// The album 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 SeedLibraryArtistWithTwoAlbumsAsync(victimUserId);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
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 album is untouched.
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.NotNull(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == victimAlbumId));
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return userId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist that owns two albums.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist and the first album.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistWithTwoAlbumsAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid otherAlbumId = 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);
AlbumEntity otherAlbum = _albumEntityFixture.Create(id: otherAlbumId, 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: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album, otherAlbum], includeContributors: false));
await dbContext.SaveChangesAsync();
return (libraryId, artistId, albumId);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,219 @@
#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.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum;
/// <summary>
/// Contains security tests for the <see cref="GetAlbumEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetAlbumEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetAlbumEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetAlbumEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetAlbum_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}");
// Assert
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(maliciousLibraryId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetAlbum_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}");
// Assert
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(maliciousArtistId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetAlbum_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}");
// Assert
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(maliciousAlbumId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task GetAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
Guid otherUserId = await SeedOtherUserAsync();
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return userId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and one of its albums.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist and album.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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: "Queen Reissues", 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);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,222 @@
#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.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks;
/// <summary>
/// Contains security tests for the <see cref="GetAlbumTracksEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetAlbumTracksEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetAlbumTracksEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetAlbumTracksEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetAlbumTracks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetAlbumTracks_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks");
// Assert
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(maliciousLibraryId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetAlbumTracks_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks");
// Assert
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(maliciousArtistId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetAlbumTracks_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks");
// Assert
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(maliciousAlbumId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task GetAlbumTracks_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
Guid otherUserId = await SeedOtherUserAsync();
(Guid libraryId, Guid artistId, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return userId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist, one of its albums and one of its tracks.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedArtistAlbumWithTrackAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/we-are-the-champions-{Guid.NewGuid():N}.flac", title: "We Are the Champions", includeMetadata: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "News of the World", tracks: [track], includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", 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, trackId);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,222 @@
#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.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite;
/// <summary>
/// Contains security tests for the <see cref="GetAlbumTracksLiteEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetAlbumTracksLiteEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetAlbumTracksLiteEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetAlbumTracksLiteEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetAlbumTracksLite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/lite";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetAlbumTracksLite_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/lite");
// Assert
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(maliciousLibraryId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetAlbumTracksLite_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks/lite");
// Assert
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(maliciousArtistId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetAlbumTracksLite_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks/lite");
// Assert
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(maliciousAlbumId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task GetAlbumTracksLite_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
Guid otherUserId = await SeedOtherUserAsync();
(Guid libraryId, Guid artistId, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return userId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist, one of its albums and one of its tracks.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedArtistAlbumWithTrackAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/we-are-the-champions-{Guid.NewGuid():N}.flac", title: "We Are the Champions", includeMetadata: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "News of the World", tracks: [track], includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", 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, trackId);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,157 @@
#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.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetDeletedAlbums;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetDeletedAlbums;
/// <summary>
/// Contains security tests for the <see cref="GetDeletedAlbumsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedAlbumsEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private readonly List<string> _seededUsernames = [];
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedAlbumsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDeletedAlbumsEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetDeletedAlbums_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/albums/deleted-items";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetDeletedAlbums_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/albums/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task GetDeletedAlbums_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenAndNotLeakTheDeletedAlbum()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
const string TITLE = "Secret Deleted Album";
const string COVER_PATH = "/private/deleted-album-cover.jpg";
Guid libraryId = await SeedLibraryAndDeletedAlbumAsync(victimUserId, TITLE, COVER_PATH);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/albums/deleted-items");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.DoesNotContain(TITLE, content, StringComparison.Ordinal);
Assert.DoesNotContain(COVER_PATH, content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with a deleted album, its artist and its cover.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="title">The title of the deleted album.</param>
/// <param name="coverPath">The stored cover path of the deleted album.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAndDeletedAlbumAsync(Guid userId, string title, string coverPath)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(
artistId: artistId,
libraryId: libraryId,
title: title,
includeTracks: false,
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
album.IsDeleted = true;
album.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Victim Artist", albums: [album], includeContributors: false));
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: album.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: coverPath));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Removes the users created by the tests.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,241 @@
#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.RestoreAlbum;
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.Net;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.RestoreAlbum;
/// <summary>
/// Contains security tests for the <see cref="RestoreAlbumEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreAlbumEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private readonly List<string> _seededUsernames = [];
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreAlbumEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RestoreAlbumEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task RestoreAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/restore";
// Act
HttpResponseMessage response = await _client.PostAsync(url, null);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task RestoreAlbum_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/restore", null);
// Assert
await AssertRejectedInjectionAttemptAsync(response);
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task RestoreAlbum_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/restore", null);
// Assert
await AssertRejectedInjectionAttemptAsync(response);
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task RestoreAlbum_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/restore", null);
// Assert
await AssertRejectedInjectionAttemptAsync(response);
}
[Fact]
public async Task RestoreAlbum_WhenAlbumBelongsToAnotherUser_ShouldReturnForbiddenAndKeepItDeleted()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndDeletedAlbumAsync(victimUserId);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/restore", null);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
AlbumEntity? album = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId);
Assert.NotNull(album);
Assert.True(album!.IsDeleted);
}
[Fact]
public async Task RestoreAlbum_WhenAlbumIsRestoredThroughAnotherLibrary_ShouldReturnNotFoundAndKeepItDeleted()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(actingUsername);
Guid ownLibraryId = await SeedLibraryAsync(actingUserId);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
(_, Guid victimArtistId, Guid victimAlbumId) = await SeedLibraryArtistAndDeletedAlbumAsync(victimUserId);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}/restore", null);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
AlbumEntity? victimAlbum = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == victimAlbumId);
Assert.NotNull(victimAlbum);
Assert.True(victimAlbum!.IsDeleted);
}
/// <summary>
/// Asserts that a route parameter carrying an injection payload is rejected as a validation error, without leaking internal details.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private async Task AssertRejectedInjectionAttemptAsync(HttpResponseMessage response)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Acting Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and a deleted album of that artist.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist and album.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndDeletedAlbumAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(
artistId: artistId,
libraryId: libraryId,
title: "Victim Album",
includeTracks: false,
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
album.IsDeleted = true;
album.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Victim Artist", albums: [album], includeContributors: false));
await dbContext.SaveChangesAsync();
return (libraryId, artistId, album.Id);
}
/// <summary>
/// Removes the users created by the tests.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,294 @@
#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.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbum;
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.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbum;
/// <summary>
/// Contains security tests for the <see cref="UpdateAlbumEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateAlbumEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly UpdateAlbumRequestFixture _updateAlbumRequestFixture = new();
private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="UpdateAlbumEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdateAlbumEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task UpdateAlbum_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();
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
Assert.NotNull(problemDetails);
Assert.Equal(401, 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}", problemDetails["instance"].GetProperty("value").GetString());
}
[Fact]
public async Task UpdateAlbum_WhenUnauthorized_ShouldNotLeakSensitiveData()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", request);
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 UpdateAlbum_WithSQLInjectionInBody_ShouldNotCorruptOrLeakData(string maliciousTitle)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(title: maliciousTitle), contributors: [], ratings: []);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", request);
// Assert
// The malicious title passes validation, reaches the parameterized update, and is persisted verbatim: if it were
// concatenated into raw SQL, the update would fail and the album would not be updated.
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
AlbumEntity? storedAlbum = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId);
Assert.NotNull(storedAlbum);
Assert.Equal(maliciousTitle, storedAlbum!.Title);
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task UpdateAlbum_WithSQLInjectionInLibraryRouteId_ShouldRemainSecure(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", request);
// Assert
await AssertCleanValidationErrorAsync(response, maliciousLibraryId, "LibraryIdCannotBeEmpty");
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task UpdateAlbum_WithSQLInjectionInArtistRouteId_ShouldRemainSecure(string maliciousArtistId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}", request);
// Assert
await AssertCleanValidationErrorAsync(response, maliciousArtistId, "ArtistIdCannotBeEmpty");
}
[Theory]
[InlineData("'; DROP TABLE Albums; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task UpdateAlbum_WithSQLInjectionInAlbumRouteId_ShouldRemainSecure(string maliciousAlbumId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}", request);
// Assert
await AssertCleanValidationErrorAsync(response, maliciousAlbumId, "AlbumIdCannotBeEmpty");
}
[Fact]
public async Task UpdateAlbum_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);
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []);
// Act
HttpResponseMessage response = await requesterClient.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", request);
// 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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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 UpdateAlbum_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);
UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(metadata: _musicAlbumMetadataDtoFixture.Create(title: "Hijacked"), contributors: [], ratings: []);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}", request);
// 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 album is untouched.
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
AlbumEntity? storedAlbum = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == victimAlbumId);
Assert.NotNull(storedAlbum);
Assert.Equal("News of the World", storedAlbum.Title);
}
/// <summary>
/// Asserts that the response is a clean validation problem details that neither leaks internals nor echoes the injected payload.
/// </summary>
/// <param name="response">The HTTP response to assert.</param>
/// <param name="injectedPayload">The injected payload that must never be echoed back.</param>
/// <param name="expectedErrorCode">The validation error code expected in the response.</param>
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);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and one of its albums.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist and album.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <see cref="UpdateAlbumCoverEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateAlbumCoverEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="UpdateAlbumCoverEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<LuminaDbContext>();
AlbumEntity? storedAlbum = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == victimAlbumId);
Assert.NotNull(storedAlbum);
Assert.Equal("News of the World", storedAlbum.Title);
}
/// <summary>
/// Asserts that the response is a clean validation problem details that neither leaks internals nor echoes the injected payload.
/// </summary>
/// <param name="response">The HTTP response to assert.</param>
/// <param name="injectedPayload">The injected payload that must never be echoed back.</param>
/// <param name="expectedErrorCode">The validation error code expected in the response.</param>
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);
}
/// <summary>
/// Creates a multipart form carrying a minimal cover payload with the specified file name.
/// </summary>
/// <param name="fileName">The name of the uploaded file.</param>
/// <returns>A configured <see cref="MultipartFormDataContent"/> instance.</returns>
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;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist and one of its albums.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist and album.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,210 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.AddArtist;
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.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.AddArtist;
/// <summary>
/// Contains security tests for the <see cref="AddArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddArtistEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly AddArtistRequestFixture _addArtistRequestFixture = new();
private readonly MusicArtistMetadataDtoFixture _musicArtistMetadataDtoFixture = new();
private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="AddArtistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AddArtistEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task AddArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AddArtistRequest request = _addArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: "Queen"), contributors: [], albums: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/artists", problemDetails["instance"].GetProperty("value").GetString());
}
[Fact]
public async Task AddArtist_WhenUnauthorized_ShouldNotLeakSensitiveData()
{
// Arrange
AddArtistRequest request = _addArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: "Queen"), contributors: [], albums: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists", request);
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.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task AddArtist_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
AddArtistRequest request = _addArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: "Queen"), contributors: [], albums: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists", request);
// Assert
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(maliciousLibraryId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task AddArtist_WithSQLInjectionInBody_ShouldNotCorruptOrDeleteData(string maliciousName)
{
// Arrange
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
Guid libraryId = await SeedLibraryAsync(userId);
AddAlbumRequest album = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
AddArtistRequest request = _addArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: maliciousName), contributors: [], albums: [album]);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request);
// Assert
// The malicious name passes validation, reaches the parameterized insert, and is persisted verbatim: if it were
// concatenated into raw SQL, the insert would fail and the artist would not be created.
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.Artists.CountAsync(artist => artist.LibraryId == libraryId));
}
[Fact]
public async Task AddArtist_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
_seededUsernames.Add(ownerUsername);
Guid libraryId = await SeedLibraryAsync(ownerId);
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(requesterUsername);
AddAlbumRequest album = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []);
AddArtistRequest request = _addArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: "Queen"), contributors: [], albums: [album]);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,230 @@
#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.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteArtist;
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.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteArtist;
/// <summary>
/// Contains security tests for the <see cref="DeleteArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteArtistEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="DeleteArtistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeleteArtistEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task DeleteArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task DeleteArtist_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task DeleteArtist_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task DeleteArtist_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
Guid otherUserId = await SeedOtherUserAsync();
(Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(otherUserId);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task DeleteArtist_WhenArtistBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutDeletingIt()
{
// 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);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
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<LuminaDbContext>();
Assert.NotNull(await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == victimArtistId));
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return userId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist of that library.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and artist.</returns>
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", 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);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,193 @@
#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.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtist;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtist;
/// <summary>
/// Contains security tests for the <see cref="GetArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetArtistEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetArtist_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}");
// Assert
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(maliciousLibraryId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetArtist_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}");
// Assert
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(maliciousArtistId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task GetArtist_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
Guid otherUserId = await SeedOtherUserAsync();
(Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return userId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist of that library.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and artist.</returns>
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", 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);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,192 @@
#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.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbums;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbums;
/// <summary>
/// Contains security tests for the <see cref="GetArtistAlbumsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistAlbumsEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistAlbumsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetArtistAlbumsEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetArtistAlbums_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetArtistAlbums_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums");
// Assert
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(maliciousLibraryId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetArtistAlbums_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums");
// Assert
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(maliciousArtistId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task GetArtistAlbums_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
Guid otherUserId = await SeedOtherUserAsync();
(Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return userId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist of that library.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and artist.</returns>
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", 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);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,192 @@
#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.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbumsLite;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbumsLite;
/// <summary>
/// Contains security tests for the <see cref="GetArtistAlbumsLiteEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistAlbumsLiteEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistAlbumsLiteEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetArtistAlbumsLiteEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetArtistAlbumsLite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/lite";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetArtistAlbumsLite_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/lite");
// Assert
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(maliciousLibraryId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetArtistAlbumsLite_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/lite");
// Assert
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(maliciousArtistId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task GetArtistAlbumsLite_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
Guid otherUserId = await SeedOtherUserAsync();
(Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/lite");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return userId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist of that library.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and artist.</returns>
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", 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);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,194 @@
#region ========================================================================= USING =====================================================================================
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.GetArtists;
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.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtists;
/// <summary>
/// Contains security tests for the <see cref="GetArtistsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistsEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetArtistsEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetArtists_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task GetArtists_WhenSearchTermContainsSqlInjection_ShouldNotCorruptOrDeleteData(string maliciousSearchTerm)
{
// Arrange
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
Guid libraryId = await SeedLibraryAsync(userId);
await SeedArtistAsync(libraryId, "Queen");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists?searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}");
// Assert
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(maliciousSearchTerm, content, StringComparison.Ordinal);
// The injected statement must never be executed: the Artists table and the seeded rows must still be there.
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.Artists.CountAsync(artist => artist.LibraryId == libraryId));
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetArtists_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists");
// Assert
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(maliciousLibraryId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetArtists_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbiddenResult()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
_seededUsernames.Add(ownerUsername);
Guid libraryId = await SeedLibraryAsync(ownerId);
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(requesterUsername);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds an artist belonging to the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="name">The name of the artist.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedArtistAsync(Guid libraryId, string name)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Artists.Add(_artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,193 @@
#region ========================================================================= USING =====================================================================================
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.GetArtistsLite;
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.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistsLite;
/// <summary>
/// Contains security tests for the <see cref="GetArtistsLiteEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtistsLiteEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetArtistsLiteEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetArtistsLiteEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetArtistsLite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/lite";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task GetArtistsLite_WhenSearchTermContainsSqlInjection_ShouldNotCorruptOrDeleteData(string maliciousSearchTerm)
{
// Arrange
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
Guid libraryId = await SeedLibraryAsync(userId);
await SeedArtistAsync(libraryId, "Queen");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite?searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}");
// Assert
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(maliciousSearchTerm, content, StringComparison.Ordinal);
// The injected statement must never be executed: the Artists table and the seeded rows must still be there.
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.Artists.CountAsync(artist => artist.LibraryId == libraryId));
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetArtistsLite_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/lite");
// Assert
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(maliciousLibraryId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetArtistsLite_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbiddenResult()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
_seededUsernames.Add(ownerUsername);
Guid libraryId = await SeedLibraryAsync(ownerId);
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(requesterUsername);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds an artist belonging to the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="name">The name of the artist.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedArtistAsync(Guid libraryId, string name)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Artists.Add(_artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,145 @@
#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.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetDeletedArtists;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetDeletedArtists;
/// <summary>
/// Contains security tests for the <see cref="GetDeletedArtistsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedArtistsEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private readonly List<string> _seededUsernames = [];
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedArtistsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDeletedArtistsEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetDeletedArtists_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/deleted-items";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetDeletedArtists_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task GetDeletedArtists_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenAndNotLeakTheDeletedArtist()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
const string NAME = "Secret Deleted Artist";
const string COVER_PATH = "/private/deleted-artist-cover.jpg";
Guid libraryId = await SeedLibraryAndDeletedArtistAsync(victimUserId, NAME, COVER_PATH);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/artists/deleted-items");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.DoesNotContain(NAME, content, StringComparison.Ordinal);
Assert.DoesNotContain(COVER_PATH, content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with a deleted artist and its cover.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="name">The name of the deleted artist.</param>
/// <param name="coverPath">The stored cover path of the deleted artist.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAndDeletedArtistAsync(Guid userId, string name, string coverPath)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false);
artist.IsDeleted = true;
artist.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(artist);
dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artist.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: coverPath));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Removes the users created by the tests.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,207 @@
#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.RestoreArtist;
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.Net;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.RestoreArtist;
/// <summary>
/// Contains security tests for the <see cref="RestoreArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreArtistEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private readonly List<string> _seededUsernames = [];
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreArtistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RestoreArtistEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task RestoreArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/restore";
// Act
HttpResponseMessage response = await _client.PostAsync(url, null);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task RestoreArtist_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task RestoreArtist_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task RestoreArtist_WhenArtistBelongsToAnotherUser_ShouldReturnForbiddenAndKeepItDeleted()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
(Guid libraryId, Guid artistId) = await SeedLibraryAndDeletedArtistAsync(victimUserId);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/restore", null);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
ArtistEntity? artist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId);
Assert.NotNull(artist);
Assert.True(artist!.IsDeleted);
}
[Fact]
public async Task RestoreArtist_WhenArtistIsRestoredThroughAnotherLibrary_ShouldReturnNotFoundAndKeepItDeleted()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(actingUsername);
Guid ownLibraryId = await SeedLibraryAsync(actingUserId);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
(_, Guid victimArtistId) = await SeedLibraryAndDeletedArtistAsync(victimUserId);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/restore", null);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
ArtistEntity? victimArtist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == victimArtistId);
Assert.NotNull(victimArtist);
Assert.True(victimArtist!.IsDeleted);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Acting Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with a deleted artist.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and artist.</returns>
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndDeletedArtistAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Victim Artist", includeAlbums: false, includeContributors: false);
artist.IsDeleted = true;
artist.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(artist);
await dbContext.SaveChangesAsync();
return (libraryId, artist.Id);
}
/// <summary>
/// Removes the users created by the tests.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,312 @@
#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.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtist;
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.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtist;
/// <summary>
/// Contains security tests for the <see cref="UpdateArtistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateArtistEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly UpdateArtistRequestFixture _updateArtistRequestFixture = new();
private readonly MusicArtistMetadataDtoFixture _musicArtistMetadataDtoFixture = new();
private readonly UpdateArtistAlbumRequestFixture _updateArtistAlbumRequestFixture = new();
private readonly MusicAlbumMetadataDtoFixture _musicAlbumMetadataDtoFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdateArtistEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task UpdateArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
UpdateArtistRequest request = _updateArtistRequestFixture.Create();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
Assert.NotNull(problemDetails);
Assert.Equal(401, 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}", problemDetails["instance"].GetProperty("value").GetString());
}
[Fact]
public async Task UpdateArtist_WhenUnauthorized_ShouldNotLeakSensitiveData()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
UpdateArtistRequest request = _updateArtistRequestFixture.Create();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}", request);
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 UpdateArtist_WithSQLInjectionInBody_ShouldNotCorruptOrLeakData(string maliciousName)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
Guid libraryId = Guid.NewGuid();
(Guid artistId, Guid albumId) = await SeedArtistAsync(libraryId, userId);
UpdateArtistAlbumRequest album = _updateArtistAlbumRequestFixture.Create(
albumId: albumId,
metadata: _musicAlbumMetadataDtoFixture.Create(title: "Updated Album"),
contributors: [],
ratings: [],
tracks: []);
UpdateArtistRequest request = _updateArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: maliciousName), contributors: [], albums: [album]);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}", request);
// Assert
// The malicious name passes validation, reaches the parameterized update, and is persisted verbatim: if it were
// concatenated into raw SQL, the update would fail and the artist would not be updated.
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
ArtistEntity? storedArtist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId);
Assert.NotNull(storedArtist);
Assert.Equal(maliciousName, storedArtist!.Name);
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task UpdateArtist_WithSQLInjectionInLibraryRouteId_ShouldRemainSecure(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
UpdateArtistRequest request = _updateArtistRequestFixture.Create();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}", request);
// Assert
await AssertCleanValidationErrorAsync(response, maliciousLibraryId, "LibraryIdCannotBeEmpty");
}
[Theory]
[InlineData("'; DROP TABLE Artists; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task UpdateArtist_WithSQLInjectionInArtistRouteId_ShouldRemainSecure(string maliciousArtistId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
UpdateArtistRequest request = _updateArtistRequestFixture.Create();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}", request);
// Assert
await AssertCleanValidationErrorAsync(response, maliciousArtistId, "ArtistIdCannotBeEmpty");
}
[Fact]
public async Task UpdateArtist_WhenArtistDoesNotExist_ShouldReturnNotFoundWithoutLeakingInternals()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
Guid libraryId = Guid.NewGuid();
UpdateArtistRequest request = _updateArtistRequestFixture.Create();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}", request);
// 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 UpdateArtist_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
_seededUsernames.Add(ownerUsername);
Guid libraryId = Guid.NewGuid();
(Guid artistId, _) = await SeedArtistAsync(libraryId, ownerId);
HttpClient requesterClient = _apiFactory.CreateClient();
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
_seededUsernames.Add(requesterUsername);
UpdateArtistRequest request = _updateArtistRequestFixture.Create();
// Act
HttpResponseMessage response = await requesterClient.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}", request);
// 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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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 UpdateArtist_WhenArtistBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutLeakingOrModifyingIt()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(actingUsername);
Guid ownLibraryId = Guid.NewGuid();
await SeedArtistAsync(ownLibraryId, 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 victimLibraryId = Guid.NewGuid();
(Guid victimArtistId, _) = await SeedArtistAsync(victimLibraryId, victimUserId);
UpdateArtistRequest request = _updateArtistRequestFixture.Create(metadata: _musicArtistMetadataDtoFixture.Create(name: "Hijacked"), contributors: [], albums: []);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}", request);
// 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<LuminaDbContext>();
ArtistEntity? storedArtist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == victimArtistId);
Assert.NotNull(storedArtist);
Assert.Equal("Queen", storedArtist.Name);
}
/// <summary>
/// Asserts that the response is a clean validation problem details that neither leaks internals nor echoes the injected payload.
/// </summary>
/// <param name="response">The HTTP response to assert.</param>
/// <param name="injectedPayload">The injected payload that must never be echoed back.</param>
/// <param name="expectedErrorCode">The validation error code expected in the response.</param>
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);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist that owns one album.
/// </summary>
/// <param name="libraryId">The Id of the media library to seed.</param>
/// <param name="userId">The Id of the user that owns the media library.</param>
/// <returns>The Ids of the seeded artist and of its album.</returns>
private async Task<(Guid artistId, Guid albumId)> SeedArtistAsync(Guid libraryId, Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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: "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 (artistId, albumId);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <see cref="UpdateArtistCoverEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateArtistCoverEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="UpdateArtistCoverEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<LuminaDbContext>();
ArtistEntity? storedArtist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == victimArtistId);
Assert.NotNull(storedArtist);
Assert.Equal("Queen", storedArtist.Name);
}
/// <summary>
/// Asserts that the response is a clean validation problem details that neither leaks internals nor echoes the injected payload.
/// </summary>
/// <param name="response">The HTTP response to assert.</param>
/// <param name="injectedPayload">The injected payload that must never be echoed back.</param>
/// <param name="expectedErrorCode">The validation error code expected in the response.</param>
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);
}
/// <summary>
/// Creates a multipart form carrying a minimal cover payload with the specified file name.
/// </summary>
/// <param name="fileName">The name of the uploaded file.</param>
/// <returns>A configured <see cref="MultipartFormDataContent"/> instance.</returns>
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;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and artist.</returns>
private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,337 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
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.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
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.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.AddTrack;
/// <summary>
/// Contains security tests for the <see cref="AddTrackEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly AddTrackRequestFixture _addTrackRequestFixture = new();
private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new();
private readonly GenreDtoFixture _genreDtoFixture = new();
private readonly TagDtoFixture _tagDtoFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TagEntityFixture _tagEntityFixture = new();
private readonly GenreEntityFixture _genreEntityFixture = new();
private readonly List<string> _seededUsernames = [];
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly string _libraryContentLocation = Path.GetTempPath();
/// <summary>
/// Initializes a new instance of the <see cref="AddTrackEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AddTrackEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task AddTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
AddTrackRequest request = _addTrackRequestFixture.Create(contributors: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks", problemDetails["instance"].GetProperty("value").GetString());
}
[Fact]
public async Task AddTrack_WhenUnauthorized_ShouldNotLeakSensitiveData()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AddTrackRequest request = _addTrackRequestFixture.Create(contributors: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks", request);
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);
}
[Fact]
public async Task AddTrack_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);
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(requesterUsername);
AddTrackRequest request = _addTrackRequestFixture.Create(contributors: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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 AddTrack_WhenArtistBelongsToAnotherLibrary_ShouldNotDiscloseCrossLibraryData()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
_seededUsernames.Add(ownerUsername);
(Guid ownerLibraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(ownerId);
(Guid attackerId, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(attackerUsername);
Guid attackerLibraryId = Guid.NewGuid();
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
{
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
seedDbContext.Libraries.Add(_libraryEntityFixture.Create(id: attackerLibraryId, userId: attackerId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: [_libraryContentLocation]));
await seedDbContext.SaveChangesAsync();
}
AddTrackRequest request = _addTrackRequestFixture.Create(contributors: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{attackerLibraryId}/artists/{artistId}/albums/{albumId}/tracks", request);
// Assert
// The artist exists in another library, but the mismatch is reported as not found, without disclosing that it exists elsewhere.
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.Contains("ArtistNotFound", content, StringComparison.Ordinal);
Assert.DoesNotContain(ownerLibraryId.ToString(), content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task AddTrack_WithSQLInjectionInPath_ShouldNotCorruptOrDeleteData(string maliciousPath)
{
// Arrange
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
string injectedPath = Path.Combine(_libraryContentLocation, $"{maliciousPath}.flac");
AddTrackRequest request = _addTrackRequestFixture.Create(path: injectedPath, contributors: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks", request);
// Assert
// The malicious path passes the authenticated handler, reaches the parameterized insert, and is persisted
// verbatim: if it were concatenated into raw SQL, the insert would fail and the track would not be created.
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.Libraries.CountAsync(library => library.Id == libraryId));
TrackEntity storedTrack = await dbContext.Tracks.SingleAsync(track => track.LibraryId == libraryId);
Assert.Equal(injectedPath, storedTrack.Path);
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task AddTrack_WithSQLInjectionInBody_ShouldNotCorruptOrDeleteData(string maliciousTitle)
{
// Arrange
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
AddTrackRequest request = _addTrackRequestFixture.Create(
path: Path.Combine(_libraryContentLocation, $"{Guid.NewGuid():N}.flac"),
metadata: _musicTrackMetadataDtoFixture.Create(title: maliciousTitle),
contributors: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks", request);
// Assert
// The malicious title passes the authenticated handler, reaches the parameterized insert, and is persisted
// verbatim: if it were concatenated into raw SQL, the insert would fail and the track would not be created.
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
TrackEntity storedTrack = await dbContext.Tracks.SingleAsync(track => track.LibraryId == libraryId);
Assert.Equal(maliciousTitle, storedTrack.Title);
}
[Theory]
[InlineData("'; DROP TABLE Tags; --")] // Destructive injection in a tag and genre name.
[InlineData("' OR '1'='1")] // Boolean-based injection in a tag and genre name.
public async Task AddTrack_WithSQLInjectionInTagAndGenreNames_ShouldNotCorruptOrLeakData(string maliciousName)
{
// Arrange
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
string suffix = Guid.NewGuid().ToString("N")[..8];
string seededTagName = $"seeded-tag-{suffix}";
string seededGenreName = $"seeded-genre-{suffix}";
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
{
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
seedDbContext.Set<TagEntity>().Add(_tagEntityFixture.Create(name: seededTagName));
seedDbContext.Set<GenreEntity>().Add(_genreEntityFixture.Create(name: seededGenreName));
await seedDbContext.SaveChangesAsync();
}
string injectedTagName = $"{maliciousName} {suffix}";
string injectedGenreName = $"{maliciousName} genre {suffix}";
AddTrackRequest request = _addTrackRequestFixture.Create(
path: Path.Combine(_libraryContentLocation, $"{Guid.NewGuid():N}.flac"),
metadata: _musicTrackMetadataDtoFixture.Create(
genres: [_genreDtoFixture.Create(name: injectedGenreName)],
tags: [_tagDtoFixture.Create(name: injectedTagName)]),
contributors: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks", request);
string content = await response.Content.ReadAsStringAsync();
// Assert
// The malicious names are user data, not SQL: they must be stored verbatim (normalized) without breaking the request or the schema.
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.DoesNotContain("SQL", content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("StackTrace", content, StringComparison.OrdinalIgnoreCase);
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.Libraries.CountAsync(library => library.Id == libraryId));
Assert.Equal(1, await dbContext.Tracks.CountAsync(track => track.LibraryId == libraryId));
Assert.True(await dbContext.Set<TagEntity>().AnyAsync(tag => tag.Name == seededTagName));
Assert.True(await dbContext.Set<GenreEntity>().AnyAsync(genre => genre.Name == seededGenreName));
Assert.True(await dbContext.Set<TagEntity>().AnyAsync(tag => tag.Name == injectedTagName.ToLowerInvariant()));
Assert.True(await dbContext.Set<GenreEntity>().AnyAsync(genre => genre.Name == injectedGenreName.ToLowerInvariant()));
}
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task AddTrack_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
AddTrackRequest request = _addTrackRequestFixture.Create(contributors: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks", request);
// Assert
// The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the command
// validator, which reports it as a clean validation error. The response must not leak stack traces, database details,
// or the injected payload.
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(maliciousLibraryId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, along with one artist and one album of that library.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist and album.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [_libraryContentLocation]));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false));
await dbContext.SaveChangesAsync();
return (libraryId, artistId, albumId);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,350 @@
#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.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteTrack;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteTrack;
/// <summary>
/// Contains security tests for the <see cref="DeleteTrackEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="DeleteTrackEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeleteTrackEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task DeleteTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task DeleteTrack_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
// Assert
// The route value is kept as a raw string, so the unparseable Id reaches the command validator, which reports a clean
// validation error instead of failing the request binding.
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("testuser_", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task DeleteTrack_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
// Assert
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("testuser_", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task DeleteTrack_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks/{Guid.NewGuid()}");
// Assert
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("testuser_", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task DeleteTrack_WithSQLInjectionInTrackId_ShouldNotCorruptOrLeakData(string maliciousTrackId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Uri.EscapeDataString(maliciousTrackId)}");
// Assert
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("testuser_", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("..%2F..%2Fevil")] // Encoded slash traversal.
[InlineData("%2e%2e%2f%2e%2e%2fevil")] // Encoded dot-slash traversal.
[InlineData("..%5Cevil")] // Encoded backslash traversal.
[InlineData("..%2F")] // Encoded trailing slash traversal.
public async Task DeleteTrack_WithPathTraversalInTrackId_ShouldReturnCleanProblemDetails(string maliciousTrackId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{maliciousTrackId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
// Some payloads are normalized away by the server before routing, producing an empty-body response, while others reach the handler and
// produce a clean problem details; either way, the status is asserted unconditionally, so an empty-bodied 500 cannot satisfy the test.
Assert.True(response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.UnprocessableEntity,
$"Unexpected status code {response.StatusCode}.");
Assert.NotEqual(StatusCodes.Status500InternalServerError, (int)response.StatusCode);
// When the payload reaches the handler, the failure must still be a clean, generic problem.
if (!string.IsNullOrWhiteSpace(content))
{
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.NotEmpty(problemDetails.RootElement.ToString());
}
}
[Fact]
public async Task DeleteTrack_WhenTrackBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
Guid otherUserId = await SeedOtherUserAsync();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task DeleteTrack_WhenTrackBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutDeletingIt()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(actingUsername);
(Guid ownLibraryId, _, _, _) = await SeedLibraryArtistAlbumAndTrackAsync(actingUserId);
// The track 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, Guid victimTrackId) = await SeedLibraryArtistAlbumAndTrackAsync(victimUserId);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}/tracks/{victimTrackId}");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
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 track is untouched.
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.NotNull(await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == victimTrackId));
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return userId;
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
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);
TrackEntity track = _trackEntityFixture.Create(
id: trackId,
albumId: albumId,
libraryId: libraryId,
path: $"/music/queen/we-are-the-champions-{Guid.NewGuid():N}.flac",
title: "We Are the Champions",
includeMetadata: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
dbContext.Albums.Add(album);
dbContext.Tracks.Add(track);
await dbContext.SaveChangesAsync();
return (libraryId, artistId, albumId, trackId);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,166 @@
#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.Tracks.GetDeletedTracks;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetDeletedTracks;
/// <summary>
/// Contains security tests for the <see cref="GetDeletedTracksEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedTracksEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private readonly List<string> _seededUsernames = [];
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedTracksEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDeletedTracksEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetDeletedTracks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/tracks/deleted-items";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetDeletedTracks_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/tracks/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task GetDeletedTracks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenAndNotLeakTheDeletedTrack()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
const string TITLE = "Secret Deleted Track";
const string PATH = "/private/secret-deleted-track.flac";
Guid libraryId = await SeedLibraryAndDeletedTrackAsync(victimUserId, TITLE, PATH);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/tracks/deleted-items");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.DoesNotContain(TITLE, content, StringComparison.Ordinal);
Assert.DoesNotContain(PATH, content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with a deleted track, its album and its artist.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="title">The title of the deleted track.</param>
/// <param name="path">The file system path of the deleted track.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAndDeletedTrackAsync(Guid userId, string title, string path)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(
albumId: albumId,
libraryId: libraryId,
path: path,
title: title,
includeMetadata: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
track.IsDeleted = true;
track.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5);
AlbumEntity album = _albumEntityFixture.Create(
artistId: artistId,
libraryId: libraryId,
title: "Victim Album",
tracks: [track],
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Victim Artist", albums: [album], includeContributors: false));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Removes the users created by the tests.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,280 @@
#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.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrack;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrack;
/// <summary>
/// Contains security tests for the <see cref="GetTrackEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetTrackEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetTrackEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetTrack_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
// Assert
// The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean validation error instead of failing the request binding.
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(maliciousLibraryId, content, StringComparison.Ordinal);
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetTrack_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
// Assert
// The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean validation error instead of failing the request binding.
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(maliciousArtistId, content, StringComparison.Ordinal);
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetTrack_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks/{Guid.NewGuid()}");
// Assert
// The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean
// validation error instead of failing the request binding.
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(maliciousAlbumId, content, StringComparison.Ordinal);
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetTrack_WithSQLInjectionInTrackId_ShouldNotCorruptOrLeakData(string maliciousTrackId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Uri.EscapeDataString(maliciousTrackId)}");
// Assert
// The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean validation error instead of failing the request binding.
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(maliciousTrackId, content, StringComparison.Ordinal);
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task GetTrack_WhenTrackBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
Guid otherUserId = await SeedOtherUserAsync();
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return userId;
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false));
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);
TrackEntity track = _trackEntityFixture.Create(
id: trackId,
albumId: albumId,
libraryId: libraryId,
path: $"/music/queen/we-are-the-champions-{Guid.NewGuid():N}.flac",
title: "We Are the Champions",
includeMetadata: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
dbContext.Albums.Add(album);
dbContext.Tracks.Add(track);
await dbContext.SaveChangesAsync();
return (libraryId, artistId, albumId, trackId);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,316 @@
#region ========================================================================= USING =====================================================================================
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.Playback;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackSegment;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
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.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackSegment;
/// <summary>
/// Contains security tests for the <see cref="GetTrackSegmentEndpoint"/> class.
/// </summary>
/// <remarks>
/// The concurrency rate limiter of the segment route is not exercised, because it requires four concurrent long lived streams, which needs a real
/// normalization pipeline and ffmpeg, neither of which is available in the test environment.
/// </remarks>
[ExcludeFromCodeCoverage]
public class GetTrackSegmentEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const int DEFAULT_SEGMENT_INDEX = 0;
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly string _contentRootPath = Path.Combine(Path.GetTempPath(), $"lumina-track-segment-security-tests-{Guid.NewGuid():N}");
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter() }
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetTrackSegmentEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetTrackSegmentEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
Directory.CreateDirectory(_contentRootPath);
}
[Fact]
public async Task GetTrackSegment_WhenCalledWithoutCredentials_ShouldReturnUnauthorizedResult()
{
// Act
HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid().ToString("N"), 0));
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("Unauthorized", problemDetails!["title"].GetString());
}
[Theory]
[InlineData("libraryId", "'; DROP TABLE Tracks; --")] // Destructive injection in the library Id.
[InlineData("libraryId", "' OR '1'='1")] // Boolean based injection in the library Id.
[InlineData("artistId", "'; DROP TABLE Tracks; --")] // Destructive injection in the artist Id.
[InlineData("artistId", "'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt in the artist Id.
[InlineData("albumId", "' OR '1'='1")] // Boolean based injection in the album Id.
[InlineData("albumId", "'; DROP TABLE Tracks; --")] // Destructive injection in the album Id.
[InlineData("trackId", "' OR '1'='1")] // Boolean based injection in the track Id.
[InlineData("trackId", "'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt in the track Id.
[InlineData("deliveryId", "'; DROP TABLE Tracks; --")] // Destructive injection in the delivery handle.
[InlineData("deliveryId", "' OR '1'='1")] // Boolean based injection in the delivery handle.
[InlineData("segmentIndex", "'; DROP TABLE Tracks; --")] // Destructive injection in the segment index.
[InlineData("segmentIndex", "' OR '1'='1")] // Boolean based injection in the segment index.
[InlineData("libraryId", "../../etc/passwd")] // Path traversal in the library Id.
[InlineData("artistId", "../../etc/passwd")] // Path traversal in the artist Id.
[InlineData("albumId", "../../etc/passwd")] // Path traversal in the album Id.
[InlineData("trackId", "../../etc/passwd")] // Path traversal in the track Id.
[InlineData("deliveryId", "../../etc/passwd")] // Path traversal in the delivery handle.
[InlineData("segmentIndex", "../../etc/passwd")] // Path traversal in the segment index.
public async Task GetTrackSegment_WithAnInjectionPayloadInARouteValue_ShouldNotFailOrLeakData(string routeValue, string payload)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
string path = BuildSegmentPathWithPayload(routeValue, payload);
// Act
HttpResponseMessage response = await _client.GetAsync(path);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
Assert.DoesNotContain("/etc/passwd", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("C:\\", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetTrackSegment_WhenDeliveryIdIsWellFormedButUnknown_ShouldReturnGenericNotFound()
{
// Arrange
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// A library owned by the authenticated user keeps the ownership check passing, so the unknown handle is what rejects the request.
Guid libraryId = await SeedLibraryAsync(userId);
string unknownDeliveryId = Guid.NewGuid().ToString("N");
// Act
HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(libraryId, Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), unknownDeliveryId, 0));
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.NotFound", problemDetails!.Title);
Assert.Equal("PlaybackDeliveryNotFound", problemDetails.Detail);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetTrackSegment_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenWithoutLeakingTheTrackPath()
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
Guid otherUserId = await SeedOtherUserAsync();
string secretTrackPath = Path.Combine(_contentRootPath, $"secret-{Guid.NewGuid():N}.flac");
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId, secretTrackPath);
// Act
HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(libraryId, artistId, albumId, trackId, Guid.NewGuid().ToString("N"), 0));
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.DoesNotContain("secret-", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(secretTrackPath, content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.Unauthorized", problemDetails!["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
}
[Fact]
public async Task GetTrackSegment_WhenManifestHandleIsUsedForAnotherTrack_ShouldReturnNotFound()
{
// Arrange
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
string trackPath = Path.Combine(_contentRootPath, $"delivered-{Guid.NewGuid():N}.ogg");
await File.WriteAllBytesAsync(trackPath, [1, 2, 3, 4, 5, 6, 7, 8]);
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
string deliveryId = await GetDeliveryIdAsync(libraryId, artistId, albumId, trackId);
Guid otherTrackId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.GetAsync(BuildSegmentPath(libraryId, artistId, albumId, otherTrackId, deliveryId, 0));
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.NotFound", problemDetails!.Title);
Assert.Equal("PlaybackDeliveryNotFound", problemDetails.Detail);
Assert.DoesNotContain(trackPath, content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return userId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="trackPath">The file system path of the audio file of the track.</param>
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId, string trackPath)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [_contentRootPath]));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen"));
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera"));
dbContext.Tracks.Add(_trackEntityFixture.Create(
id: trackId,
albumId: albumId,
libraryId: libraryId,
path: trackPath,
container: "OGG",
audioCodec: "OPUS",
title: "A Track",
includeMetadata: false));
await dbContext.SaveChangesAsync();
return (libraryId, artistId, albumId, trackId);
}
/// <summary>
/// Requests a transcoded playback manifest for the seeded track and returns the delivery handle it reports.
/// </summary>
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
/// <param name="artistId">The Id of the artist the album belongs to.</param>
/// <param name="albumId">The Id of the album the track belongs to.</param>
/// <param name="trackId">The Id of the track.</param>
/// <returns>The delivery handle of the normalized delivery.</returns>
private async Task<string> GetDeliveryIdAsync(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
{
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest?capabilities=mp3/mp3");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
PlaybackManifestResponse? manifest = JsonSerializer.Deserialize<PlaybackManifestResponse>(content, _jsonOptions);
Assert.NotNull(manifest);
Assert.NotNull(manifest!.DeliveryId);
return manifest.DeliveryId;
}
/// <summary>
/// Builds the route of a single segment of the normalized audio of a track.
/// </summary>
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
/// <param name="artistId">The Id of the artist the album belongs to.</param>
/// <param name="albumId">The Id of the album the track belongs to.</param>
/// <param name="trackId">The Id of the track.</param>
/// <param name="deliveryId">The opaque handle of the normalized delivery.</param>
/// <param name="segmentIndex">The zero based index of the segment.</param>
/// <returns>The route of the requested segment.</returns>
private static string BuildSegmentPath(Guid libraryId, Guid artistId, Guid albumId, Guid trackId, string deliveryId, int segmentIndex)
{
return $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex}";
}
/// <summary>
/// Builds the route of a single segment of the normalized audio of a track, with a malicious payload in one of its route values.
/// </summary>
/// <param name="routeValue">The name of the route value that carries the payload.</param>
/// <param name="payload">The malicious payload.</param>
/// <returns>The route of the requested segment, with the payload URL-escaped.</returns>
private static string BuildSegmentPathWithPayload(string routeValue, string payload)
{
string libraryId = routeValue == "libraryId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString();
string artistId = routeValue == "artistId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString();
string albumId = routeValue == "albumId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString();
string trackId = routeValue == "trackId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString();
string deliveryId = routeValue == "deliveryId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString("N");
string segmentIndex = routeValue == "segmentIndex" ? Uri.EscapeDataString(payload) : DEFAULT_SEGMENT_INDEX.ToString();
return $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex}";
}
/// <summary>
/// Disposes the API factory resources, the seeded users and the temporary files of the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
if (Directory.Exists(_contentRootPath))
Directory.Delete(_contentRootPath, recursive: true);
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,380 @@
#region ========================================================================= USING =====================================================================================
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.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackStream;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackStream;
/// <summary>
/// Contains security tests for the <see cref="GetTrackStreamEndpoint"/> class.
/// </summary>
/// <remarks>
/// The concurrency rate limiter of the stream route is not exercised, because it requires four concurrent long lived streams, which needs a real
/// normalization pipeline and ffmpeg, neither of which is available in the test environment.
/// </remarks>
[ExcludeFromCodeCoverage]
public class GetTrackStreamEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string ACTIVE_CONTENT_BODY = "<html><body><script>alert('active')</script></body></html>";
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly string _contentRootPath = Path.Combine(Path.GetTempPath(), $"lumina-track-stream-security-tests-{Guid.NewGuid():N}");
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _temporaryFiles = [];
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetTrackStreamEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetTrackStreamEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
Directory.CreateDirectory(_contentRootPath);
}
[Fact]
public async Task GetTrackStream_WhenCalledWithoutCredentials_ShouldReturnUnauthorizedResult()
{
// Act
HttpResponseMessage response = await _client.GetAsync(BuildStreamPath(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()));
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("Unauthorized", problemDetails!["title"].GetString());
}
[Theory]
[InlineData("libraryId", "'; DROP TABLE Tracks; --")] // Destructive injection in the library Id.
[InlineData("libraryId", "' OR '1'='1")] // Boolean based injection in the library Id.
[InlineData("artistId", "'; DROP TABLE Tracks; --")] // Destructive injection in the artist Id.
[InlineData("artistId", "'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt in the artist Id.
[InlineData("albumId", "' OR '1'='1")] // Boolean based injection in the album Id.
[InlineData("albumId", "'; DROP TABLE Tracks; --")] // Destructive injection in the album Id.
[InlineData("trackId", "' OR '1'='1")] // Boolean based injection in the track Id.
[InlineData("trackId", "'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt in the track Id.
[InlineData("libraryId", "../../etc/passwd")] // Path traversal in the library Id.
[InlineData("artistId", "../../etc/passwd")] // Path traversal in the artist Id.
[InlineData("albumId", "../../etc/passwd")] // Path traversal in the album Id.
[InlineData("trackId", "../../etc/passwd")] // Path traversal in the track Id.
public async Task GetTrackStream_WithAnInjectionPayloadInARouteValue_ShouldRejectItWithoutLeakingData(string routeValue, string payload)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
string path = BuildStreamPathWithPayload(routeValue, payload);
// Act
HttpResponseMessage response = await _client.GetAsync(path);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
Assert.DoesNotContain("/etc/passwd", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("C:\\", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetTrackStream_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenWithoutLeakingTheTrackPath()
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
Guid otherUserId = await SeedOtherUserAsync();
string secretTrackPath = WriteContentFile($"secret-{Guid.NewGuid():N}.flac", [1, 2, 3, 4]);
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId, secretTrackPath);
// Act
HttpResponseMessage response = await _client.GetAsync(BuildStreamPath(libraryId, artistId, albumId, trackId));
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.DoesNotContain("secret-", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(secretTrackPath, content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.Unauthorized", problemDetails!["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
}
[Fact]
public async Task GetTrackStream_WhenTrackIsRequestedThroughAnotherAlbum_ShouldReturnTrackNotFound()
{
// Arrange
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
string trackPath = WriteContentFile($"track-{Guid.NewGuid():N}.mp3", [1, 2, 3, 4]);
(Guid libraryId, Guid artistId, _, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
Guid otherAlbumId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.GetAsync(BuildStreamPath(libraryId, artistId, otherAlbumId, trackId));
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.DoesNotContain(trackPath, content, StringComparison.OrdinalIgnoreCase);
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.NotFound", problemDetails!.Title);
Assert.Equal("TrackNotFound", problemDetails.Detail);
}
[Fact]
public async Task GetTrackStream_WhenTrackIsRequestedThroughAnotherArtist_ShouldReturnTrackNotFound()
{
// Arrange
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
string trackPath = WriteContentFile($"track-{Guid.NewGuid():N}.mp3", [1, 2, 3, 4]);
(Guid libraryId, _, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
Guid otherArtistId = Guid.NewGuid();
// Act
HttpResponseMessage response = await _client.GetAsync(BuildStreamPath(libraryId, otherArtistId, albumId, trackId));
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.NotFound", problemDetails!.Title);
Assert.Equal("TrackNotFound", problemDetails.Detail);
}
[Fact]
public async Task GetTrackStream_WhenTrackIsRequestedThroughAnotherLibraryOwnedByTheSameUser_ShouldReturnTrackNotFound()
{
// Arrange
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
string trackPath = WriteContentFile($"track-{Guid.NewGuid():N}.mp3", [1, 2, 3, 4]);
(_, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
Guid otherLibraryId = await SeedEmptyLibraryAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync(BuildStreamPath(otherLibraryId, artistId, albumId, trackId));
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("TrackNotFound", problemDetails!.Detail);
}
[Fact]
public async Task GetTrackStream_WhenAudioFileIsOutsideTheLibraryContentLocations_ShouldReturnTrackFileNotFoundWithoutLeakingThePath()
{
// Arrange
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
string outsideFilePath = Path.Combine(Path.GetTempPath(), $"lumina-track-stream-outside-{Guid.NewGuid():N}.mp3");
await File.WriteAllBytesAsync(outsideFilePath, [1, 2, 3, 4]);
_temporaryFiles.Add(outsideFilePath);
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, outsideFilePath);
// Act
HttpResponseMessage response = await _client.GetAsync(BuildStreamPath(libraryId, artistId, albumId, trackId));
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.DoesNotContain(outsideFilePath, content, StringComparison.OrdinalIgnoreCase);
Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize<Microsoft.AspNetCore.Mvc.ProblemDetails>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal("General.NotFound", problemDetails!.Title);
Assert.Equal("TrackFileNotFound", problemDetails.Detail);
}
[Fact]
public async Task GetTrackStream_WhenTheAudioFileHasAnActiveContentExtension_ShouldServeItAsOpaqueContentWithSniffingDisabled()
{
// Arrange
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
string activeContentPath = WriteContentFile($"active-{Guid.NewGuid():N}.html", System.Text.Encoding.UTF8.GetBytes(ACTIVE_CONTENT_BODY));
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, activeContentPath);
// Act
HttpResponseMessage response = await _client.GetAsync(BuildStreamPath(libraryId, artistId, albumId, trackId));
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("application/octet-stream", response.Content.Headers.ContentType?.MediaType);
Assert.NotEqual("text/html", response.Content.Headers.ContentType?.MediaType);
Assert.Contains("nosniff", response.Headers.GetValues("X-Content-Type-Options"));
Assert.Contains("private", response.Headers.CacheControl?.ToString());
Assert.Contains("Authorization", response.Headers.Vary);
Assert.Null(response.Content.Headers.ContentDisposition);
}
[Fact]
public async Task GetTrackStream_WhenTheTrackBelongsToAnOwnedLibrary_ShouldServeItPrivatelyWithoutADownloadName()
{
// Arrange
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
string trackPath = WriteContentFile($"owned-{Guid.NewGuid():N}.mp3", [1, 2, 3, 4, 5, 6, 7, 8]);
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath);
// Act
HttpResponseMessage response = await _client.GetAsync(BuildStreamPath(libraryId, artistId, albumId, trackId));
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("audio/mpeg", response.Content.Headers.ContentType?.MediaType);
Assert.NotNull(response.Headers.ETag);
Assert.NotNull(response.Content.Headers.LastModified);
Assert.Contains("private", response.Headers.CacheControl?.ToString());
Assert.DoesNotContain("public", response.Headers.CacheControl?.ToString());
Assert.Contains("Authorization", response.Headers.Vary);
Assert.Null(response.Content.Headers.ContentDisposition);
Assert.DoesNotContain(trackPath, response.Headers.ETag!.Tag.ToString(), StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return userId;
}
/// <summary>
/// Seeds an empty music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedEmptyLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Other Library", libraryType: LibraryType.Music, contentLocations: [_contentRootPath]));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="trackPath">The file system path of the audio file of the track.</param>
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId, string trackPath)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [_contentRootPath]));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen"));
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera"));
dbContext.Tracks.Add(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: trackPath, title: "A Track", includeMetadata: false));
await dbContext.SaveChangesAsync();
return (libraryId, artistId, albumId, trackId);
}
/// <summary>
/// Writes a file with the provided <paramref name="contentBytes"/> inside the content root of the test, and returns its full path.
/// </summary>
/// <param name="fileName">The name of the file to write.</param>
/// <param name="contentBytes">The bytes of the file to write.</param>
/// <returns>The full path of the written file.</returns>
private string WriteContentFile(string fileName, byte[] contentBytes)
{
string filePath = Path.Combine(_contentRootPath, fileName);
File.WriteAllBytes(filePath, contentBytes);
return filePath;
}
/// <summary>
/// Builds the route of the direct stream of a track.
/// </summary>
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
/// <param name="artistId">The Id of the artist the album belongs to.</param>
/// <param name="albumId">The Id of the album the track belongs to.</param>
/// <param name="trackId">The Id of the track.</param>
/// <returns>The route of the requested stream.</returns>
private static string BuildStreamPath(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
{
return $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream";
}
/// <summary>
/// Builds the route of the direct stream of a track, with a malicious payload in one of its route values.
/// </summary>
/// <param name="routeValue">The name of the route value that carries the payload.</param>
/// <param name="payload">The malicious payload.</param>
/// <returns>The route of the requested stream, with the payload URL-escaped.</returns>
private static string BuildStreamPathWithPayload(string routeValue, string payload)
{
string libraryId = routeValue == "libraryId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString();
string artistId = routeValue == "artistId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString();
string albumId = routeValue == "albumId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString();
string trackId = routeValue == "trackId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString();
return $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream";
}
/// <summary>
/// Disposes the API factory resources, the seeded users and the temporary files of the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
if (Directory.Exists(_contentRootPath))
Directory.Delete(_contentRootPath, recursive: true);
foreach (string temporaryFile in _temporaryFiles)
if (File.Exists(temporaryFile))
File.Delete(temporaryFile);
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,271 @@
#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.Tracks.RestoreTrack;
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.Net;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.RestoreTrack;
/// <summary>
/// Contains security tests for the <see cref="RestoreTrackEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private readonly List<string> _seededUsernames = [];
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreTrackEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RestoreTrackEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task RestoreTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/restore";
// Act
HttpResponseMessage response = await _client.PostAsync(url, null);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task RestoreTrack_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/restore", null);
// Assert
await AssertRejectedInjectionAttemptAsync(response);
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task RestoreTrack_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/restore", null);
// Assert
await AssertRejectedInjectionAttemptAsync(response);
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task RestoreTrack_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks/{Guid.NewGuid()}/restore", null);
// Assert
await AssertRejectedInjectionAttemptAsync(response);
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task RestoreTrack_WithSQLInjectionInTrackId_ShouldNotCorruptOrLeakData(string maliciousTrackId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Uri.EscapeDataString(maliciousTrackId)}/restore", null);
// Assert
await AssertRejectedInjectionAttemptAsync(response);
}
[Fact]
public async Task RestoreTrack_WhenTrackBelongsToAnotherUser_ShouldReturnForbiddenAndKeepItDeleted()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndDeletedTrackAsync(victimUserId);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/restore", null);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
TrackEntity? track = await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId);
Assert.NotNull(track);
Assert.True(track!.IsDeleted);
}
[Fact]
public async Task RestoreTrack_WhenTrackIsRestoredThroughAnotherLibrary_ShouldReturnNotFoundAndKeepItDeleted()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(actingUsername);
Guid ownLibraryId = await SeedLibraryAsync(actingUserId);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
(_, Guid victimArtistId, Guid victimAlbumId, Guid victimTrackId) = await SeedLibraryArtistAlbumAndDeletedTrackAsync(victimUserId);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}/tracks/{victimTrackId}/restore", null);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
TrackEntity? victimTrack = await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == victimTrackId);
Assert.NotNull(victimTrack);
Assert.True(victimTrack!.IsDeleted);
}
/// <summary>
/// Asserts that a route parameter carrying an injection payload is rejected as a validation error, without leaking internal details.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private async Task AssertRejectedInjectionAttemptAsync(HttpResponseMessage response)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Acting Library", libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>, together with an artist, an album and a deleted track of that album.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndDeletedTrackAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(
albumId: albumId,
libraryId: libraryId,
path: $"/music/victim/{Guid.NewGuid():N}.flac",
title: "Victim Track",
includeMetadata: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
track.IsDeleted = true;
track.DeletedOnUtc = DateTime.UtcNow.AddMinutes(-5);
AlbumEntity album = _albumEntityFixture.Create(
artistId: artistId,
libraryId: libraryId,
title: "Victim Album",
tracks: [track],
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.Music, contentLocations: []));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Victim Artist", albums: [album], includeContributors: false));
await dbContext.SaveChangesAsync();
return (libraryId, artistId, album.Id, track.Id);
}
/// <summary>
/// Removes the users created by the tests.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,353 @@
#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.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
/// <summary>
/// Contains security tests for the <see cref="ShuffleTracksEndpoint"/> class.
/// </summary>
/// <remarks>
/// Rate limiting is not exercised because the shuffle route does not declare a rate limiter policy, unlike the authentication and track streaming routes,
/// so there is no configured limit to exceed. Token and claim correctness does not apply, because the route issues no token. Timing attack resistance does not
/// apply either, because the route performs no credential comparison.
/// </remarks>
[ExcludeFromCodeCoverage]
public class ShuffleTracksEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="ShuffleTracksEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ShuffleTracksEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task ShuffleTracks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle";
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(url, new { count = 10 });
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task ShuffleTracks_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(
$"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/tracks/shuffle", new { count = 10 });
// Assert
// The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean validation error instead of failing the request binding.
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(maliciousLibraryId, content, StringComparison.Ordinal);
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task ShuffleTracks_WithInjectionInCount_ShouldNotCorruptOrLeakData(string maliciousCount)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(
$"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle", new { count = maliciousCount });
// Assert
// The endpoint opts into DontCatchExceptions(), so a body value that cannot be bound is answered by the generic exception handler with the sanitized 500 problem.
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
await AssertSanitizedProblemAsync(response, maliciousCount);
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task ShuffleTracks_WithInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(
$"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle", new { count = 10, artistId = maliciousArtistId });
// Assert
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
await AssertSanitizedProblemAsync(response, maliciousArtistId);
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task ShuffleTracks_WithInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(
$"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle", new { count = 10, albumId = maliciousAlbumId });
// Assert
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
await AssertSanitizedProblemAsync(response, maliciousAlbumId);
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task ShuffleTracks_WithInjectionInExcludedTrackIds_ShouldNotCorruptOrLeakData(string maliciousTrackId)
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(
$"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle", new { count = 10, excludedTrackIds = new[] { maliciousTrackId } });
// Assert
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
await AssertSanitizedProblemAsync(response, maliciousTrackId);
}
[Fact]
public async Task ShuffleTracks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenResult()
{
// Arrange
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
_seededUsernames.Add(username);
Guid otherUserId = await SeedOtherUserAsync();
Guid libraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
await SeedTrackAsync(libraryId, albumId, "Hidden Song");
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync(
$"/api/v1/libraries/{libraryId}/tracks/shuffle", new { count = 10 });
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.DoesNotContain("Hidden Song", content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Asserts that the response is the sanitized generic API problem and never echoes the payload or leaks database details.
/// </summary>
/// <param name="response">The response to inspect.</param>
/// <param name="payload">The malicious payload that must not be echoed.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private static async Task AssertSanitizedProblemAsync(HttpResponseMessage response, string payload)
{
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("InternalServerError", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal(StatusCodes.Status500InternalServerError, problemDetails.RootElement.GetProperty("status").GetInt32());
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return userId;
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="title">The title of the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(
id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: []));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds an artist of the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library the artist belongs to.</param>
/// <param name="name">The name of the artist.</param>
/// <returns>The Id of the seeded artist.</returns>
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid artistId = Guid.NewGuid();
dbContext.Artists.Add(_artistEntityFixture.Create(
id: artistId, libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
await dbContext.SaveChangesAsync();
return artistId;
}
/// <summary>
/// Seeds an album of the artist identified by <paramref name="artistId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library the album belongs to.</param>
/// <param name="artistId">The Id of the artist the album belongs to.</param>
/// <param name="title">The title of the album.</param>
/// <returns>The Id of the seeded album.</returns>
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid albumId = Guid.NewGuid();
AlbumEntity album = _albumEntityFixture.Create(
id: albumId,
artistId: artistId,
libraryId: libraryId,
title: title,
includeTracks: false,
includeMetadata: false,
includeBarcode: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
dbContext.Albums.Add(album);
await dbContext.SaveChangesAsync();
return albumId;
}
/// <summary>
/// Seeds a track of the album identified by <paramref name="albumId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library the track belongs to.</param>
/// <param name="albumId">The Id of the album the track belongs to.</param>
/// <param name="title">The title of the track.</param>
/// <returns>The Id of the seeded track.</returns>
private async Task<Guid> SeedTrackAsync(Guid libraryId, Guid albumId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid trackId = Guid.NewGuid();
TrackEntity track = _trackEntityFixture.Create(
id: trackId,
albumId: albumId,
libraryId: libraryId,
path: $"/music/shuffle-{Guid.NewGuid():N}.flac",
title: title,
includeMetadata: false,
includeOriginalReleaseDate: false,
includeOriginalReleaseYear: false,
includeReReleaseDate: false,
includeReReleaseYear: false);
dbContext.Tracks.Add(track);
await dbContext.SaveChangesAsync();
return trackId;
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,402 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
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.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;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.UpdateTrack;
/// <summary>
/// Contains security tests for the <see cref="UpdateTrackEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private static readonly string s_contentRootPath = Path.Combine(Path.GetTempPath(), "lumina-security-update-track-tests");
private readonly LuminaApiFactory _apiFactory;
private readonly UpdateTrackRequestFixture _updateTrackRequestFixture = new();
private readonly MusicTrackMetadataDtoFixture _musicTrackMetadataDtoFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly List<Guid> _seededLibraryIds = [];
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="UpdateTrackEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdateTrackEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task UpdateTrack_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();
Guid trackId = Guid.NewGuid();
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
Assert.NotNull(problemDetails);
Assert.Equal(401, 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}/tracks/{trackId}", problemDetails["instance"].GetProperty("value").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task UpdateTrack_WithSQLInjectionInBody_ShouldNotCorruptOrLeakData(string maliciousTitle)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
Guid libraryId = Guid.NewGuid();
SeedLibrary(libraryId, userId);
(Guid artistId, Guid albumId, Guid trackId) = SeedArtistGraph(libraryId);
UpdateTrackRequest request = _updateTrackRequestFixture.Create(
metadata: _musicTrackMetadataDtoFixture.Create(title: maliciousTitle),
moods: [],
isrcs: [],
contributors: [],
ratings: []);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", request);
// Assert
// The malicious title passes validation, reaches the parameterized update, and is persisted verbatim: if it were
// concatenated into raw SQL, the update would fail and the track would not be updated.
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
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(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.
public async Task UpdateTrack_WithSQLInjectionInLibraryRouteId_ShouldRemainSecure(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", request);
// Assert
await AssertCleanValidationErrorAsync(response, maliciousLibraryId, "LibraryIdCannotBeEmpty");
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task UpdateTrack_WithSQLInjectionInArtistRouteId_ShouldRemainSecure(string maliciousArtistId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", request);
// Assert
await AssertCleanValidationErrorAsync(response, maliciousArtistId, "ArtistIdCannotBeEmpty");
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task UpdateTrack_WithSQLInjectionInAlbumRouteId_ShouldRemainSecure(string maliciousAlbumId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks/{Guid.NewGuid()}", request);
// Assert
await AssertCleanValidationErrorAsync(response, maliciousAlbumId, "AlbumIdCannotBeEmpty");
}
[Theory]
[InlineData("'; DROP TABLE Tracks; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task UpdateTrack_WithSQLInjectionInTrackRouteId_ShouldRemainSecure(string maliciousTrackId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Uri.EscapeDataString(maliciousTrackId)}", request);
// Assert
await AssertCleanValidationErrorAsync(response, maliciousTrackId, "TrackIdCannotBeEmpty");
}
[Fact]
public async Task UpdateTrack_WhenArtistDoesNotExist_ShouldReturnNotFoundWithoutLeakingInternals()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
Guid libraryId = Guid.NewGuid();
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", request);
// 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 UpdateTrack_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
_seededUsernames.Add(ownerUsername);
Guid libraryId = Guid.NewGuid();
SeedLibrary(libraryId, ownerId);
(Guid artistId, Guid albumId, Guid trackId) = SeedArtistGraph(libraryId);
HttpClient requesterClient = _apiFactory.CreateClient();
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
_seededUsernames.Add(requesterUsername);
UpdateTrackRequest request = _updateTrackRequestFixture.Create();
// Act
HttpResponseMessage response = await requesterClient.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", request);
// 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);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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 UpdateTrack_WhenTrackBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutLeakingOrModifyingIt()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(actingUsername);
Guid ownLibraryId = Guid.NewGuid();
SeedLibrary(ownLibraryId, actingUserId);
// The track 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 victimLibraryId = Guid.NewGuid();
SeedLibrary(victimLibraryId, victimUserId);
(Guid victimArtistId, Guid victimAlbumId, Guid victimTrackId) = SeedArtistGraph(victimLibraryId);
UpdateTrackRequest request = _updateTrackRequestFixture.Create(metadata: _musicTrackMetadataDtoFixture.Create(title: "Hijacked"));
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}/tracks/{victimTrackId}", request);
// 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 track is untouched.
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.NotNull(await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == victimTrackId));
}
/// <summary>
/// Asserts that the response is a clean validation problem details that neither leaks internals nor echoes the injected payload.
/// </summary>
/// <param name="response">The HTTP response to assert.</param>
/// <param name="injectedPayload">The injected payload that must never be echoed back.</param>
/// <param name="expectedErrorCode">The validation error code expected in the response.</param>
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);
}
/// <summary>
/// Seeds a media library of type music owned by <paramref name="userId"/>, whose single content location is the test content root path.
/// </summary>
/// <param name="libraryId">The Id of the media library to seed.</param>
/// <param name="userId">The Id of the user that owns the media library.</param>
private void SeedLibrary(Guid libraryId, Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Security Audio Library", libraryType: LibraryType.Music, contentLocations: [s_contentRootPath]));
dbContext.SaveChanges();
_seededLibraryIds.Add(libraryId);
}
/// <summary>
/// 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, 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: 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);
dbContext.SaveChanges();
return (artist.Id, albumId, trackId);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<ArtistEntity> artists = [.. dbContext.Artists.Where(artist => _seededLibraryIds.Contains(artist.LibraryId))];
dbContext.Artists.RemoveRange(artists);
List<LibraryEntity> libraries = [.. dbContext.Libraries.Where(library => _seededLibraryIds.Contains(library.Id))];
dbContext.Libraries.RemoveRange(libraries);
dbContext.SaveChanges();
}
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,221 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.AddLibrary;
/// <summary>
/// Contains security tests for the <see cref="AddLibraryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddLibraryEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="AddLibraryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AddLibraryEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task AddLibrary_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: "New Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("/api/v1/libraries", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Libraries--")] // Destructive injection.
public async Task AddLibrary_WithSQLInjectionInTitle_ShouldNotLeakOrError(string maliciousTitle)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: maliciousTitle,
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true
);
// Act
HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
// The malicious title passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim.
Assert.Equal(HttpStatusCode.Created, 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);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Title == maliciousTitle);
Assert.NotNull(storedLibrary);
Assert.Equal(maliciousTitle, storedLibrary!.Title);
}
[Theory]
[InlineData(-1)] // Just below the allowed range.
[InlineData(101)] // Just above the allowed range.
[InlineData(int.MinValue)] // Lowest possible value.
[InlineData(int.MaxValue)] // Highest possible value.
public async Task AddLibrary_WhenThresholdIsOutsideAllowedRange_ShouldRejectTheRequestWithoutPersisting(int completionThresholdPercentage)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
string title = $"Out Of Range Library {completionThresholdPercentage}";
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: title,
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: completionThresholdPercentage
);
// Act
HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
string content = await AssertValidationProblemAsync(response, "CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred");
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.Libraries.AnyAsync(library => library.Title == title));
}
[Fact]
public async Task AddLibrary_WhenThresholdIsSuppliedWithProgressTrackingDisabled_ShouldRejectTheRequestWithoutPersisting()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
string title = "Disabled Tracking Library";
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: title,
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: 50
);
// Act
HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
string content = await AssertValidationProblemAsync(response, "CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff");
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.Libraries.AnyAsync(library => library.Title == title));
}
/// <summary>
/// Asserts that <paramref name="response"/> carries the standard validation problem of the add library route.
/// </summary>
/// <param name="response">The response to assert.</param>
/// <param name="expectedErrorDescription">The error description expected under the validation errors.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedErrorDescription)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/libraries", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorDescription, errors["General.Validation"]);
return content;
}
}
@@ -0,0 +1,108 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Core.UoW;
using Lumina.Infrastructure.Core.Security;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.CancelLibrariesScan;
/// <summary>
/// Contains security tests for the <see cref="CancelLibrariesScanEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CancelLibrariesScanEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly PasswordHashService _hashService = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly UserEntityFixture _userEntityFixture = new();
private readonly LoginRequestFixture _loginRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="CancelLibrariesScanEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public CancelLibrariesScanEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task CancelLibrariesScan_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries/scans/cancel", new { });
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("/api/v1/libraries/scans/cancel", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Fact]
public async Task CancelLibrariesScan_WhenAuthenticated_ShouldNotLeakSensitiveData()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await CreateAndAuthenticateUserAsync(client);
// Act
HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/libraries/scans/cancel", new { });
// Assert
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task CreateAndAuthenticateUserAsync(HttpClient client)
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"testuser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
user.TotpSecret = null;
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!"));
string content = await loginResponse.Content.ReadAsStringAsync();
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
}
}
@@ -0,0 +1,103 @@
#region ========================================================================= USING =====================================================================================
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.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.CancelLibraryScan;
/// <summary>
/// Contains security tests for the <see cref="CancelLibraryScanEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CancelLibraryScanEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="CancelLibraryScanEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public CancelLibraryScanEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task CancelLibraryScan_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryId = Guid.NewGuid().ToString();
string scanId = Guid.NewGuid().ToString();
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/scans/{scanId}/cancel", new { });
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/scans/{scanId}/cancel", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE LibraryScans--")] // Destructive injection.
public async Task CancelLibraryScan_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId)
{
// Arrange
// Authenticate with an admin user and seed a library, so a valid libraryId would reach the handler and be authorized.
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
await SeedLibraryAsync(userId);
// Act
HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/scans/{Guid.NewGuid()}/cancel", new { });
// Assert
// Note: the {libraryId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler.
// Note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding
// ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here).
// Note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here.
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(_libraryEntityFixture.Create(userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,163 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.DeleteLibrary;
/// <summary>
/// Contains security tests for the <see cref="DeleteLibraryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteLibraryEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="DeleteLibraryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeleteLibraryEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task DeleteLibrary_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryId = Guid.NewGuid().ToString();
// Act
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Libraries--")] // Destructive injection.
public async Task DeleteLibrary_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId)
{
// Arrange
// Authenticate with an admin user and seed a library, so a valid id would reach the handler and be authorized.
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
await SeedLibraryAsync(userId);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}");
// Assert
// Note: the {id} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler.
// The observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here).
// That 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here.
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task DeleteLibrary_WhenTheOwnerLacksTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary()
{
// Arrange
// The created user holds no permission, so it owns the library without being allowed to change it.
HttpClient client = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.NotNull(await dbContext.Libraries.FindAsync(libraryId));
}
await _apiFactory.RemoveTestUserAsync(ownerUsername);
}
[Fact]
public async Task DeleteLibrary_WhenNonOwnerHoldsTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary()
{
// Arrange
// Ownership and the manage permission are both required, so a user that holds the permission must not delete a library it does not own.
HttpClient client = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
(Guid _, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserWithPermissionAsync(client, AuthorizationPermission.CanCreateLibraries);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.NotNull(await dbContext.Libraries.FindAsync(libraryId));
}
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveTestUserAsync(attackerUsername);
}
/// <summary>
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(_libraryEntityFixture.Create(userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,109 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Core.UoW;
using Lumina.Infrastructure.Core.Security;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetEnabledLibraries;
/// <summary>
/// Contains security tests for the <see cref="GetEnabledLibrariesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetEnabledLibrariesEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly PasswordHashService _hashService = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly UserEntityFixture _userEntityFixture = new();
private readonly LoginRequestFixture _loginRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetEnabledLibrariesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetEnabledLibrariesEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetEnabledLibraries_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/enabled");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("/api/v1/libraries/enabled", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Fact]
public async Task GetEnabledLibraries_WhenAuthenticated_ShouldNotLeakSensitiveData()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await CreateAndAuthenticateUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync("/api/v1/libraries/enabled");
// Assert
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task CreateAndAuthenticateUserAsync(HttpClient client)
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"testuser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
user.TotpSecret = null;
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!"));
string content = await loginResponse.Content.ReadAsStringAsync();
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
}
}
@@ -0,0 +1,109 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Core.UoW;
using Lumina.Infrastructure.Core.Security;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetLibraries;
/// <summary>
/// Contains security tests for the <see cref="GetLibrariesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibrariesEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly PasswordHashService _hashService = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly UserEntityFixture _userEntityFixture = new();
private readonly LoginRequestFixture _loginRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibrariesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibrariesEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetLibraries_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("/api/v1/libraries", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Fact]
public async Task GetLibraries_WhenAuthenticated_ShouldNotLeakSensitiveData()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await CreateAndAuthenticateUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync("/api/v1/libraries");
// Assert
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task CreateAndAuthenticateUserAsync(HttpClient client)
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"testuser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
user.TotpSecret = null;
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!"));
string content = await loginResponse.Content.ReadAsStringAsync();
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
}
}
@@ -0,0 +1,157 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.Security;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetLibrary;
/// <summary>
/// Contains security tests for the <see cref="GetLibraryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly PasswordHashService _hashService = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly LoginRequestFixture _loginRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetLibrary_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryId = Guid.NewGuid().ToString();
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Libraries--")] // Destructive injection.
public async Task GetLibrary_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId)
{
// Arrange
// Authenticate with an admin user and seed a library, so a valid id would reach the handler and be authorized.
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
await SeedLibraryAsync(userId);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}");
// Assert
// Note: the {id} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler.
// Note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding
// ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here).
// Note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here.
// Note: the payloads never contain the literal "SQL", so checking for that word would assert nothing; what matters
// is that the injection never reaches the database, so no SQL engine error (SqliteException) may surface.
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetLibrary_WhenAuthenticated_ShouldNotLeakSensitiveData()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}");
// Assert
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(_libraryEntityFixture.Create(userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task CreateAndAuthenticateUserAsync(HttpClient client)
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"testuser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
user.TotpSecret = null;
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!"));
string content = await loginResponse.Content.ReadAsStringAsync();
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
}
}
@@ -0,0 +1,112 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts;
/// <summary>
/// Contains security tests for the <see cref="GetLibraryPathTemplatePartsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryPathTemplatePartsEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryPathTemplatePartsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryPathTemplatePartsEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetLibraryPathTemplateParts_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryType = "Music";
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/path-template-parts/{libraryType}");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/path-template-parts/{libraryType}", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Libraries--")] // Destructive SQL injection.
[InlineData("Music; rm -rf /")] // Command injection.
[InlineData("$(whoami)")] // Command substitution injection.
[InlineData("`whoami`")] // Backtick command injection.
[InlineData("{0}{1}{0}")] // Template/placeholder injection.
[InlineData("..\\..\\..\\Windows\\System32\\config\\SAM")] // Windows path traversal.
[InlineData("%2e%2e%2fetc%2fpasswd")] // Encoded path traversal.
public async Task GetLibraryPathTemplateParts_WithInjectionInLibraryType_ShouldNotLeakOrError(string maliciousLibraryType)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/path-template-parts/{Uri.EscapeDataString(maliciousLibraryType)}");
string content = await response.Content.ReadAsStringAsync();
// Assert
// An unrecognized library type is a value that is not accepted, so it is reported as forbidden, and the response must stay
// generic: the failed request leaks no database, filesystem or framework internals.
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(6, problemDetails!.Count);
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.Forbidden", problemDetails["title"].GetString());
Assert.Equal("UnknownLibraryType", problemDetails["detail"].GetString());
Assert.StartsWith("/api/v1/libraries/path-template-parts/", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
}
}
@@ -0,0 +1,102 @@
#region ========================================================================= USING =====================================================================================
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.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetLibraryScanProgress;
/// <summary>
/// Contains security tests for the <see cref="GetLibraryScanProgressEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryScanProgressEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryScanProgressEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryScanProgressEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetLibraryScanProgress_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryId = Guid.NewGuid().ToString();
string scanId = Guid.NewGuid().ToString();
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/scans/{scanId}/progress");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/scans/{scanId}/progress", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE LibraryScans--")] // Destructive injection.
public async Task GetLibraryScanProgress_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId)
{
// Arrange
// Authenticate with an admin user and seed a library, so a valid libraryId would reach the handler and be authorized.
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
await SeedLibraryAsync(userId);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/scans/{Guid.NewGuid()}/progress");
// Assert
// Note: the {libraryId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler.
// Note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding
// ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here).
// Note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here.
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(_libraryEntityFixture.Create(userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,109 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Core.UoW;
using Lumina.Infrastructure.Core.Security;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetRunningLibraryScans;
/// <summary>
/// Contains security tests for the <see cref="GetRunningLibraryScansEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetRunningLibraryScansEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly PasswordHashService _hashService = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly UserEntityFixture _userEntityFixture = new();
private readonly LoginRequestFixture _loginRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetRunningLibraryScansEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetRunningLibraryScansEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetRunningLibraryScans_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/scans/running");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("/api/v1/libraries/scans/running", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Fact]
public async Task GetRunningLibraryScans_WhenAuthenticated_ShouldNotLeakSensitiveData()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await CreateAndAuthenticateUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync("/api/v1/libraries/scans/running");
// Assert
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task CreateAndAuthenticateUserAsync(HttpClient client)
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"testuser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
user.TotpSecret = null;
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!"));
string content = await loginResponse.Content.ReadAsStringAsync();
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
}
}
@@ -0,0 +1,108 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Core.UoW;
using Lumina.Infrastructure.Core.Security;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.ScanLibraries;
/// <summary>
/// Contains security tests for the <see cref="ScanLibrariesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScanLibrariesEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly PasswordHashService _hashService = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly UserEntityFixture _userEntityFixture = new();
private readonly LoginRequestFixture _loginRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScanLibrariesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ScanLibrariesEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task ScanLibraries_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries/scans", new { });
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("/api/v1/libraries/scans", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Fact]
public async Task ScanLibraries_WhenAuthenticated_ShouldNotLeakSensitiveData()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await CreateAndAuthenticateUserAsync(client);
// Act
HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/libraries/scans", new { });
// Assert
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task CreateAndAuthenticateUserAsync(HttpClient client)
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"testuser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
user.TotpSecret = null;
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!"));
string content = await loginResponse.Content.ReadAsStringAsync();
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
}
}
@@ -0,0 +1,102 @@
#region ========================================================================= USING =====================================================================================
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.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.ScanLibrary;
/// <summary>
/// Contains security tests for the <see cref="ScanLibraryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScanLibraryEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScanLibraryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ScanLibraryEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task ScanLibrary_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryId = Guid.NewGuid().ToString();
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/scans", new { });
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/scans", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Libraries--")] // Destructive injection.
public async Task ScanLibrary_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId)
{
// Arrange
// Authenticate with an admin user and seed a library, so a valid id would reach the handler and be authorized.
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
await SeedLibraryAsync(userId);
// Act
HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/scans", new { });
// Assert
// Note: the {id} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler.
// Note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding
// ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here).
// Note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here.
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(_libraryEntityFixture.Create(userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,457 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Nodes;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.UpdateLibrary;
/// <summary>
/// Contains security tests for the <see cref="UpdateLibraryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateLibraryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdateLibraryEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task UpdateLibrary_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryId = Guid.NewGuid().ToString();
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: Guid.NewGuid(),
title: "Updated Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Libraries--")] // Destructive injection.
public async Task UpdateLibrary_WithSQLInjectionInTitle_ShouldNotLeakOrError(string maliciousTitle)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
title: maliciousTitle,
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true
);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
// The malicious title passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim.
Assert.Equal(HttpStatusCode.OK, 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);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.Equal(maliciousTitle, storedLibrary!.Title);
}
[Theory]
[InlineData(-1)] // Just below the allowed range.
[InlineData(101)] // Just above the allowed range.
[InlineData(int.MinValue)] // Lowest possible value.
[InlineData(int.MaxValue)] // Highest possible value.
public async Task UpdateLibrary_WhenThresholdIsOutsideAllowedRange_ShouldRejectTheRequestAndKeepTheStoredSettings(int completionThresholdPercentage)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
title: "Test Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: completionThresholdPercentage
);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
string content = await AssertValidationProblemAsync(response, $"/api/v1/libraries/{libraryId}", "CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred");
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Equal(70, storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task UpdateLibrary_WhenThresholdIsSuppliedWithProgressTrackingDisabled_ShouldRejectTheRequestAndKeepTheStoredSettings()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
title: "Test Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: 50
);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
string content = await AssertValidationProblemAsync(response, $"/api/v1/libraries/{libraryId}", "CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff");
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Equal(70, storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task UpdateLibrary_WhenNonOwnerTriesToChangeConsumptionSettings_ShouldNotApplyThem()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, ownerId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
// Authenticating a second user on the same client replaces the bearer token, so the update below is sent as the non-owner.
(Guid _, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
title: "Test Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: null
);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
// The update handler authorizes after loading the library and answers a non-owner with the NotAuthorized application error,
// which the shared problem mapping exposes as 403 Forbidden (ownership is a permission problem, not a missing resource).
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.Equal($"/api/v1/libraries/{libraryId}", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Equal(70, storedLibrary.CompletionThresholdPercentage);
}
await _apiFactory.RemoveTestUserAsync(attackerUsername);
await _apiFactory.RemoveTestUserAsync(ownerUsername);
}
[Fact]
public async Task UpdateLibrary_WhenNonOwnerHoldsTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary()
{
// Arrange
// Ownership and the manage permission are both required, so a user that holds the permission must not update a library it does not own.
HttpClient client = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, ownerId, title: "Original Title");
(Guid _, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserWithPermissionAsync(client, AuthorizationPermission.CanCreateLibraries);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.Equal("Original Title", storedLibrary!.Title);
}
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveTestUserAsync(attackerUsername);
}
[Fact]
public async Task UpdateLibrary_WhenTheOwnerLacksTheManagePermission_ShouldReturnForbiddenAndKeepTheLibrary()
{
// Arrange
// The created user holds no permission, so it owns the library without being allowed to change it.
HttpClient client = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, ownerId, title: "Original Title");
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
title: "Updated Title",
libraryType: "Book",
contentLocations: ["C:/Media"],
coverImage: null
);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.Equal("Original Title", storedLibrary!.Title);
Assert.Equal(LibraryType.EBook, storedLibrary.LibraryType);
}
await _apiFactory.RemoveTestUserAsync(ownerUsername);
}
[Fact]
public async Task UpdateLibrary_WhenBodyNamesAnotherOwner_ShouldKeepTheStoredOwner()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, ownerId);
HttpClient client = _apiFactory.CreateClient();
Guid adminId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
title: "Test Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true
);
// The request has no owner, so the claimed owner is added to the raw body, the way a crafted request would carry it.
JsonObject body = JsonSerializer.SerializeToNode(request, new JsonSerializerOptions(JsonSerializerDefaults.Web))!.AsObject();
body["userId"] = adminId.ToString();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", body);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.Equal(ownerId, storedLibrary!.UserId);
}
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveAdminUserAsync(adminId);
}
/// <summary>
/// Asserts that <paramref name="response"/> carries the standard validation problem of the update library route.
/// </summary>
/// <param name="response">The response to assert.</param>
/// <param name="expectedInstance">The expected instance path of the problem.</param>
/// <param name="expectedErrorDescription">The error description expected under the validation errors.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorDescription)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorDescription, errors["General.Validation"]);
return content;
}
/// <summary>
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library to seed.</param>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="title">The title of the library.</param>
/// <param name="shouldTrackConsumptionProgress">Whether the seeded library tracks the consumption progress of its items.</param>
/// <param name="completionThresholdPercentage">The completion threshold percentage of the seeded library, if any.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(
Guid libraryId,
Guid userId,
string title = "Test Library",
bool shouldTrackConsumptionProgress = false,
int? completionThresholdPercentage = null)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(_libraryEntityFixture.Create(
id: libraryId,
userId: userId,
title: title,
libraryType: LibraryType.EBook,
contentLocations: [],
shouldTrackConsumptionProgress: shouldTrackConsumptionProgress,
completionThresholdPercentage: completionThresholdPercentage));
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,376 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
/// <summary>
/// Contains security tests for the <see cref="ClearConsumptionHistoryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ClearConsumptionHistoryEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private const string PATH = "/api/v1/users/me/consumption-history";
private static readonly DateTime s_startedOnUtc = new(2026, 5, 3, 9, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 5, 3, 9, 10, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="ClearConsumptionHistoryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ClearConsumptionHistoryEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task ClearConsumptionHistory_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Act
HttpResponseMessage response = await _client.DeleteAsync(PATH);
// Assert
await AssertUnauthorizedAsync(response, PATH);
}
[Fact]
public async Task ClearConsumptionHistory_WhenCalled_ShouldDeleteOnlyTheCallersHistoryAndPreserveResumePoints()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid ownLibraryId = await SeedLibraryAsync(userId, "Owner Library");
Guid ownRecordId = await SeedRecordAsync(userId, ownLibraryId);
Guid ownOtherRecordId = await SeedRecordAsync(userId, ownLibraryId);
Guid ownResumePointId = await SeedResumePointAsync(userId, ownLibraryId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId);
// Act
HttpResponseMessage response = await _client.DeleteAsync(PATH);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
AssertNoSensitiveData(content);
await AssertRecordsAreDeletedAsync(ownRecordId, ownOtherRecordId);
await AssertRecordsArePreservedAsync(otherUserRecordId);
// Clearing the history is a separate user action from clearing the continue watching list, so resume points survive.
await AssertResumePointsArePreservedAsync(ownResumePointId);
}
[Fact]
public async Task ClearConsumptionHistory_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndClearOnlyTheCallersHistory()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid ownLibraryId = await SeedLibraryAsync(userId, "Owner Library");
Guid ownRecordId = await SeedRecordAsync(userId, ownLibraryId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId);
string url = $"{PATH}?userId={otherUserId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
// The me route always targets the authenticated caller, so a spoofed query parameter cannot redirect the deletion.
await AssertRecordsAreDeletedAsync(ownRecordId);
await AssertRecordsArePreservedAsync(otherUserRecordId);
}
[Fact]
public async Task ClearConsumptionHistory_WithInjectionInSpoofedUserIdQueryParameter_ShouldIgnoreItAndRemainSecure()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid ownLibraryId = await SeedLibraryAsync(userId, "Owner Library");
Guid ownRecordId = await SeedRecordAsync(userId, ownLibraryId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId);
string maliciousUserId = "'; DROP TABLE MediaConsumptionRecords--";
string url = $"{PATH}?userId={Uri.EscapeDataString(maliciousUserId)}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
AssertNoSensitiveData(content);
Assert.DoesNotContain(maliciousUserId, content, StringComparison.Ordinal);
// The unused query parameter never reaches the query builder, so the caller's own rows are deleted and the other user's rows survive.
await AssertRecordsAreDeletedAsync(ownRecordId);
await AssertRecordsArePreservedAsync(otherUserRecordId);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="title">The title of the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a consumption record of a music track of <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the record.</param>
/// <param name="libraryId">The Id of the library that contains the consumed track.</param>
/// <returns>The Id of the seeded consumption record.</returns>
private async Task<Guid> SeedRecordAsync(Guid userId, Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid recordId = Guid.NewGuid();
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: recordId,
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: Guid.NewGuid(),
status: ConsumptionStatus.Stopped,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
consumedDurationMilliseconds: 90_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 45_000,
lastPositionLocation: null,
lastProgressFraction: 0.5,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return recordId;
}
/// <summary>
/// Seeds a resume point of <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the resume point.</param>
/// <param name="libraryId">The Id of the library that contains the media item.</param>
/// <returns>The Id of the seeded resume point.</returns>
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid resumePointId = Guid.NewGuid();
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
id: resumePointId,
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: Guid.NewGuid(),
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 45_000,
lastPositionLocation: null,
lastProgressFraction: 0.5,
lastConsumedOnUtc: s_lastActivityOnUtc));
await dbContext.SaveChangesAsync();
return resumePointId;
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
// has run, instead of assuming that it already has.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
if (storedRecords.Count == 0)
return;
await Task.Delay(100);
}
Assert.Empty(storedRecords);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
// completion has run, instead of trusting the state observed right after the response.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
Assert.Equal(recordIds.Length, storedRecords.Count);
await Task.Delay(100);
}
Assert.Equal(recordIds.Length, storedRecords.Count);
}
/// <summary>
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
/// </summary>
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaResumePointEntity> storedResumePoints = [];
// The request transaction is committed or rolled back after the response has been sent, so a resume point that must survive is read until
// that completion has run, instead of trusting the state observed right after the response.
for (int attempt = 0; attempt < 20; attempt++)
{
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
.ToListAsync();
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
await Task.Delay(100);
}
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
}
/// <summary>
/// Asserts that the per-user responses are not storable by any intermediary and vary by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,505 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
/// <summary>
/// Contains security tests for the <see cref="ClearUserConsumptionHistoryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ClearUserConsumptionHistoryEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private const string PATH_PREFIX = "/api/v1/users/";
private const string PATH_SUFFIX = "/consumption-history";
private static readonly DateTime s_startedOnUtc = new(2026, 5, 4, 9, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 5, 4, 9, 10, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
private readonly List<Guid> _adminUserIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="ClearUserConsumptionHistoryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ClearUserConsumptionHistoryEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task ClearUserConsumptionHistory_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task ClearUserConsumptionHistory_WhenCallerNamesThemselves_ShouldClearTheOwnHistory()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
Guid recordId = await SeedRecordAsync(userId, libraryId);
string url = $"{PATH_PREFIX}{userId}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
await AssertRecordsAreDeletedAsync(recordId);
}
[Fact]
public async Task ClearUserConsumptionHistory_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheHistory()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid targetUserId, _) = await SeedOtherUserAsync();
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
Guid targetRecordId = await SeedRecordAsync(targetUserId, targetLibraryId);
string url = $"{PATH_PREFIX}{targetUserId}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
string content = await AssertForbiddenAsync(response, url);
AssertNonCacheable(response);
AssertNoSensitiveData(content);
await AssertRecordsArePreservedAsync(targetRecordId);
}
[Fact]
public async Task ClearUserConsumptionHistory_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid otherUserId, _) = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId);
string foreignUrl = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
string missingUrl = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
// Act
HttpResponseMessage foreignResponse = await _client.DeleteAsync(foreignUrl);
HttpResponseMessage missingResponse = await _client.DeleteAsync(missingUrl);
// Assert
await AssertForbiddenAsync(foreignResponse, foreignUrl);
await AssertForbiddenAsync(missingResponse, missingUrl);
Dictionary<string, JsonElement> foreignProblem = await ReadProblemDetailsAsync(foreignResponse);
Dictionary<string, JsonElement> missingProblem = await ReadProblemDetailsAsync(missingResponse);
Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32());
Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString());
Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString());
Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString());
await AssertRecordsArePreservedAsync(otherUserRecordId);
}
[Fact]
public async Task ClearUserConsumptionHistory_WhenAdminNamesAnotherUser_ShouldClearThatUsersHistory()
{
// Arrange
(Guid targetUserId, _) = await SeedOtherUserAsync();
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
Guid targetRecordId = await SeedRecordAsync(targetUserId, targetLibraryId);
Guid targetResumePointId = await SeedResumePointAsync(targetUserId, targetLibraryId);
string url = $"{PATH_PREFIX}{targetUserId}{PATH_SUFFIX}";
HttpClient adminClient = _apiFactory.CreateClient();
Guid adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(adminClient);
_adminUserIds.Add(adminUserId);
try
{
// Act
HttpResponseMessage response = await adminClient.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
await AssertRecordsAreDeletedAsync(targetRecordId);
await AssertResumePointsArePreservedAsync(targetResumePointId);
}
finally
{
adminClient.Dispose();
}
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task ClearUserConsumptionHistory_WithInjectionInUserIdRouteValue_ShouldRejectWithoutDeletingRows(string maliciousUserId)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
Guid recordId = await SeedRecordAsync(userId, libraryId);
string url = $"{PATH_PREFIX}{Uri.EscapeDataString(maliciousUserId)}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedInjectionAsync(response, maliciousUserId, url, "TargetUserIdIsInvalid");
AssertNonCacheable(response);
await AssertRecordsArePreservedAsync(recordId);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="title">The title of the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a consumption record of a music track of <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the record.</param>
/// <param name="libraryId">The Id of the library that contains the consumed track.</param>
/// <returns>The Id of the seeded consumption record.</returns>
private async Task<Guid> SeedRecordAsync(Guid userId, Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid recordId = Guid.NewGuid();
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: recordId,
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: Guid.NewGuid(),
status: ConsumptionStatus.Stopped,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
consumedDurationMilliseconds: 90_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 45_000,
lastPositionLocation: null,
lastProgressFraction: 0.5,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return recordId;
}
/// <summary>
/// Seeds a resume point of <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the resume point.</param>
/// <param name="libraryId">The Id of the library that contains the media item.</param>
/// <returns>The Id of the seeded resume point.</returns>
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid resumePointId = Guid.NewGuid();
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
id: resumePointId,
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: Guid.NewGuid(),
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 45_000,
lastPositionLocation: null,
lastProgressFraction: 0.5,
lastConsumedOnUtc: s_lastActivityOnUtc));
await dbContext.SaveChangesAsync();
return resumePointId;
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts that the response is the exact not authorized problem document and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
return content;
}
/// <summary>
/// Reads the problem details document of <paramref name="response"/>.
/// </summary>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The parsed problem details fields.</returns>
private async Task<Dictionary<string, JsonElement>> ReadProblemDetailsAsync(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
return problemDetails!;
}
/// <summary>
/// Asserts that a malicious route value is rejected without disclosing internals or reaching the data access layer.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <param name="requestPath">The request path the value was sent in.</param>
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
private async Task AssertRejectedInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode)
{
string content = await response.Content.ReadAsStringAsync();
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
{
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
// The instance is the request path with the rejected payload still in place, independent of how the server escapes it.
string escapedPayload = Uri.EscapeDataString(payload);
int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal);
string? instance = problemDetails["instance"].GetString();
Assert.NotNull(instance);
Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path.");
Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal);
Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
}
else
{
// A payload that carries encoded path separators is rejected by routing before it reaches the validator. That is still a safe rejection, so only it may take this branch.
Assert.Contains("/", payload, StringComparison.Ordinal);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
AssertNoSensitiveData(content);
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
// has run, instead of assuming that it already has.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
if (storedRecords.Count == 0)
return;
await Task.Delay(100);
}
Assert.Empty(storedRecords);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
// completion has run, instead of trusting the state observed right after the response.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
Assert.Equal(recordIds.Length, storedRecords.Count);
await Task.Delay(100);
}
Assert.Equal(recordIds.Length, storedRecords.Count);
}
/// <summary>
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
/// </summary>
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaResumePointEntity> storedResumePoints = [];
// The request transaction is committed or rolled back after the response has been sent, so a resume point that must survive is read until
// that completion has run, instead of trusting the state observed right after the response.
for (int attempt = 0; attempt < 20; attempt++)
{
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
.ToListAsync();
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
await Task.Delay(100);
}
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
}
/// <summary>
/// Asserts that the per-user responses are not storable by any intermediary and vary by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users and admin users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
foreach (Guid userId in _adminUserIds)
_apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult();
}
}
@@ -0,0 +1,431 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearResumePoints;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.ClearResumePoints;
/// <summary>
/// Contains security tests for the <see cref="ClearResumePointsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ClearResumePointsEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private const string PATH = "/api/v1/users/me/media-resume-points";
private static readonly DateTime s_startedOnUtc = new(2026, 5, 5, 9, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 5, 5, 9, 10, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="ClearResumePointsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ClearResumePointsEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task ClearResumePoints_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Act
HttpResponseMessage response = await _client.DeleteAsync(PATH);
// Assert
await AssertUnauthorizedAsync(response, PATH);
}
[Fact]
public async Task ClearResumePoints_WhenLibraryIdIsOmitted_ShouldDeleteOnlyTheCallersResumePointsAndPreserveHistory()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid firstLibraryId = await SeedLibraryAsync(userId, "First Owner Library");
Guid secondLibraryId = await SeedLibraryAsync(userId, "Second Owner Library");
Guid firstResumePointId = await SeedResumePointAsync(userId, firstLibraryId);
Guid secondResumePointId = await SeedResumePointAsync(userId, secondLibraryId);
Guid recordId = await SeedRecordAsync(userId, firstLibraryId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId);
// Act
HttpResponseMessage response = await _client.DeleteAsync(PATH);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
AssertNoSensitiveData(content);
await AssertResumePointsAreDeletedAsync(firstResumePointId, secondResumePointId);
await AssertResumePointsArePreservedAsync(otherUserResumePointId);
// Removing the resume points does not touch the history, so the consumption records survive.
await AssertRecordsArePreservedAsync(recordId);
}
[Fact]
public async Task ClearResumePoints_WithLibraryId_ShouldDeleteOnlyTheCallersResumePointsInThatLibrary()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid targetLibraryId = await SeedLibraryAsync(userId, "Target Owner Library");
Guid otherLibraryId = await SeedLibraryAsync(userId, "Other Owner Library");
Guid targetResumePointId = await SeedResumePointAsync(userId, targetLibraryId);
Guid otherResumePointId = await SeedResumePointAsync(userId, otherLibraryId);
Guid recordId = await SeedRecordAsync(userId, targetLibraryId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId);
string url = $"{PATH}?libraryId={targetLibraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
await AssertResumePointsAreDeletedAsync(targetResumePointId);
await AssertResumePointsArePreservedAsync(otherResumePointId, otherUserResumePointId);
await AssertRecordsArePreservedAsync(recordId);
}
[Fact]
public async Task ClearResumePoints_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndNeverDeleteTheOtherUsersResumePoints()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid ownLibraryId = await SeedLibraryAsync(userId, "Owner Library");
Guid ownResumePointId = await SeedResumePointAsync(userId, ownLibraryId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId);
string url = $"{PATH}?libraryId={otherUserLibraryId}&userId={otherUserId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
// The me route always targets the authenticated caller, so the spoofed user Id cannot turn the request into a deletion of the other user's rows.
await AssertResumePointsArePreservedAsync(otherUserResumePointId, ownResumePointId);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaResumePoints--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaResumePoints")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task ClearResumePoints_WithInjectionInLibraryIdQueryParameter_ShouldRejectWithoutDeletingRows(string maliciousLibraryId)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
Guid resumePointId = await SeedResumePointAsync(userId, libraryId);
string url = $"{PATH}?libraryId={Uri.EscapeDataString(maliciousLibraryId)}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedQueryInjectionAsync(response, maliciousLibraryId, PATH, "LibraryIdCannotBeEmpty");
AssertNonCacheable(response);
await AssertResumePointsArePreservedAsync(resumePointId);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="title">The title of the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a consumption record of a music track of <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the record.</param>
/// <param name="libraryId">The Id of the library that contains the consumed track.</param>
/// <returns>The Id of the seeded consumption record.</returns>
private async Task<Guid> SeedRecordAsync(Guid userId, Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid recordId = Guid.NewGuid();
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: recordId,
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: Guid.NewGuid(),
status: ConsumptionStatus.Stopped,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
consumedDurationMilliseconds: 90_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 45_000,
lastPositionLocation: null,
lastProgressFraction: 0.5,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return recordId;
}
/// <summary>
/// Seeds a resume point of <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the resume point.</param>
/// <param name="libraryId">The Id of the library that contains the media item.</param>
/// <returns>The Id of the seeded resume point.</returns>
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid resumePointId = Guid.NewGuid();
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
id: resumePointId,
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: Guid.NewGuid(),
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 45_000,
lastPositionLocation: null,
lastProgressFraction: 0.5,
lastConsumedOnUtc: s_lastActivityOnUtc));
await dbContext.SaveChangesAsync();
return resumePointId;
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts that a malicious query value is rejected with the exact RFC 4918 validation problem shape.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <param name="requestPath">The request path the value was sent on.</param>
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
private async Task AssertRejectedQueryInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(requestPath, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNoSensitiveData(content);
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are no longer stored once the request transaction has completed.
/// </summary>
/// <param name="resumePointIds">The Ids of the resume points that must be deleted.</param>
private async Task AssertResumePointsAreDeletedAsync(params Guid[] resumePointIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaResumePointEntity> storedResumePoints = [];
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
// has run, instead of assuming that it already has.
for (int attempt = 0; attempt < 20; attempt++)
{
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
.ToListAsync();
if (storedResumePoints.Count == 0)
return;
await Task.Delay(100);
}
Assert.Empty(storedResumePoints);
}
/// <summary>
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
/// </summary>
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaResumePointEntity> storedResumePoints = [];
// The request transaction is committed or rolled back after the response has been sent, so a resume point that must survive is read until
// that completion has run, instead of trusting the state observed right after the response.
for (int attempt = 0; attempt < 20; attempt++)
{
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
.ToListAsync();
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
await Task.Delay(100);
}
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
// completion has run, instead of trusting the state observed right after the response.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
Assert.Equal(recordIds.Length, storedRecords.Count);
await Task.Delay(100);
}
Assert.Equal(recordIds.Length, storedRecords.Count);
}
/// <summary>
/// Asserts that the per-user responses are not storable by any intermediary and vary by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,567 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearResumePoints;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.ClearResumePoints;
/// <summary>
/// Contains security tests for the <see cref="ClearUserResumePointsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ClearUserResumePointsEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private const string PATH_PREFIX = "/api/v1/users/";
private const string PATH_SUFFIX = "/media-resume-points";
private static readonly DateTime s_startedOnUtc = new(2026, 5, 6, 9, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 5, 6, 9, 10, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
private readonly List<Guid> _adminUserIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="ClearUserResumePointsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ClearUserResumePointsEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task ClearUserResumePoints_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task ClearUserResumePoints_WhenCallerNamesThemselves_ShouldClearTheOwnResumePointsAndPreserveHistory()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
Guid resumePointId = await SeedResumePointAsync(userId, libraryId);
Guid recordId = await SeedRecordAsync(userId, libraryId);
string url = $"{PATH_PREFIX}{userId}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
await AssertResumePointsAreDeletedAsync(resumePointId);
await AssertRecordsArePreservedAsync(recordId);
}
[Fact]
public async Task ClearUserResumePoints_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheResumePoints()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid targetUserId, _) = await SeedOtherUserAsync();
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
Guid targetResumePointId = await SeedResumePointAsync(targetUserId, targetLibraryId);
string url = $"{PATH_PREFIX}{targetUserId}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
string content = await AssertForbiddenAsync(response, url);
AssertNonCacheable(response);
AssertNoSensitiveData(content);
await AssertResumePointsArePreservedAsync(targetResumePointId);
}
[Fact]
public async Task ClearUserResumePoints_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid otherUserId, _) = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId);
string foreignUrl = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
string missingUrl = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
// Act
HttpResponseMessage foreignResponse = await _client.DeleteAsync(foreignUrl);
HttpResponseMessage missingResponse = await _client.DeleteAsync(missingUrl);
// Assert
await AssertForbiddenAsync(foreignResponse, foreignUrl);
await AssertForbiddenAsync(missingResponse, missingUrl);
Dictionary<string, JsonElement> foreignProblem = await ReadProblemDetailsAsync(foreignResponse);
Dictionary<string, JsonElement> missingProblem = await ReadProblemDetailsAsync(missingResponse);
Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32());
Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString());
Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString());
Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString());
await AssertResumePointsArePreservedAsync(otherUserResumePointId);
}
[Fact]
public async Task ClearUserResumePoints_WhenAdminNamesAnotherUser_ShouldClearOnlyThatUsersResumePointsInTheNamedLibrary()
{
// Arrange
(Guid targetUserId, _) = await SeedOtherUserAsync();
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
Guid otherTargetLibraryId = await SeedLibraryAsync(targetUserId, "Other Target User Library");
Guid targetResumePointId = await SeedResumePointAsync(targetUserId, targetLibraryId);
Guid otherTargetResumePointId = await SeedResumePointAsync(targetUserId, otherTargetLibraryId);
Guid targetRecordId = await SeedRecordAsync(targetUserId, targetLibraryId);
string url = $"{PATH_PREFIX}{targetUserId}{PATH_SUFFIX}?libraryId={targetLibraryId}";
HttpClient adminClient = _apiFactory.CreateClient();
Guid adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(adminClient);
_adminUserIds.Add(adminUserId);
try
{
// Act
HttpResponseMessage response = await adminClient.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
await AssertResumePointsAreDeletedAsync(targetResumePointId);
await AssertResumePointsArePreservedAsync(otherTargetResumePointId);
await AssertRecordsArePreservedAsync(targetRecordId);
}
finally
{
adminClient.Dispose();
}
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaResumePoints--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaResumePoints")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task ClearUserResumePoints_WithInjectionInUserIdRouteValue_ShouldRejectWithoutDeletingRows(string maliciousUserId)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
Guid resumePointId = await SeedResumePointAsync(userId, libraryId);
string url = $"{PATH_PREFIX}{Uri.EscapeDataString(maliciousUserId)}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedRouteInjectionAsync(response, maliciousUserId, url, "TargetUserIdIsInvalid");
AssertNonCacheable(response);
await AssertResumePointsArePreservedAsync(resumePointId);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaResumePoints--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaResumePoints")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task ClearUserResumePoints_WithInjectionInLibraryIdQueryParameter_ShouldRejectWithoutDeletingRows(string maliciousLibraryId)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
Guid resumePointId = await SeedResumePointAsync(userId, libraryId);
string path = $"{PATH_PREFIX}{userId}{PATH_SUFFIX}";
string url = $"{path}?libraryId={Uri.EscapeDataString(maliciousLibraryId)}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedQueryInjectionAsync(response, maliciousLibraryId, path, "LibraryIdCannotBeEmpty");
AssertNonCacheable(response);
await AssertResumePointsArePreservedAsync(resumePointId);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="title">The title of the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a consumption record of a music track of <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the record.</param>
/// <param name="libraryId">The Id of the library that contains the consumed track.</param>
/// <returns>The Id of the seeded consumption record.</returns>
private async Task<Guid> SeedRecordAsync(Guid userId, Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid recordId = Guid.NewGuid();
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: recordId,
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: Guid.NewGuid(),
status: ConsumptionStatus.Stopped,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
consumedDurationMilliseconds: 90_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 45_000,
lastPositionLocation: null,
lastProgressFraction: 0.5,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return recordId;
}
/// <summary>
/// Seeds a resume point of <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the resume point.</param>
/// <param name="libraryId">The Id of the library that contains the media item.</param>
/// <returns>The Id of the seeded resume point.</returns>
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid resumePointId = Guid.NewGuid();
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
id: resumePointId,
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: Guid.NewGuid(),
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 45_000,
lastPositionLocation: null,
lastProgressFraction: 0.5,
lastConsumedOnUtc: s_lastActivityOnUtc));
await dbContext.SaveChangesAsync();
return resumePointId;
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts that the response is the exact not authorized problem document and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
return content;
}
/// <summary>
/// Reads the problem details document of <paramref name="response"/>.
/// </summary>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The parsed problem details fields.</returns>
private async Task<Dictionary<string, JsonElement>> ReadProblemDetailsAsync(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
return problemDetails!;
}
/// <summary>
/// Asserts that a malicious route value is rejected without disclosing internals or reaching the data access layer.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <param name="requestPath">The request path the value was sent in.</param>
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
private async Task AssertRejectedRouteInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode)
{
string content = await response.Content.ReadAsStringAsync();
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
{
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
// The instance is the request path with the rejected payload still in place, independent of how the server escapes it.
string escapedPayload = Uri.EscapeDataString(payload);
int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal);
string? instance = problemDetails["instance"].GetString();
Assert.NotNull(instance);
Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path.");
Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal);
Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
}
else
{
// A payload that carries encoded path separators is rejected by routing before it reaches the validator. That is still a safe rejection, so only it may take this branch.
Assert.Contains("/", payload, StringComparison.Ordinal);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
AssertNoSensitiveData(content);
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that a malicious query value is rejected with the exact RFC 4918 validation problem shape.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <param name="requestPath">The request path the value was sent on.</param>
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
private async Task AssertRejectedQueryInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(requestPath, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNoSensitiveData(content);
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are no longer stored once the request transaction has completed.
/// </summary>
/// <param name="resumePointIds">The Ids of the resume points that must be deleted.</param>
private async Task AssertResumePointsAreDeletedAsync(params Guid[] resumePointIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaResumePointEntity> storedResumePoints = [];
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
// has run, instead of assuming that it already has.
for (int attempt = 0; attempt < 20; attempt++)
{
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
.ToListAsync();
if (storedResumePoints.Count == 0)
return;
await Task.Delay(100);
}
Assert.Empty(storedResumePoints);
}
/// <summary>
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
/// </summary>
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaResumePointEntity> storedResumePoints = [];
// The request transaction is committed or rolled back after the response has been sent, so a resume point that must survive is read until
// that completion has run, instead of trusting the state observed right after the response.
for (int attempt = 0; attempt < 20; attempt++)
{
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
.ToListAsync();
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
await Task.Delay(100);
}
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
// completion has run, instead of trusting the state observed right after the response.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
Assert.Equal(recordIds.Length, storedRecords.Count);
await Task.Delay(100);
}
Assert.Equal(recordIds.Length, storedRecords.Count);
}
/// <summary>
/// Asserts that the per-user responses are not storable by any intermediary and vary by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users and admin users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
foreach (Guid userId in _adminUserIds)
_apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult();
}
}
@@ -0,0 +1,465 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
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.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
/// <summary>
/// Contains security tests for the <see cref="DeleteConsumptionItemHistoryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteConsumptionItemHistoryEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private static readonly DateTime s_startedOnUtc = new(2026, 5, 1, 9, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 5, 1, 9, 10, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="DeleteConsumptionItemHistoryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeleteConsumptionItemHistoryEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task DeleteConsumptionItemHistory_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task DeleteConsumptionItemHistory_WhenOwnItemIsDeleted_ShouldReturnNonCacheableResponseWithoutSensitiveData()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
await AssertRecordsAreDeletedAsync(recordId);
}
[Fact]
public async Task DeleteConsumptionItemHistory_WhenAnotherUsersItemIdIsUsed_ShouldSucceedAndPreserveThatUsersRecords()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid ownLibraryId = await SeedLibraryAsync(userId);
Guid ownRecordId = await SeedRecordAsync(userId, ownLibraryId, MediaKind.MusicTrack, Guid.NewGuid(), 60_000);
(Guid otherUserId, _) = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId);
Guid sharedItemId = Guid.NewGuid();
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId, MediaKind.MusicTrack, sharedItemId, 60_000);
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{sharedItemId}/{otherUserLibraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
// Deleting an item that does not belong to the caller succeeds, but it must never remove the other user's rows.
await AssertRecordsArePreservedAsync(otherUserRecordId, ownRecordId);
}
[Fact]
public async Task DeleteConsumptionItemHistory_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndDeleteOnlyTheMatchingRecords()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid ownLibraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid ownRecordId = await SeedRecordAsync(userId, ownLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
(Guid otherUserId, _) = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId);
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{ownLibraryId}?userId={otherUserId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
// The route identifier belongs to the caller, so the spoofed query parameter cannot redirect the deletion.
await AssertRecordsAreDeletedAsync(ownRecordId);
await AssertRecordsArePreservedAsync(otherUserRecordId);
}
[Fact]
public async Task DeleteConsumptionItemHistory_WhenCalledTwice_ShouldSucceedAndStayDeleted()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
// Act
HttpResponseMessage firstResponse = await _client.DeleteAsync(url);
await AssertRecordsAreDeletedAsync(recordId);
HttpResponseMessage secondResponse = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
AssertNonCacheable(secondResponse);
await AssertRecordsAreDeletedAsync(recordId);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task DeleteConsumptionItemHistory_WithInjectionInMediaKind_ShouldRejectWithoutDeletingRows(string maliciousMediaKind)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"/api/v1/users/me/consumption-history/media-items/{Uri.EscapeDataString(maliciousMediaKind)}/{mediaItemId}/{libraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedInjectionAsync(response, maliciousMediaKind, url, "UnsupportedMediaKind");
await AssertRecordsArePreservedAsync(recordId);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task DeleteConsumptionItemHistory_WithInjectionInMediaItemId_ShouldRejectWithoutDeletingRows(string maliciousMediaItemId)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Uri.EscapeDataString(maliciousMediaItemId)}/{libraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedInjectionAsync(response, maliciousMediaItemId, url, "MediaItemIdCannotBeEmpty");
await AssertRecordsArePreservedAsync(recordId);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task DeleteConsumptionItemHistory_WithInjectionInLibraryId_ShouldRejectWithoutDeletingRows(string maliciousLibraryId)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{Uri.EscapeDataString(maliciousLibraryId)}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedInjectionAsync(response, maliciousLibraryId, url, "LibraryIdCannotBeEmpty");
await AssertRecordsArePreservedAsync(recordId);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a media library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Owner Library", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the record.</param>
/// <param name="libraryId">The Id of the library that contains the media item.</param>
/// <param name="mediaKind">The kind of the consumed media item.</param>
/// <param name="mediaItemId">The Id of the consumed media item.</param>
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
/// <returns>The Id of the seeded record.</returns>
private async Task<Guid> SeedRecordAsync(Guid userId, Guid libraryId, MediaKind mediaKind, Guid mediaItemId, long consumedDurationMilliseconds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid recordId = Guid.NewGuid();
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: recordId,
userId: userId,
libraryId: libraryId,
mediaKind: mediaKind,
mediaItemId: mediaItemId,
status: ConsumptionStatus.Stopped,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
consumedDurationMilliseconds: consumedDurationMilliseconds,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 45_000,
lastPositionLocation: null,
lastProgressFraction: 0.5,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return recordId;
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts that a malicious route value is rejected with a client error that never discloses internals or deletes rows.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <param name="requestPath">The request path the value was sent in.</param>
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
private async Task AssertRejectedInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode)
{
string content = await response.Content.ReadAsStringAsync();
// An unparseable route value must never become a server error, and it must never be reported as a successful request.
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.NotEqual(HttpStatusCode.OK, response.StatusCode);
if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
{
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
// The instance is the request path with the rejected payload still in place, independent of how the server escapes it.
string escapedPayload = Uri.EscapeDataString(payload);
int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal);
string? instance = problemDetails["instance"].GetString();
Assert.NotNull(instance);
Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path.");
Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal);
Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNonCacheable(response);
}
else
{
// A payload that carries encoded path separators is rejected by routing before it reaches the endpoint. That is still a safe rejection.
Assert.Contains("/", payload, StringComparison.Ordinal);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
AssertNoSensitiveData(content);
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
// has run, instead of assuming that it already has.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
if (storedRecords.Count == 0)
return;
await Task.Delay(100);
}
Assert.Empty(storedRecords);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
// completion has run, instead of trusting the state observed right after the response.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
Assert.Equal(recordIds.Length, storedRecords.Count);
await Task.Delay(100);
}
Assert.Equal(recordIds.Length, storedRecords.Count);
}
/// <summary>
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,540 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
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.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
/// <summary>
/// Contains security tests for the <see cref="DeleteUserConsumptionItemHistoryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteUserConsumptionItemHistoryEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private const string PATH_PREFIX = "/api/v1/users/";
private const string PATH_SUFFIX = "/consumption-history/media-items/";
private static readonly DateTime s_startedOnUtc = new(2026, 5, 2, 9, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 5, 2, 9, 10, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
private readonly List<Guid> _adminUserIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="DeleteUserConsumptionItemHistoryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeleteUserConsumptionItemHistoryEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task DeleteUserConsumptionItemHistory_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task DeleteUserConsumptionItemHistory_WhenCallerNamesThemselves_ShouldDeleteTheOwnRecords()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"{PATH_PREFIX}{userId}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
await AssertRecordsAreDeletedAsync(recordId);
}
[Fact]
public async Task DeleteUserConsumptionItemHistory_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheRecords()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid targetUserId, _) = await SeedOtherUserAsync();
Guid targetLibraryId = await SeedLibraryAsync(targetUserId);
Guid mediaItemId = Guid.NewGuid();
Guid targetRecordId = await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"{PATH_PREFIX}{targetUserId}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{targetLibraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
string content = await AssertForbiddenAsync(response, url);
AssertNonCacheable(response);
AssertNoSensitiveData(content);
await AssertRecordsArePreservedAsync(targetRecordId);
}
[Fact]
public async Task DeleteUserConsumptionItemHistory_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid otherUserId, _) = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId);
Guid mediaItemId = Guid.NewGuid();
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string foreignUrl = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{otherUserLibraryId}";
string missingUrl = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
// Act
HttpResponseMessage foreignResponse = await _client.DeleteAsync(foreignUrl);
HttpResponseMessage missingResponse = await _client.DeleteAsync(missingUrl);
// Assert
await AssertForbiddenAsync(foreignResponse, foreignUrl);
await AssertForbiddenAsync(missingResponse, missingUrl);
Dictionary<string, JsonElement> foreignProblem = await ReadProblemDetailsAsync(foreignResponse);
Dictionary<string, JsonElement> missingProblem = await ReadProblemDetailsAsync(missingResponse);
Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32());
Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString());
Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString());
Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString());
await AssertRecordsArePreservedAsync(otherUserRecordId);
}
[Fact]
public async Task DeleteUserConsumptionItemHistory_WhenAdminNamesAnotherUser_ShouldDeleteThatUsersRecords()
{
// Arrange
(Guid targetUserId, _) = await SeedOtherUserAsync();
Guid targetLibraryId = await SeedLibraryAsync(targetUserId);
Guid mediaItemId = Guid.NewGuid();
Guid targetRecordId = await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"{PATH_PREFIX}{targetUserId}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{targetLibraryId}";
HttpClient adminClient = _apiFactory.CreateClient();
Guid adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(adminClient);
_adminUserIds.Add(adminUserId);
try
{
// Act
HttpResponseMessage response = await adminClient.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
await AssertRecordsAreDeletedAsync(targetRecordId);
}
finally
{
adminClient.Dispose();
}
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task DeleteUserConsumptionItemHistory_WithInjectionInUserIdRouteValue_ShouldRejectWithoutDeletingRows(string maliciousUserId)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"{PATH_PREFIX}{Uri.EscapeDataString(maliciousUserId)}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedInjectionAsync(response, maliciousUserId, url, "TargetUserIdIsInvalid");
await AssertRecordsArePreservedAsync(recordId);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task DeleteUserConsumptionItemHistory_WithInjectionInMediaKind_ShouldRejectWithoutDeletingRows(string maliciousMediaKind)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"{PATH_PREFIX}{userId}{PATH_SUFFIX}{Uri.EscapeDataString(maliciousMediaKind)}/{mediaItemId}/{libraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedInjectionAsync(response, maliciousMediaKind, url, "UnsupportedMediaKind");
await AssertRecordsArePreservedAsync(recordId);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task DeleteUserConsumptionItemHistory_WithInjectionInMediaItemId_ShouldRejectWithoutDeletingRows(string maliciousMediaItemId)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"{PATH_PREFIX}{userId}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{Uri.EscapeDataString(maliciousMediaItemId)}/{libraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedInjectionAsync(response, maliciousMediaItemId, url, "MediaItemIdCannotBeEmpty");
await AssertRecordsArePreservedAsync(recordId);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task DeleteUserConsumptionItemHistory_WithInjectionInLibraryId_ShouldRejectWithoutDeletingRows(string maliciousLibraryId)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"{PATH_PREFIX}{userId}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{Uri.EscapeDataString(maliciousLibraryId)}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedInjectionAsync(response, maliciousLibraryId, url, "LibraryIdCannotBeEmpty");
await AssertRecordsArePreservedAsync(recordId);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a media library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Owner Library", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the record.</param>
/// <param name="libraryId">The Id of the library that contains the media item.</param>
/// <param name="mediaKind">The kind of the consumed media item.</param>
/// <param name="mediaItemId">The Id of the consumed media item.</param>
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
/// <returns>The Id of the seeded record.</returns>
private async Task<Guid> SeedRecordAsync(Guid userId, Guid libraryId, MediaKind mediaKind, Guid mediaItemId, long consumedDurationMilliseconds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid recordId = Guid.NewGuid();
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: recordId,
userId: userId,
libraryId: libraryId,
mediaKind: mediaKind,
mediaItemId: mediaItemId,
status: ConsumptionStatus.Stopped,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
consumedDurationMilliseconds: consumedDurationMilliseconds,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 45_000,
lastPositionLocation: null,
lastProgressFraction: 0.5,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return recordId;
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts that the response is the exact not authorized problem document and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Reads the problem details document of <paramref name="response"/>.
/// </summary>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The parsed problem details fields.</returns>
private async Task<Dictionary<string, JsonElement>> ReadProblemDetailsAsync(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
return problemDetails!;
}
/// <summary>
/// Asserts that a malicious route value is rejected with a client error that never discloses internals or deletes rows.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <param name="requestPath">The request path the value was sent in.</param>
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
private async Task AssertRejectedInjectionAsync(
HttpResponseMessage response,
string payload,
string requestPath,
string expectedErrorCode)
{
string content = await response.Content.ReadAsStringAsync();
// An unparseable route value must never become a server error, and it must never be reported as a successful request.
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.NotEqual(HttpStatusCode.OK, response.StatusCode);
if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
{
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
// The instance is the request path with the rejected payload still in place, independent of how the server escapes it.
string escapedPayload = Uri.EscapeDataString(payload);
int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal);
string? instance = problemDetails["instance"].GetString();
Assert.NotNull(instance);
Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path.");
Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal);
Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNonCacheable(response);
}
else
{
// A payload that carries encoded path separators is rejected by routing before it reaches the endpoint. That is still a safe rejection.
Assert.Contains("/", payload, StringComparison.Ordinal);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
AssertNoSensitiveData(content);
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
// has run, instead of assuming that it already has.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
if (storedRecords.Count == 0)
return;
await Task.Delay(100);
}
Assert.Empty(storedRecords);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
// completion has run, instead of trusting the state observed right after the response.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
Assert.Equal(recordIds.Length, storedRecords.Count);
await Task.Delay(100);
}
Assert.Equal(recordIds.Length, storedRecords.Count);
}
/// <summary>
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users and admin users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
foreach (Guid userId in _adminUserIds)
_apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult();
}
}
@@ -0,0 +1,440 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord;
/// <summary>
/// Contains security tests for the <see cref="DeleteConsumptionRecordEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteConsumptionRecordEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private static readonly DateTime s_startedOnUtc = new(2026, 5, 1, 9, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 5, 1, 9, 10, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="DeleteConsumptionRecordEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeleteConsumptionRecordEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task DeleteConsumptionRecord_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/users/me/consumption-history/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task DeleteConsumptionRecord_WhenOwnRecordIsDeleted_ShouldReturnNonCacheableResponseWithoutSensitiveData()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
Guid recordId = await SeedRecordAsync(userId, libraryId);
Guid resumePointId = await SeedResumePointAsync(userId, libraryId);
string url = $"/api/v1/users/me/consumption-history/{recordId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
AssertNoSensitiveData(content);
await AssertRecordsAreDeletedAsync(recordId);
await AssertResumePointsArePreservedAsync(resumePointId);
}
[Fact]
public async Task DeleteConsumptionRecord_WhenAnotherUsersRecordIdIsUsed_ShouldSucceedAndPreserveThatRecord()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid ownLibraryId = await SeedLibraryAsync(userId, "Owner Library");
Guid ownRecordId = await SeedRecordAsync(userId, ownLibraryId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId);
string url = $"/api/v1/users/me/consumption-history/{otherUserRecordId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
// Deleting a record that does not belong to the caller succeeds, but it must never remove the other user's row.
await AssertRecordsArePreservedAsync(otherUserRecordId);
await AssertRecordsArePreservedAsync(ownRecordId);
}
[Fact]
public async Task DeleteConsumptionRecord_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndDeleteOnlyTheOwnRecord()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid ownLibraryId = await SeedLibraryAsync(userId, "Owner Library");
Guid ownRecordId = await SeedRecordAsync(userId, ownLibraryId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId);
string url = $"/api/v1/users/me/consumption-history/{ownRecordId}?userId={otherUserId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
// The route identifier belongs to the caller, so the spoofed query parameter cannot redirect the deletion.
await AssertRecordsAreDeletedAsync(ownRecordId);
await AssertRecordsArePreservedAsync(otherUserRecordId);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task DeleteConsumptionRecord_WithInjectionInRecordId_ShouldRejectWithoutDeletingRows(string maliciousRecordId)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
Guid recordId = await SeedRecordAsync(userId, libraryId);
string url = $"/api/v1/users/me/consumption-history/{Uri.EscapeDataString(maliciousRecordId)}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedInjectionAsync(response, maliciousRecordId, url, "ConsumptionRecordIdCannotBeEmpty");
AssertNonCacheable(response);
await AssertRecordsArePreservedAsync(recordId);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="title">The title of the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a consumption record of a music track of <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the record.</param>
/// <param name="libraryId">The Id of the library that contains the consumed track.</param>
/// <returns>The Id of the seeded consumption record.</returns>
private async Task<Guid> SeedRecordAsync(Guid userId, Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid recordId = Guid.NewGuid();
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: recordId,
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: Guid.NewGuid(),
status: ConsumptionStatus.Stopped,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
consumedDurationMilliseconds: 90_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 45_000,
lastPositionLocation: null,
lastProgressFraction: 0.5,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return recordId;
}
/// <summary>
/// Seeds a resume point of <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the resume point.</param>
/// <param name="libraryId">The Id of the library that contains the media item.</param>
/// <returns>The Id of the seeded resume point.</returns>
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid resumePointId = Guid.NewGuid();
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
id: resumePointId,
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: Guid.NewGuid(),
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 45_000,
lastPositionLocation: null,
lastProgressFraction: 0.5,
lastConsumedOnUtc: s_lastActivityOnUtc));
await dbContext.SaveChangesAsync();
return resumePointId;
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts that a malicious route value is rejected without disclosing internals or reaching the data access layer.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <param name="requestPath">The request path the value was sent in.</param>
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
private async Task AssertRejectedInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode)
{
string content = await response.Content.ReadAsStringAsync();
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
{
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
// The instance is the request path with the rejected payload still in place, independent of how the server escapes it.
string escapedPayload = Uri.EscapeDataString(payload);
int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal);
string? instance = problemDetails["instance"].GetString();
Assert.NotNull(instance);
Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path.");
Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal);
Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
}
else
{
// A payload that carries encoded path separators is rejected by routing before it reaches the validator. That is still a safe rejection, so only it may take this branch.
Assert.Contains("/", payload, StringComparison.Ordinal);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
AssertNoSensitiveData(content);
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
// has run, instead of assuming that it already has.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
if (storedRecords.Count == 0)
return;
await Task.Delay(100);
}
Assert.Empty(storedRecords);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
// completion has run, instead of trusting the state observed right after the response.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
Assert.Equal(recordIds.Length, storedRecords.Count);
await Task.Delay(100);
}
Assert.Equal(recordIds.Length, storedRecords.Count);
}
/// <summary>
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
/// </summary>
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaResumePointEntity> storedResumePoints = [];
// The request transaction is committed or rolled back after the response has been sent, so a resume point that must survive is read until
// that completion has run, instead of trusting the state observed right after the response.
for (int attempt = 0; attempt < 20; attempt++)
{
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
.ToListAsync();
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
await Task.Delay(100);
}
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
}
/// <summary>
/// Asserts that the per-user responses are not storable by any intermediary and vary by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,526 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord;
/// <summary>
/// Contains security tests for the <see cref="DeleteUserConsumptionRecordEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteUserConsumptionRecordEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private static readonly DateTime s_startedOnUtc = new(2026, 5, 2, 9, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 5, 2, 9, 10, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
private readonly List<Guid> _adminUserIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="DeleteUserConsumptionRecordEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeleteUserConsumptionRecordEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task DeleteUserConsumptionRecord_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-history/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task DeleteUserConsumptionRecord_WhenCallerNamesThemselves_ShouldDeleteTheOwnRecord()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
Guid recordId = await SeedRecordAsync(userId, libraryId);
string url = $"/api/v1/users/{userId}/consumption-history/{recordId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
await AssertRecordsAreDeletedAsync(recordId);
}
[Fact]
public async Task DeleteUserConsumptionRecord_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheRecord()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid targetUserId, _) = await SeedOtherUserAsync();
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
Guid targetRecordId = await SeedRecordAsync(targetUserId, targetLibraryId);
string url = $"/api/v1/users/{targetUserId}/consumption-history/{targetRecordId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
string content = await AssertForbiddenAsync(response, url);
AssertNonCacheable(response);
AssertNoSensitiveData(content);
await AssertRecordsArePreservedAsync(targetRecordId);
}
[Fact]
public async Task DeleteUserConsumptionRecord_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid otherUserId, _) = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId);
string foreignUrl = $"/api/v1/users/{otherUserId}/consumption-history/{otherUserRecordId}";
string missingUrl = $"/api/v1/users/{Guid.NewGuid()}/consumption-history/{Guid.NewGuid()}";
// Act
HttpResponseMessage foreignResponse = await _client.DeleteAsync(foreignUrl);
HttpResponseMessage missingResponse = await _client.DeleteAsync(missingUrl);
// Assert
await AssertForbiddenAsync(foreignResponse, foreignUrl);
await AssertForbiddenAsync(missingResponse, missingUrl);
Dictionary<string, JsonElement> foreignProblem = await ReadProblemDetailsAsync(foreignResponse);
Dictionary<string, JsonElement> missingProblem = await ReadProblemDetailsAsync(missingResponse);
Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32());
Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString());
Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString());
Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString());
await AssertRecordsArePreservedAsync(otherUserRecordId);
}
[Fact]
public async Task DeleteUserConsumptionRecord_WhenAdminNamesAnotherUser_ShouldDeleteThatUsersRecord()
{
// Arrange
(Guid targetUserId, _) = await SeedOtherUserAsync();
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
Guid targetRecordId = await SeedRecordAsync(targetUserId, targetLibraryId);
Guid targetResumePointId = await SeedResumePointAsync(targetUserId, targetLibraryId);
string url = $"/api/v1/users/{targetUserId}/consumption-history/{targetRecordId}";
HttpClient adminClient = _apiFactory.CreateClient();
Guid adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(adminClient);
_adminUserIds.Add(adminUserId);
try
{
// Act
HttpResponseMessage response = await adminClient.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
await AssertRecordsAreDeletedAsync(targetRecordId);
await AssertResumePointsArePreservedAsync(targetResumePointId);
}
finally
{
adminClient.Dispose();
}
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task DeleteUserConsumptionRecord_WithInjectionInUserIdRouteValue_ShouldRejectWithoutDeletingRows(string maliciousUserId)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
Guid recordId = await SeedRecordAsync(userId, libraryId);
string url = $"/api/v1/users/{Uri.EscapeDataString(maliciousUserId)}/consumption-history/{recordId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedInjectionAsync(response, maliciousUserId, url, "TargetUserIdIsInvalid");
AssertNonCacheable(response);
await AssertRecordsArePreservedAsync(recordId);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task DeleteUserConsumptionRecord_WithInjectionInRecordIdRouteValue_ShouldRejectWithoutDeletingRows(string maliciousRecordId)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
Guid recordId = await SeedRecordAsync(userId, libraryId);
string url = $"/api/v1/users/{userId}/consumption-history/{Uri.EscapeDataString(maliciousRecordId)}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedInjectionAsync(response, maliciousRecordId, url, "ConsumptionRecordIdCannotBeEmpty");
AssertNonCacheable(response);
await AssertRecordsArePreservedAsync(recordId);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="title">The title of the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a consumption record of a music track of <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the record.</param>
/// <param name="libraryId">The Id of the library that contains the consumed track.</param>
/// <returns>The Id of the seeded consumption record.</returns>
private async Task<Guid> SeedRecordAsync(Guid userId, Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid recordId = Guid.NewGuid();
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: recordId,
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: Guid.NewGuid(),
status: ConsumptionStatus.Stopped,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
consumedDurationMilliseconds: 90_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 45_000,
lastPositionLocation: null,
lastProgressFraction: 0.5,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return recordId;
}
/// <summary>
/// Seeds a resume point of <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the resume point.</param>
/// <param name="libraryId">The Id of the library that contains the media item.</param>
/// <returns>The Id of the seeded resume point.</returns>
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid resumePointId = Guid.NewGuid();
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
id: resumePointId,
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: Guid.NewGuid(),
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 45_000,
lastPositionLocation: null,
lastProgressFraction: 0.5,
lastConsumedOnUtc: s_lastActivityOnUtc));
await dbContext.SaveChangesAsync();
return resumePointId;
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts that the response is the exact not authorized problem document and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
return content;
}
/// <summary>
/// Reads the problem details document of <paramref name="response"/>.
/// </summary>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The parsed problem details fields.</returns>
private async Task<Dictionary<string, JsonElement>> ReadProblemDetailsAsync(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
return problemDetails!;
}
/// <summary>
/// Asserts that a malicious route value is rejected without disclosing internals or reaching the data access layer.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <param name="requestPath">The request path the value was sent in.</param>
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
private async Task AssertRejectedInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode)
{
string content = await response.Content.ReadAsStringAsync();
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
{
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
// The instance is the request path with the rejected payload still in place, independent of how the server escapes it.
string escapedPayload = Uri.EscapeDataString(payload);
int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal);
string? instance = problemDetails["instance"].GetString();
Assert.NotNull(instance);
Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path.");
Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal);
Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
}
else
{
// A payload that carries encoded path separators is rejected by routing before it reaches the validator. That is still a safe rejection, so only it may take this branch.
Assert.Contains("/", payload, StringComparison.Ordinal);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
AssertNoSensitiveData(content);
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
// has run, instead of assuming that it already has.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
if (storedRecords.Count == 0)
return;
await Task.Delay(100);
}
Assert.Empty(storedRecords);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
// completion has run, instead of trusting the state observed right after the response.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
Assert.Equal(recordIds.Length, storedRecords.Count);
await Task.Delay(100);
}
Assert.Equal(recordIds.Length, storedRecords.Count);
}
/// <summary>
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
/// </summary>
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaResumePointEntity> storedResumePoints = [];
// The request transaction is committed or rolled back after the response has been sent, so a resume point that must survive is read until
// that completion has run, instead of trusting the state observed right after the response.
for (int attempt = 0; attempt < 20; attempt++)
{
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
.ToListAsync();
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
await Task.Delay(100);
}
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
}
/// <summary>
/// Asserts that the per-user responses are not storable by any intermediary and vary by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users and admin users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
foreach (Guid userId in _adminUserIds)
_apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult();
}
}
@@ -0,0 +1,418 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.MediaConsumption;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics;
/// <summary>
/// Contains security tests for the <see cref="GetAllUsersConsumptionStatisticsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetAllUsersConsumptionStatisticsEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private const string PATH = "/api/v1/users/consumption-statistics";
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 3, 1, 10, 5, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
private readonly List<Guid> _adminUserIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetAllUsersConsumptionStatisticsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetAllUsersConsumptionStatisticsEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetAllUsersConsumptionStatistics_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = PATH;
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task GetAllUsersConsumptionStatistics_WhenCalledByRegularUser_ShouldReturnForbiddenWithoutAnyUserStatistics()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid otherUserId, string otherUsername) = await SeedOtherUserAsync();
await SeedCompletedMusicSessionAsync(otherUserId);
string url = PATH;
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertForbiddenAsync(response, url);
AssertNonCacheable(response);
Assert.DoesNotContain(otherUserId.ToString(), content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(otherUsername, content, StringComparison.Ordinal);
Assert.DoesNotContain("\"users\"", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("\"total\"", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetAllUsersConsumptionStatistics_WhenCalledByAdmin_ShouldReturnEveryUsersStatisticsWithoutSensitiveData()
{
// Arrange
(Guid userId, _) = await SeedOtherUserAsync();
await SeedCompletedMusicSessionAsync(userId);
HttpClient adminClient = _apiFactory.CreateClient();
Guid adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(adminClient);
_adminUserIds.Add(adminUserId);
string url = PATH;
try
{
// Act
HttpResponseMessage response = await adminClient.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
AssertNoSensitiveData(content);
AssertNoDatabaseOnlyFields(content);
AllUsersConsumptionStatisticsResponse? statistics = JsonSerializer.Deserialize<AllUsersConsumptionStatisticsResponse>(content, _jsonOptions);
Assert.NotNull(statistics);
// The only records of this test belong to the seeded user, so no other account may appear in the admin summary.
ConsumptionSummaryResponse summary = Assert.Single(statistics!.Users);
Assert.Equal(userId, summary.UserId);
Assert.Equal(60d, summary.TotalConsumedDurationInSeconds, 3);
Assert.Equal(1, summary.CountedSessionCount);
Assert.Equal(60d, statistics.Total.TotalConsumedDurationInSeconds, 3);
Assert.Equal(1, statistics.Total.CountedSessionCount);
Assert.DoesNotContain(adminUserId.ToString(), content, StringComparison.OrdinalIgnoreCase);
}
finally
{
adminClient.Dispose();
}
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task GetAllUsersConsumptionStatistics_WithInjectionInLibraryId_ShouldRejectWithoutLeakingData(string maliciousLibraryId)
{
// Arrange
(Guid userId, _) = await SeedOtherUserAsync();
await SeedCompletedMusicSessionAsync(userId);
HttpClient adminClient = _apiFactory.CreateClient();
Guid adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(adminClient);
_adminUserIds.Add(adminUserId);
string url = $"{PATH}?libraryId={Uri.EscapeDataString(maliciousLibraryId)}";
try
{
// Act
HttpResponseMessage response = await adminClient.GetAsync(url);
// Assert
string content = await AssertValidationProblemAsync(response, PATH, "LibraryIdCannotBeEmpty");
AssertNonCacheable(response);
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == userId));
}
finally
{
adminClient.Dispose();
}
}
[Theory]
[InlineData("999")] // Out of range numeric value.
[InlineData("not-a-media-kind")] // Textual value that is not an enum member.
public async Task GetAllUsersConsumptionStatistics_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
{
// Arrange
(Guid userId, _) = await SeedOtherUserAsync();
await SeedCompletedMusicSessionAsync(userId);
HttpClient adminClient = _apiFactory.CreateClient();
Guid adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(adminClient);
_adminUserIds.Add(adminUserId);
string url = $"{PATH}?mediaKind={Uri.EscapeDataString(mediaKind)}";
try
{
// Act
HttpResponseMessage response = await adminClient.GetAsync(url);
// Assert
// The media kind is carried as text, so an unknown or numeric name reaches the validator and is reported as an
// unsupported kind instead of being rejected by request binding.
await AssertRejectedMediaKindAsync(response, PATH);
}
finally
{
adminClient.Dispose();
}
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/> and one completed consumption session of one of its tracks.
/// </summary>
/// <param name="userId">The Id of the user that owns the records.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedCompletedMusicSessionAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
string suffix = Guid.NewGuid().ToString("N");
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: $"Library-{suffix}", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: Guid.NewGuid(),
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: Guid.NewGuid(),
status: ConsumptionStatus.Completed,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
consumedDurationMilliseconds: 60_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 60_000,
lastProgressFraction: 1.0,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts that the response is the exact not authorized problem document and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts the shape of a validation problem details response and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts that an unparseable media kind is rejected without returning data or disclosing internals.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]);
AssertNonCacheable(response);
AssertNoSensitiveData(content);
Assert.DoesNotContain("\"users\"", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("\"total\"", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Asserts that the serialized statistics expose only the fields of their documented response contract.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoDatabaseOnlyFields(string content)
{
// The user Id is a documented statistics field, so it is not asserted absent here.
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users and admin users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
foreach (Guid userId in _adminUserIds)
_apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult();
}
}
@@ -0,0 +1,392 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.MediaConsumption;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
/// <summary>
/// Contains security tests for the <see cref="GetConsumptionStatisticsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetConsumptionStatisticsEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private const string PATH = "/api/v1/users/me/consumption-statistics";
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 3, 1, 10, 5, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetConsumptionStatisticsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetConsumptionStatisticsEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetConsumptionStatistics_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = PATH;
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task GetConsumptionStatistics_WhenSuccessful_ShouldReturnOnlyCallersStatisticsWithoutSensitiveData()
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedCompletedMusicSessionAsync(callerId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
await SeedCompletedMusicSessionAsync(otherUserId);
string url = PATH;
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
AssertNoSensitiveData(content);
AssertNoDatabaseOnlyFields(content);
Assert.DoesNotContain(otherUserId.ToString(), content, StringComparison.OrdinalIgnoreCase);
ConsumptionSummaryResponse? statistics = JsonSerializer.Deserialize<ConsumptionSummaryResponse>(content, _jsonOptions);
Assert.NotNull(statistics);
// The user Id is part of the documented statistics contract, so it must be present and must be the callers.
Assert.Equal(callerId, statistics!.UserId);
Assert.Equal(60d, statistics.TotalConsumedDurationInSeconds, 3);
Assert.Equal(1, statistics.CountedSessionCount);
Assert.Equal(1, statistics.CompletedSessionCount);
Assert.Equal(0, statistics.StoppedSessionCount);
MediaKindConsumptionSummaryResponse kind = Assert.Single(statistics.MediaKindSummaries);
Assert.Equal(MediaKind.MusicTrack, kind.MediaKind);
}
[Fact]
public async Task GetConsumptionStatistics_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndReturnCallersStatistics()
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedCompletedMusicSessionAsync(callerId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
await SeedCompletedMusicSessionAsync(otherUserId);
string url = $"{PATH}?userId={otherUserId}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
ConsumptionSummaryResponse? statistics = JsonSerializer.Deserialize<ConsumptionSummaryResponse>(content, _jsonOptions);
Assert.NotNull(statistics);
Assert.Equal(callerId, statistics!.UserId);
Assert.DoesNotContain(otherUserId.ToString(), content, StringComparison.OrdinalIgnoreCase);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task GetConsumptionStatistics_WithInjectionInLibraryId_ShouldRejectWithoutLeakingData(string maliciousLibraryId)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedCompletedMusicSessionAsync(callerId);
string url = $"{PATH}?libraryId={Uri.EscapeDataString(maliciousLibraryId)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertValidationProblemAsync(response, PATH, "LibraryIdCannotBeEmpty");
AssertNonCacheable(response);
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task GetConsumptionStatistics_WithInjectionInFromUtc_ShouldRejectWithoutLeakingData(string maliciousFromUtc)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedCompletedMusicSessionAsync(callerId);
string url = $"{PATH}?fromUtc={Uri.EscapeDataString(maliciousFromUtc)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertValidationProblemAsync(response, PATH, "ConsumptionDateRangeIsInvalid");
AssertNonCacheable(response);
Assert.DoesNotContain(maliciousFromUtc, content, StringComparison.Ordinal);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
}
[Theory]
[InlineData("999")] // Out of range numeric value.
[InlineData("not-a-media-kind")] // Textual value that is not an enum member.
public async Task GetConsumptionStatistics_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedCompletedMusicSessionAsync(callerId);
string url = $"{PATH}?mediaKind={Uri.EscapeDataString(mediaKind)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
// The media kind is carried as text, so an unknown or numeric name reaches the validator and is reported as an
// unsupported kind instead of being rejected by request binding.
await AssertRejectedMediaKindAsync(response, PATH);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/> and one completed consumption session of one of its tracks.
/// </summary>
/// <param name="userId">The Id of the user that owns the records.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedCompletedMusicSessionAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
string suffix = Guid.NewGuid().ToString("N");
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: $"Library-{suffix}", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: Guid.NewGuid(),
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: Guid.NewGuid(),
status: ConsumptionStatus.Completed,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
consumedDurationMilliseconds: 60_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 60_000,
lastProgressFraction: 1.0,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts the shape of a validation problem details response and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts that an unparseable media kind is rejected without returning data or disclosing internals.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]);
AssertNonCacheable(response);
AssertNoSensitiveData(content);
Assert.DoesNotContain("\"mediaKindSummaries\"", content, StringComparison.Ordinal);
Assert.DoesNotContain("\"countedSessionCount\"", content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Asserts that the serialized statistics expose only the fields of their documented response contract.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoDatabaseOnlyFields(string content)
{
// The user Id is a documented statistics field, so it is not asserted absent here.
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,461 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.MediaConsumption;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
/// <summary>
/// Contains security tests for the <see cref="GetUserConsumptionStatisticsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUserConsumptionStatisticsEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private const string PATH_PREFIX = "/api/v1/users/";
private const string PATH_SUFFIX = "/consumption-statistics";
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 3, 1, 10, 5, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
private readonly List<Guid> _adminUserIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetUserConsumptionStatisticsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetUserConsumptionStatisticsEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetUserConsumptionStatistics_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task GetUserConsumptionStatistics_WhenAnotherUsersStatisticsAreRequested_ShouldReturnForbiddenWithoutDisclosingData()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid otherUserId, _) = await SeedOtherUserAsync();
await SeedCompletedMusicSessionAsync(otherUserId);
string url = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertForbiddenAsync(response, url);
AssertNonCacheable(response);
Assert.DoesNotContain("countedSessionCount", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("totalConsumedDurationInSeconds", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetUserConsumptionStatistics_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid otherUserId, _) = await SeedOtherUserAsync();
await SeedCompletedMusicSessionAsync(otherUserId);
string foreignUrl = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
string missingUrl = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
// Act
HttpResponseMessage foreignResponse = await _client.GetAsync(foreignUrl);
HttpResponseMessage missingResponse = await _client.GetAsync(missingUrl);
// Assert
await AssertForbiddenAsync(foreignResponse, foreignUrl);
await AssertForbiddenAsync(missingResponse, missingUrl);
Dictionary<string, JsonElement> foreignProblem = await ReadProblemDetailsAsync(foreignResponse);
Dictionary<string, JsonElement> missingProblem = await ReadProblemDetailsAsync(missingResponse);
Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32());
Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString());
Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString());
Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString());
}
[Fact]
public async Task GetUserConsumptionStatistics_WhenAdminRequestsAnotherUser_ShouldReturnOnlyThatUsersStatistics()
{
// Arrange
(Guid otherUserId, _) = await SeedOtherUserAsync();
await SeedCompletedMusicSessionAsync(otherUserId);
HttpClient adminClient = _apiFactory.CreateClient();
Guid adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(adminClient);
_adminUserIds.Add(adminUserId);
string url = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
try
{
// Act
HttpResponseMessage response = await adminClient.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
AssertNoSensitiveData(content);
AssertNoDatabaseOnlyFields(content);
ConsumptionSummaryResponse? statistics = JsonSerializer.Deserialize<ConsumptionSummaryResponse>(content, _jsonOptions);
Assert.NotNull(statistics);
Assert.Equal(otherUserId, statistics!.UserId);
Assert.Equal(60d, statistics.TotalConsumedDurationInSeconds, 3);
Assert.Equal(1, statistics.CountedSessionCount);
}
finally
{
adminClient.Dispose();
}
}
[Fact]
public async Task GetUserConsumptionStatistics_WhenCallerNamesThemselves_ShouldReturnOwnStatistics()
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedCompletedMusicSessionAsync(callerId);
string url = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
ConsumptionSummaryResponse? statistics = JsonSerializer.Deserialize<ConsumptionSummaryResponse>(content, _jsonOptions);
Assert.NotNull(statistics);
Assert.Equal(callerId, statistics!.UserId);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task GetUserConsumptionStatistics_WithInjectionInUserIdRouteValue_ShouldRejectWithoutLeakingData(string maliciousUserId)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedCompletedMusicSessionAsync(callerId);
string url = $"{PATH_PREFIX}{Uri.EscapeDataString(maliciousUserId)}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertRejectedRouteValueAsync(response, maliciousUserId, PATH_PREFIX, PATH_SUFFIX, "TargetUserIdIsInvalid");
AssertNonCacheable(response);
Assert.DoesNotContain(maliciousUserId, content, StringComparison.Ordinal);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
}
[Theory]
[InlineData("999")] // Out of range numeric value.
[InlineData("not-a-media-kind")] // Textual value that is not an enum member.
public async Task GetUserConsumptionStatistics_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedCompletedMusicSessionAsync(callerId);
string path = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
string url = $"{path}?mediaKind={Uri.EscapeDataString(mediaKind)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
// The media kind is carried as text, so an unknown or numeric name reaches the validator and is reported as an
// unsupported kind instead of being rejected by request binding.
await AssertRejectedMediaKindAsync(response, path);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/> and one completed consumption session of one of its tracks.
/// </summary>
/// <param name="userId">The Id of the user that owns the records.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedCompletedMusicSessionAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
string suffix = Guid.NewGuid().ToString("N");
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: $"Library-{suffix}", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: Guid.NewGuid(),
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: Guid.NewGuid(),
status: ConsumptionStatus.Completed,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
consumedDurationMilliseconds: 60_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 60_000,
lastProgressFraction: 1.0,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts that the response is the exact not authorized problem document and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Reads the problem details document of <paramref name="response"/>.
/// </summary>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The parsed problem details fields.</returns>
private async Task<Dictionary<string, JsonElement>> ReadProblemDetailsAsync(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
return problemDetails!;
}
/// <summary>
/// Asserts that a malicious route value is rejected without disclosing internals.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <param name="pathPrefix">The request path that precedes the malicious value.</param>
/// <param name="pathSuffix">The request path that follows the malicious value.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertRejectedRouteValueAsync(HttpResponseMessage response, string payload, string pathPrefix, string pathSuffix, string expectedErrorCode)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
// The instance is the request path with the rejected payload in place, so decoding the middle segment must give the payload back.
string? instance = problemDetails["instance"].GetString();
Assert.NotNull(instance);
Assert.StartsWith(pathPrefix, instance, StringComparison.Ordinal);
Assert.EndsWith(pathSuffix, instance, StringComparison.Ordinal);
string encodedSegment = instance![pathPrefix.Length..(instance.Length - pathSuffix.Length)];
Assert.Equal(payload, Uri.UnescapeDataString(encodedSegment));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts that an unparseable media kind is rejected without returning data or disclosing internals.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]);
AssertNonCacheable(response);
AssertNoSensitiveData(content);
Assert.DoesNotContain("\"mediaKindSummaries\"", content, StringComparison.Ordinal);
Assert.DoesNotContain("\"countedSessionCount\"", content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Asserts that the serialized statistics expose only the fields of their documented response contract.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoDatabaseOnlyFields(string content)
{
// The user Id is a documented statistics field, so it is not asserted absent here.
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users and admin users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
foreach (Guid userId in _adminUserIds)
_apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult();
}
}
@@ -0,0 +1,460 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
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.MediaConsumption;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption;
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.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.GetGenreConsumption;
/// <summary>
/// Contains security tests for the <see cref="GetGenreConsumptionEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetGenreConsumptionEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private const string PATH = "/api/v1/users/me/consumption-statistics/genres";
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 3, 1, 10, 5, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
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 TrackEntityFixture _trackEntityFixture = new();
private readonly GenreEntityFixture _genreEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetGenreConsumptionEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetGenreConsumptionEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetGenreConsumption_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = PATH;
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task GetGenreConsumption_WhenSuccessful_ShouldReturnOnlyCallersGenresWithoutSensitiveData()
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
string callerGenre = await SeedGenreConsumptionAsync(callerId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
string url = PATH;
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
AssertNoSensitiveData(content);
AssertNoDatabaseOnlyFields(content);
Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
List<GenreConsumptionResponse>? genres = JsonSerializer.Deserialize<List<GenreConsumptionResponse>>(content, _jsonOptions);
Assert.NotNull(genres);
GenreConsumptionResponse genre = Assert.Single(genres!);
Assert.Equal(callerGenre.ToLowerInvariant(), genre.Name);
Assert.Equal(1, genre.ConsumedItemCount);
Assert.Equal(60d, genre.ConsumedDurationInSeconds, 3);
}
[Fact]
public async Task GetGenreConsumption_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndReturnCallersGenres()
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
string callerGenre = await SeedGenreConsumptionAsync(callerId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
string url = $"{PATH}?userId={otherUserId}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
List<GenreConsumptionResponse>? genres = JsonSerializer.Deserialize<List<GenreConsumptionResponse>>(content, _jsonOptions);
Assert.NotNull(genres);
GenreConsumptionResponse genre = Assert.Single(genres!);
Assert.Equal(callerGenre.ToLowerInvariant(), genre.Name);
Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task GetGenreConsumption_WithInjectionInLibraryId_ShouldRejectWithoutLeakingData(string maliciousLibraryId)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedGenreConsumptionAsync(callerId);
string url = $"{PATH}?libraryId={Uri.EscapeDataString(maliciousLibraryId)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertValidationProblemAsync(response, PATH, "LibraryIdCannotBeEmpty");
AssertNonCacheable(response);
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
}
[Theory]
[InlineData("999")] // Out of range numeric value.
[InlineData("not-a-media-kind")] // Textual value that is not an enum member.
public async Task GetGenreConsumption_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedGenreConsumptionAsync(callerId);
string url = $"{PATH}?mediaKind={Uri.EscapeDataString(mediaKind)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
// The media kind is carried as text, so an unknown or numeric name reaches the validator and is reported as an
// unsupported kind instead of being rejected by request binding.
await AssertRejectedMediaKindAsync(response, PATH);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task GetGenreConsumption_WithInjectionInFromUtc_ShouldRejectWithoutLeakingData(string maliciousFromUtc)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedGenreConsumptionAsync(callerId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
string url = $"{PATH}?fromUtc={Uri.EscapeDataString(maliciousFromUtc)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertSafeDatePayloadResponseAsync(response, maliciousFromUtc);
Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == otherUserId));
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task GetGenreConsumption_WithInjectionInToUtc_ShouldRejectWithoutLeakingData(string maliciousToUtc)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedGenreConsumptionAsync(callerId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
string url = $"{PATH}?toUtc={Uri.EscapeDataString(maliciousToUtc)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertSafeDatePayloadResponseAsync(response, maliciousToUtc);
Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == otherUserId));
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a uniquely genred track in a library owned by <paramref name="userId"/> and one completed session of it.
/// </summary>
/// <param name="userId">The Id of the user that owns the records.</param>
/// <returns>The unique name of the seeded genre.</returns>
private async Task<string> SeedGenreConsumptionAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
string suffix = Guid.NewGuid().ToString("N")[..8];
// Genre names are the primary key of a shared table, so every seeded name carries a unique suffix.
string genreName = $"Genre-{suffix}";
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: $"Library-{suffix}", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: $"Artist-{suffix}", includeAlbums: false, includeContributors: false, includeMetadata: false));
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: $"Album-{suffix}", includeTracks: false, includeMetadata: false));
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: $"Track-{suffix}", includeMetadata: false);
GenreEntity genre = _genreEntityFixture.Create(name: genreName);
track.Genres.Add(genre);
dbContext.Tracks.Add(track);
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: Guid.NewGuid(),
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: trackId,
status: ConsumptionStatus.Completed,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
consumedDurationMilliseconds: 60_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 60_000,
lastProgressFraction: 1.0,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return genreName;
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts the shape of a validation problem details response and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts that an unparseable media kind is rejected without returning data or disclosing internals.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]);
AssertNonCacheable(response);
AssertNoSensitiveData(content);
Assert.DoesNotContain("\"consumedItemCount\"", content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that a malicious date bound never causes a server error, never leaks internals, and never returns data of another user.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertSafeDatePayloadResponseAsync(HttpResponseMessage response, string payload)
{
string content = await response.Content.ReadAsStringAsync();
// A bound date is parsed before the handler runs, so an unparseable value must either be ignored or rejected, but it must never reach the
// storage medium, fail the request, or disclose internals.
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.True(
response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.BadRequest || response.StatusCode == HttpStatusCode.UnprocessableEntity,
$"Unexpected status code {response.StatusCode} for a date bound payload.");
AssertNoSensitiveData(content);
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
return content;
}
/// <summary>
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Asserts that the serialized genres expose only the fields of their documented response contract.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoDatabaseOnlyFields(string content)
{
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,617 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
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.MediaConsumption;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption;
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.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.GetGenreConsumption;
/// <summary>
/// Contains security tests for the <see cref="GetUserGenreConsumptionEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUserGenreConsumptionEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private const string PATH_PREFIX = "/api/v1/users/";
private const string PATH_SUFFIX = "/consumption-statistics/genres";
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 3, 1, 10, 5, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
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 TrackEntityFixture _trackEntityFixture = new();
private readonly GenreEntityFixture _genreEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
private readonly List<Guid> _adminUserIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetUserGenreConsumptionEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetUserGenreConsumptionEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetUserGenreConsumption_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task GetUserGenreConsumption_WhenAnotherUsersGenresAreRequested_ShouldReturnForbiddenWithoutDisclosingData()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
string url = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertForbiddenAsync(response, url);
AssertNonCacheable(response);
Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("consumedItemCount", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetUserGenreConsumption_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid otherUserId, _) = await SeedOtherUserAsync();
await SeedGenreConsumptionAsync(otherUserId);
string foreignUrl = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
string missingUrl = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
// Act
HttpResponseMessage foreignResponse = await _client.GetAsync(foreignUrl);
HttpResponseMessage missingResponse = await _client.GetAsync(missingUrl);
// Assert
await AssertForbiddenAsync(foreignResponse, foreignUrl);
await AssertForbiddenAsync(missingResponse, missingUrl);
Dictionary<string, JsonElement> foreignProblem = await ReadProblemDetailsAsync(foreignResponse);
Dictionary<string, JsonElement> missingProblem = await ReadProblemDetailsAsync(missingResponse);
Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32());
Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString());
Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString());
Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString());
}
[Fact]
public async Task GetUserGenreConsumption_WhenAdminRequestsAnotherUser_ShouldReturnOnlyThatUsersGenres()
{
// Arrange
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
HttpClient adminClient = _apiFactory.CreateClient();
Guid adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(adminClient);
_adminUserIds.Add(adminUserId);
string url = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
try
{
// Act
HttpResponseMessage response = await adminClient.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
AssertNoSensitiveData(content);
AssertNoDatabaseOnlyFields(content);
List<GenreConsumptionResponse>? genres = JsonSerializer.Deserialize<List<GenreConsumptionResponse>>(content, _jsonOptions);
Assert.NotNull(genres);
GenreConsumptionResponse genre = Assert.Single(genres!);
Assert.Equal(otherGenre.ToLowerInvariant(), genre.Name);
Assert.Equal(1, genre.ConsumedItemCount);
}
finally
{
adminClient.Dispose();
}
}
[Fact]
public async Task GetUserGenreConsumption_WhenCallerNamesThemselves_ShouldReturnOwnGenres()
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
string callerGenre = await SeedGenreConsumptionAsync(callerId);
string url = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
List<GenreConsumptionResponse>? genres = JsonSerializer.Deserialize<List<GenreConsumptionResponse>>(content, _jsonOptions);
Assert.NotNull(genres);
GenreConsumptionResponse genre = Assert.Single(genres!);
Assert.Equal(callerGenre.ToLowerInvariant(), genre.Name);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task GetUserGenreConsumption_WithInjectionInUserIdRouteValue_ShouldRejectWithoutLeakingData(string maliciousUserId)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedGenreConsumptionAsync(callerId);
string url = $"{PATH_PREFIX}{Uri.EscapeDataString(maliciousUserId)}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertRejectedRouteValueAsync(response, maliciousUserId, PATH_PREFIX, PATH_SUFFIX, "TargetUserIdIsInvalid");
AssertNonCacheable(response);
Assert.DoesNotContain(maliciousUserId, content, StringComparison.Ordinal);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task GetUserGenreConsumption_WithInjectionInLibraryId_ShouldRejectWithoutLeakingData(string maliciousLibraryId)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedGenreConsumptionAsync(callerId);
string path = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
string url = $"{path}?libraryId={Uri.EscapeDataString(maliciousLibraryId)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertValidationProblemAsync(response, path, "LibraryIdCannotBeEmpty");
AssertNonCacheable(response);
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
}
[Theory]
[InlineData("999")] // Out of range numeric value.
[InlineData("not-a-media-kind")] // Textual value that is not an enum member.
public async Task GetUserGenreConsumption_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedGenreConsumptionAsync(callerId);
string path = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
string url = $"{path}?mediaKind={Uri.EscapeDataString(mediaKind)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
// The media kind is carried as text, so an unknown or numeric name reaches the validator and is reported as an
// unsupported kind instead of being rejected by request binding.
await AssertRejectedMediaKindAsync(response, path);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task GetUserGenreConsumption_WithInjectionInFromUtc_ShouldRejectWithoutLeakingData(string maliciousFromUtc)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedGenreConsumptionAsync(callerId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
string path = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
string url = $"{path}?fromUtc={Uri.EscapeDataString(maliciousFromUtc)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertSafeDatePayloadResponseAsync(response, maliciousFromUtc);
Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == otherUserId));
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task GetUserGenreConsumption_WithInjectionInToUtc_ShouldRejectWithoutLeakingData(string maliciousToUtc)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedGenreConsumptionAsync(callerId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
string path = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
string url = $"{path}?toUtc={Uri.EscapeDataString(maliciousToUtc)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertSafeDatePayloadResponseAsync(response, maliciousToUtc);
Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == otherUserId));
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a uniquely genred track in a library owned by <paramref name="userId"/> and one completed session of it.
/// </summary>
/// <param name="userId">The Id of the user that owns the records.</param>
/// <returns>The unique name of the seeded genre.</returns>
private async Task<string> SeedGenreConsumptionAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
string suffix = Guid.NewGuid().ToString("N")[..8];
// Genre names are the primary key of a shared table, so every seeded name carries a unique suffix.
string genreName = $"Genre-{suffix}";
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: $"Library-{suffix}", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: $"Artist-{suffix}", includeAlbums: false, includeContributors: false, includeMetadata: false));
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: $"Album-{suffix}", includeTracks: false, includeMetadata: false));
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: $"Track-{suffix}", includeMetadata: false);
GenreEntity genre = _genreEntityFixture.Create(name: genreName);
track.Genres.Add(genre);
dbContext.Tracks.Add(track);
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: Guid.NewGuid(),
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: trackId,
status: ConsumptionStatus.Completed,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
consumedDurationMilliseconds: 60_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 60_000,
lastProgressFraction: 1.0,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return genreName;
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts that the response is the exact not authorized problem document and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Reads the problem details document of <paramref name="response"/>.
/// </summary>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The parsed problem details fields.</returns>
private async Task<Dictionary<string, JsonElement>> ReadProblemDetailsAsync(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
return problemDetails!;
}
/// <summary>
/// Asserts that a malicious route value is rejected without disclosing internals.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <param name="pathPrefix">The request path that precedes the malicious value.</param>
/// <param name="pathSuffix">The request path that follows the malicious value.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertRejectedRouteValueAsync(HttpResponseMessage response, string payload, string pathPrefix, string pathSuffix, string expectedErrorCode)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
// The instance is the request path with the rejected payload in place, so decoding the middle segment must give the payload back.
string? instance = problemDetails["instance"].GetString();
Assert.NotNull(instance);
Assert.StartsWith(pathPrefix, instance, StringComparison.Ordinal);
Assert.EndsWith(pathSuffix, instance, StringComparison.Ordinal);
string encodedSegment = instance![pathPrefix.Length..(instance.Length - pathSuffix.Length)];
Assert.Equal(payload, Uri.UnescapeDataString(encodedSegment));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts the shape of a validation problem details response and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts that an unparseable media kind is rejected without returning data or disclosing internals.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]);
AssertNonCacheable(response);
AssertNoSensitiveData(content);
Assert.DoesNotContain("\"consumedItemCount\"", content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that a malicious date bound never causes a server error, never leaks internals, and never returns data of another user.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private static async Task<string> AssertSafeDatePayloadResponseAsync(HttpResponseMessage response, string payload)
{
string content = await response.Content.ReadAsStringAsync();
// A bound date is parsed before the handler runs, so an unparseable value must either be ignored or rejected, but it must never reach the
// storage medium, fail the request, or disclose internals.
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.True(
response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.BadRequest || response.StatusCode == HttpStatusCode.UnprocessableEntity,
$"Unexpected status code {response.StatusCode} for a date bound payload.");
AssertNoSensitiveData(content);
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
return content;
}
/// <summary>
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Asserts that the serialized genres expose only the fields of their documented response contract.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoDatabaseOnlyFields(string content)
{
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users and admin users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
foreach (Guid userId in _adminUserIds)
_apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult();
}
}
@@ -0,0 +1,389 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
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.Common;
using Lumina.Contracts.Responses.MediaConsumption;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetMostConsumed;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.GetMostConsumed;
/// <summary>
/// Contains security tests for the <see cref="GetMostConsumedEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetMostConsumedEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private const string PATH = "/api/v1/users/me/consumption-history/most-consumed";
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 3, 1, 10, 5, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
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 TrackEntityFixture _trackEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetMostConsumedEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetMostConsumedEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetMostConsumed_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = PATH;
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task GetMostConsumed_WhenSuccessful_ShouldReturnOnlyCallersDataWithoutSensitiveData()
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
(Guid callerLibraryId, Guid callerMediaItemId) = await SeedConsumedTrackAsync(callerId, "Caller-Most-Consumed");
(Guid otherUserId, _) = await SeedOtherUserAsync();
(_, Guid otherMediaItemId) = await SeedConsumedTrackAsync(otherUserId, "Foreign-Most-Consumed");
string url = PATH;
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
AssertNoSensitiveData(content);
AssertNoDatabaseOnlyFields(content);
Assert.DoesNotContain(otherMediaItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Foreign-Most-Consumed", content, StringComparison.Ordinal);
PaginatedResponse<ConsumedItemResponse>? history = JsonSerializer.Deserialize<PaginatedResponse<ConsumedItemResponse>>(content, _jsonOptions);
Assert.NotNull(history);
ConsumedItemResponse item = Assert.Single(history!.Data);
Assert.Equal(callerMediaItemId, item.MediaItemId);
Assert.Equal(callerLibraryId, item.LibraryId);
Assert.Equal("Caller-Most-Consumed", item.Title);
}
[Fact]
public async Task GetMostConsumed_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndReturnCallersData()
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
(_, Guid callerMediaItemId) = await SeedConsumedTrackAsync(callerId, "Caller-Spoof-Target");
(Guid otherUserId, _) = await SeedOtherUserAsync();
(_, Guid otherMediaItemId) = await SeedConsumedTrackAsync(otherUserId, "Foreign-Spoof-Target");
string url = $"{PATH}?userId={otherUserId}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
PaginatedResponse<ConsumedItemResponse>? history = JsonSerializer.Deserialize<PaginatedResponse<ConsumedItemResponse>>(content, _jsonOptions);
Assert.NotNull(history);
ConsumedItemResponse item = Assert.Single(history!.Data);
Assert.Equal(callerMediaItemId, item.MediaItemId);
Assert.NotEqual(otherMediaItemId, item.MediaItemId);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task GetMostConsumed_WithInjectionInLibraryId_ShouldRejectWithoutLeakingData(string maliciousLibraryId)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedConsumedTrackAsync(callerId, "Caller-Injection-Target");
string url = $"{PATH}?libraryId={Uri.EscapeDataString(maliciousLibraryId)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertValidationProblemAsync(response, PATH, "LibraryIdCannotBeEmpty");
AssertNonCacheable(response);
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(2, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
}
[Theory]
[InlineData("999")] // Out of range numeric value.
[InlineData("not-a-media-kind")] // Textual value that is not an enum member.
public async Task GetMostConsumed_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedConsumedTrackAsync(callerId, "Caller-Media-Kind-Target");
string url = $"{PATH}?mediaKind={Uri.EscapeDataString(mediaKind)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
// The media kind is carried as text, so an unknown or numeric name reaches the validator and is reported as an
// unsupported kind instead of being rejected by request binding.
await AssertRejectedMediaKindAsync(response, PATH);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/> and two completed consumption sessions of one of its tracks.
/// </summary>
/// <param name="userId">The Id of the user that owns the history.</param>
/// <param name="title">The title of the consumed track.</param>
/// <returns>The Ids of the seeded library and of the consumed media item.</returns>
private async Task<(Guid LibraryId, Guid MediaItemId)> SeedConsumedTrackAsync(Guid userId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
string suffix = Guid.NewGuid().ToString("N");
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: $"Library-{suffix}", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: $"Artist-{suffix}", includeAlbums: false, includeContributors: false, includeMetadata: false));
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: $"Album-{suffix}", includeTracks: false, includeMetadata: false));
dbContext.Tracks.Add(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: title, includeMetadata: false));
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: Guid.NewGuid(),
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: trackId,
status: ConsumptionStatus.Completed,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
consumedDurationMilliseconds: 60_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 60_000,
lastProgressFraction: 1.0,
consecutivePagesRead: 0));
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: Guid.NewGuid(),
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: trackId,
status: ConsumptionStatus.Completed,
startedOnUtc: s_startedOnUtc.AddDays(1),
lastActivityOnUtc: s_lastActivityOnUtc.AddDays(1),
consumedDurationMilliseconds: 60_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 60_000,
lastProgressFraction: 1.0,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return (libraryId, trackId);
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts the shape of a validation problem details response and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts that an unparseable media kind is rejected without returning data or disclosing internals.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]);
AssertNonCacheable(response);
AssertNoSensitiveData(content);
Assert.DoesNotContain("\"data\"", content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Asserts that the serialized consumed items expose only the fields of their documented response contract.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoDatabaseOnlyFields(string content)
{
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,487 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
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.Common;
using Lumina.Contracts.Responses.MediaConsumption;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetMostConsumed;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.GetMostConsumed;
/// <summary>
/// Contains security tests for the <see cref="GetUserMostConsumedEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUserMostConsumedEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private const string PATH_PREFIX = "/api/v1/users/";
private const string PATH_SUFFIX = "/consumption-history/most-consumed";
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 3, 1, 10, 5, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
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 TrackEntityFixture _trackEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
private readonly List<Guid> _adminUserIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetUserMostConsumedEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetUserMostConsumedEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetUserMostConsumed_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task GetUserMostConsumed_WhenAnotherUsersHistoryIsRequested_ShouldReturnForbiddenWithoutDisclosingData()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid otherUserId, _) = await SeedOtherUserAsync();
(_, Guid otherMediaItemId) = await SeedConsumedTrackAsync(otherUserId, "Foreign-Most-Consumed");
string url = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertForbiddenAsync(response, url);
AssertNonCacheable(response);
Assert.DoesNotContain(otherMediaItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Foreign-Most-Consumed", content, StringComparison.Ordinal);
}
[Fact]
public async Task GetUserMostConsumed_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid otherUserId, _) = await SeedOtherUserAsync();
await SeedConsumedTrackAsync(otherUserId, "Foreign-Indistinguishable");
string foreignUrl = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
string missingUrl = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
// Act
HttpResponseMessage foreignResponse = await _client.GetAsync(foreignUrl);
HttpResponseMessage missingResponse = await _client.GetAsync(missingUrl);
// Assert
await AssertForbiddenAsync(foreignResponse, foreignUrl);
await AssertForbiddenAsync(missingResponse, missingUrl);
Dictionary<string, JsonElement> foreignProblem = await ReadProblemDetailsAsync(foreignResponse);
Dictionary<string, JsonElement> missingProblem = await ReadProblemDetailsAsync(missingResponse);
Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32());
Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString());
Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString());
Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString());
}
[Fact]
public async Task GetUserMostConsumed_WhenAdminRequestsAnotherUser_ShouldReturnOnlyThatUsersData()
{
// Arrange
(Guid otherUserId, _) = await SeedOtherUserAsync();
(_, Guid otherMediaItemId) = await SeedConsumedTrackAsync(otherUserId, "Foreign-Most-Consumed");
HttpClient adminClient = _apiFactory.CreateClient();
Guid adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(adminClient);
_adminUserIds.Add(adminUserId);
string url = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
try
{
// Act
HttpResponseMessage response = await adminClient.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
AssertNoSensitiveData(content);
AssertNoDatabaseOnlyFields(content);
PaginatedResponse<ConsumedItemResponse>? history = JsonSerializer.Deserialize<PaginatedResponse<ConsumedItemResponse>>(content, _jsonOptions);
Assert.NotNull(history);
ConsumedItemResponse item = Assert.Single(history!.Data);
Assert.Equal(otherMediaItemId, item.MediaItemId);
Assert.Equal("Foreign-Most-Consumed", item.Title);
}
finally
{
adminClient.Dispose();
}
}
[Fact]
public async Task GetUserMostConsumed_WhenCallerNamesThemselves_ShouldReturnOwnData()
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
(_, Guid callerMediaItemId) = await SeedConsumedTrackAsync(callerId, "Caller-Most-Consumed");
string url = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
PaginatedResponse<ConsumedItemResponse>? history = JsonSerializer.Deserialize<PaginatedResponse<ConsumedItemResponse>>(content, _jsonOptions);
Assert.NotNull(history);
ConsumedItemResponse item = Assert.Single(history!.Data);
Assert.Equal(callerMediaItemId, item.MediaItemId);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task GetUserMostConsumed_WithInjectionInUserIdRouteValue_ShouldRejectWithoutLeakingData(string maliciousUserId)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedConsumedTrackAsync(callerId, "Caller-Injection-Target");
string url = $"{PATH_PREFIX}{Uri.EscapeDataString(maliciousUserId)}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertRejectedRouteValueAsync(response, maliciousUserId, PATH_PREFIX, PATH_SUFFIX, "TargetUserIdIsInvalid");
AssertNonCacheable(response);
Assert.DoesNotContain(maliciousUserId, content, StringComparison.Ordinal);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(2, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
}
[Theory]
[InlineData("999")] // Out of range numeric value.
[InlineData("not-a-media-kind")] // Textual value that is not an enum member.
public async Task GetUserMostConsumed_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedConsumedTrackAsync(callerId, "Caller-Media-Kind-Target");
string path = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
string url = $"{path}?mediaKind={Uri.EscapeDataString(mediaKind)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
// The media kind is carried as text, so an unknown or numeric name reaches the validator and is reported as an
// unsupported kind instead of being rejected by request binding.
await AssertRejectedMediaKindAsync(response, path);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/> and two completed consumption sessions of one of its tracks.
/// </summary>
/// <param name="userId">The Id of the user that owns the history.</param>
/// <param name="title">The title of the consumed track.</param>
/// <returns>The Ids of the seeded library and of the consumed media item.</returns>
private async Task<(Guid LibraryId, Guid MediaItemId)> SeedConsumedTrackAsync(Guid userId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
string suffix = Guid.NewGuid().ToString("N");
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: $"Library-{suffix}", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: $"Artist-{suffix}", includeAlbums: false, includeContributors: false, includeMetadata: false));
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: $"Album-{suffix}", includeTracks: false, includeMetadata: false));
dbContext.Tracks.Add(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: title, includeMetadata: false));
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: Guid.NewGuid(),
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: trackId,
status: ConsumptionStatus.Completed,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
consumedDurationMilliseconds: 60_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 60_000,
lastProgressFraction: 1.0,
consecutivePagesRead: 0));
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: Guid.NewGuid(),
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: trackId,
status: ConsumptionStatus.Completed,
startedOnUtc: s_startedOnUtc.AddDays(1),
lastActivityOnUtc: s_lastActivityOnUtc.AddDays(1),
consumedDurationMilliseconds: 60_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 60_000,
lastProgressFraction: 1.0,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return (libraryId, trackId);
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts that the response is the exact not authorized problem document and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Reads the problem details document of <paramref name="response"/>.
/// </summary>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The parsed problem details fields.</returns>
private async Task<Dictionary<string, JsonElement>> ReadProblemDetailsAsync(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
return problemDetails!;
}
/// <summary>
/// Asserts that a malicious route value is rejected without disclosing internals.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <param name="pathPrefix">The request path that precedes the malicious value.</param>
/// <param name="pathSuffix">The request path that follows the malicious value.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertRejectedRouteValueAsync(HttpResponseMessage response, string payload, string pathPrefix, string pathSuffix, string expectedErrorCode)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
// The instance is the request path with the rejected payload in place, so decoding the middle segment must give the payload back.
string? instance = problemDetails["instance"].GetString();
Assert.NotNull(instance);
Assert.StartsWith(pathPrefix, instance, StringComparison.Ordinal);
Assert.EndsWith(pathSuffix, instance, StringComparison.Ordinal);
string encodedSegment = instance![pathPrefix.Length..(instance.Length - pathSuffix.Length)];
Assert.Equal(payload, Uri.UnescapeDataString(encodedSegment));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts that an unparseable media kind is rejected without returning data or disclosing internals.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]);
AssertNonCacheable(response);
AssertNoSensitiveData(content);
Assert.DoesNotContain("\"data\"", content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Asserts that the serialized consumed items expose only the fields of their documented response contract.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoDatabaseOnlyFields(string content)
{
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users and admin users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
foreach (Guid userId in _adminUserIds)
_apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult();
}
}
@@ -0,0 +1,375 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
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.Common;
using Lumina.Contracts.Responses.MediaConsumption;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
/// <summary>
/// Contains security tests for the <see cref="GetRecentlyConsumedEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetRecentlyConsumedEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private const string PATH = "/api/v1/users/me/consumption-history/recently-consumed";
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 3, 1, 10, 5, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
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 TrackEntityFixture _trackEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetRecentlyConsumedEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetRecentlyConsumedEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetRecentlyConsumed_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = PATH;
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task GetRecentlyConsumed_WhenSuccessful_ShouldReturnOnlyCallersDataWithoutSensitiveData()
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
(Guid callerLibraryId, Guid callerMediaItemId) = await SeedConsumedTrackAsync(callerId, "Caller-Recently-Consumed");
(Guid otherUserId, _) = await SeedOtherUserAsync();
(_, Guid otherMediaItemId) = await SeedConsumedTrackAsync(otherUserId, "Foreign-Recently-Consumed");
string url = PATH;
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
AssertNoSensitiveData(content);
AssertNoDatabaseOnlyFields(content);
Assert.DoesNotContain(otherMediaItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Foreign-Recently-Consumed", content, StringComparison.Ordinal);
PaginatedResponse<ConsumedItemResponse>? history = JsonSerializer.Deserialize<PaginatedResponse<ConsumedItemResponse>>(content, _jsonOptions);
Assert.NotNull(history);
ConsumedItemResponse item = Assert.Single(history!.Data);
Assert.Equal(callerMediaItemId, item.MediaItemId);
Assert.Equal(callerLibraryId, item.LibraryId);
Assert.Equal("Caller-Recently-Consumed", item.Title);
}
[Fact]
public async Task GetRecentlyConsumed_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndReturnCallersData()
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
(_, Guid callerMediaItemId) = await SeedConsumedTrackAsync(callerId, "Caller-Spoof-Target");
(Guid otherUserId, _) = await SeedOtherUserAsync();
(_, Guid otherMediaItemId) = await SeedConsumedTrackAsync(otherUserId, "Foreign-Spoof-Target");
string url = $"{PATH}?userId={otherUserId}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
PaginatedResponse<ConsumedItemResponse>? history = JsonSerializer.Deserialize<PaginatedResponse<ConsumedItemResponse>>(content, _jsonOptions);
Assert.NotNull(history);
ConsumedItemResponse item = Assert.Single(history!.Data);
Assert.Equal(callerMediaItemId, item.MediaItemId);
Assert.NotEqual(otherMediaItemId, item.MediaItemId);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task GetRecentlyConsumed_WithInjectionInLibraryId_ShouldRejectWithoutLeakingData(string maliciousLibraryId)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedConsumedTrackAsync(callerId, "Caller-Injection-Target");
string url = $"{PATH}?libraryId={Uri.EscapeDataString(maliciousLibraryId)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertValidationProblemAsync(response, PATH, "LibraryIdCannotBeEmpty");
AssertNonCacheable(response);
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
}
[Theory]
[InlineData("999")] // Out of range numeric value.
[InlineData("not-a-media-kind")] // Textual value that is not an enum member.
public async Task GetRecentlyConsumed_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedConsumedTrackAsync(callerId, "Caller-Media-Kind-Target");
string url = $"{PATH}?mediaKind={Uri.EscapeDataString(mediaKind)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
// The media kind is carried as text, so an unknown or numeric name reaches the validator and is reported as an
// unsupported kind instead of being rejected by request binding.
await AssertRejectedMediaKindAsync(response, PATH);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/> and a completed consumption session of one of its tracks.
/// </summary>
/// <param name="userId">The Id of the user that owns the history.</param>
/// <param name="title">The title of the consumed track.</param>
/// <returns>The Ids of the seeded library and of the consumed media item.</returns>
private async Task<(Guid LibraryId, Guid MediaItemId)> SeedConsumedTrackAsync(Guid userId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
string suffix = Guid.NewGuid().ToString("N");
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: $"Library-{suffix}", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: $"Artist-{suffix}", includeAlbums: false, includeContributors: false, includeMetadata: false));
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: $"Album-{suffix}", includeTracks: false, includeMetadata: false));
dbContext.Tracks.Add(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: title, includeMetadata: false));
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: Guid.NewGuid(),
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: trackId,
status: ConsumptionStatus.Completed,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
consumedDurationMilliseconds: 60_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 60_000,
lastProgressFraction: 1.0,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return (libraryId, trackId);
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts the shape of a validation problem details response and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts that an unparseable media kind is rejected without returning data or disclosing internals.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]);
AssertNonCacheable(response);
AssertNoSensitiveData(content);
Assert.DoesNotContain("\"data\"", content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Asserts that the serialized consumed items expose only the fields of their documented response contract.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoDatabaseOnlyFields(string content)
{
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,473 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
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.Common;
using Lumina.Contracts.Responses.MediaConsumption;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
/// <summary>
/// Contains security tests for the <see cref="GetUserRecentlyConsumedEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUserRecentlyConsumedEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private const string PATH_PREFIX = "/api/v1/users/";
private const string PATH_SUFFIX = "/consumption-history/recently-consumed";
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 3, 1, 10, 5, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
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 TrackEntityFixture _trackEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
private readonly List<Guid> _adminUserIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetUserRecentlyConsumedEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetUserRecentlyConsumedEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetUserRecentlyConsumed_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task GetUserRecentlyConsumed_WhenAnotherUsersHistoryIsRequested_ShouldReturnForbiddenWithoutDisclosingData()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid otherUserId, _) = await SeedOtherUserAsync();
(_, Guid otherMediaItemId) = await SeedConsumedTrackAsync(otherUserId, "Foreign-Recently-Consumed");
string url = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertForbiddenAsync(response, url);
AssertNonCacheable(response);
Assert.DoesNotContain(otherMediaItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Foreign-Recently-Consumed", content, StringComparison.Ordinal);
}
[Fact]
public async Task GetUserRecentlyConsumed_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid otherUserId, _) = await SeedOtherUserAsync();
await SeedConsumedTrackAsync(otherUserId, "Foreign-Indistinguishable");
string foreignUrl = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
string missingUrl = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
// Act
HttpResponseMessage foreignResponse = await _client.GetAsync(foreignUrl);
HttpResponseMessage missingResponse = await _client.GetAsync(missingUrl);
// Assert
await AssertForbiddenAsync(foreignResponse, foreignUrl);
await AssertForbiddenAsync(missingResponse, missingUrl);
Dictionary<string, JsonElement> foreignProblem = await ReadProblemDetailsAsync(foreignResponse);
Dictionary<string, JsonElement> missingProblem = await ReadProblemDetailsAsync(missingResponse);
Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32());
Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString());
Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString());
Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString());
}
[Fact]
public async Task GetUserRecentlyConsumed_WhenAdminRequestsAnotherUser_ShouldReturnOnlyThatUsersData()
{
// Arrange
(Guid otherUserId, _) = await SeedOtherUserAsync();
(_, Guid otherMediaItemId) = await SeedConsumedTrackAsync(otherUserId, "Foreign-Recently-Consumed");
HttpClient adminClient = _apiFactory.CreateClient();
Guid adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(adminClient);
_adminUserIds.Add(adminUserId);
string url = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
try
{
// Act
HttpResponseMessage response = await adminClient.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
AssertNoSensitiveData(content);
AssertNoDatabaseOnlyFields(content);
PaginatedResponse<ConsumedItemResponse>? history = JsonSerializer.Deserialize<PaginatedResponse<ConsumedItemResponse>>(content, _jsonOptions);
Assert.NotNull(history);
ConsumedItemResponse item = Assert.Single(history!.Data);
Assert.Equal(otherMediaItemId, item.MediaItemId);
Assert.Equal("Foreign-Recently-Consumed", item.Title);
}
finally
{
adminClient.Dispose();
}
}
[Fact]
public async Task GetUserRecentlyConsumed_WhenCallerNamesThemselves_ShouldReturnOwnData()
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
(_, Guid callerMediaItemId) = await SeedConsumedTrackAsync(callerId, "Caller-Recently-Consumed");
string url = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
PaginatedResponse<ConsumedItemResponse>? history = JsonSerializer.Deserialize<PaginatedResponse<ConsumedItemResponse>>(content, _jsonOptions);
Assert.NotNull(history);
ConsumedItemResponse item = Assert.Single(history!.Data);
Assert.Equal(callerMediaItemId, item.MediaItemId);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task GetUserRecentlyConsumed_WithInjectionInUserIdRouteValue_ShouldRejectWithoutLeakingData(string maliciousUserId)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedConsumedTrackAsync(callerId, "Caller-Injection-Target");
string url = $"{PATH_PREFIX}{Uri.EscapeDataString(maliciousUserId)}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertRejectedRouteValueAsync(response, maliciousUserId, PATH_PREFIX, PATH_SUFFIX, "TargetUserIdIsInvalid");
AssertNonCacheable(response);
Assert.DoesNotContain(maliciousUserId, content, StringComparison.Ordinal);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
}
[Theory]
[InlineData("999")] // Out of range numeric value.
[InlineData("not-a-media-kind")] // Textual value that is not an enum member.
public async Task GetUserRecentlyConsumed_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedConsumedTrackAsync(callerId, "Caller-Media-Kind-Target");
string path = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
string url = $"{path}?mediaKind={Uri.EscapeDataString(mediaKind)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
// The media kind is carried as text, so an unknown or numeric name reaches the validator and is reported as an
// unsupported kind instead of being rejected by request binding.
await AssertRejectedMediaKindAsync(response, path);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/> and a completed consumption session of one of its tracks.
/// </summary>
/// <param name="userId">The Id of the user that owns the history.</param>
/// <param name="title">The title of the consumed track.</param>
/// <returns>The Ids of the seeded library and of the consumed media item.</returns>
private async Task<(Guid LibraryId, Guid MediaItemId)> SeedConsumedTrackAsync(Guid userId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
string suffix = Guid.NewGuid().ToString("N");
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: $"Library-{suffix}", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: $"Artist-{suffix}", includeAlbums: false, includeContributors: false, includeMetadata: false));
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: $"Album-{suffix}", includeTracks: false, includeMetadata: false));
dbContext.Tracks.Add(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: title, includeMetadata: false));
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: Guid.NewGuid(),
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: trackId,
status: ConsumptionStatus.Completed,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
consumedDurationMilliseconds: 60_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 60_000,
lastProgressFraction: 1.0,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return (libraryId, trackId);
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts that the response is the exact not authorized problem document and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Reads the problem details document of <paramref name="response"/>.
/// </summary>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The parsed problem details fields.</returns>
private async Task<Dictionary<string, JsonElement>> ReadProblemDetailsAsync(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
return problemDetails!;
}
/// <summary>
/// Asserts that a malicious route value is rejected without disclosing internals.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <param name="pathPrefix">The request path that precedes the malicious value.</param>
/// <param name="pathSuffix">The request path that follows the malicious value.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertRejectedRouteValueAsync(HttpResponseMessage response, string payload, string pathPrefix, string pathSuffix, string expectedErrorCode)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
// The instance is the request path with the rejected payload in place, so decoding the middle segment must give the payload back.
string? instance = problemDetails["instance"].GetString();
Assert.NotNull(instance);
Assert.StartsWith(pathPrefix, instance, StringComparison.Ordinal);
Assert.EndsWith(pathSuffix, instance, StringComparison.Ordinal);
string encodedSegment = instance![pathPrefix.Length..(instance.Length - pathSuffix.Length)];
Assert.Equal(payload, Uri.UnescapeDataString(encodedSegment));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts that an unparseable media kind is rejected without returning data or disclosing internals.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]);
AssertNonCacheable(response);
AssertNoSensitiveData(content);
Assert.DoesNotContain("\"data\"", content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Asserts that the serialized consumed items expose only the fields of their documented response contract.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoDatabaseOnlyFields(string content)
{
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users and admin users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
foreach (Guid userId in _adminUserIds)
_apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult();
}
}
@@ -0,0 +1,381 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
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.MediaConsumption;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetTagConsumption;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.GetTagConsumption;
/// <summary>
/// Contains security tests for the <see cref="GetTagConsumptionEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTagConsumptionEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private const string PATH = "/api/v1/users/me/consumption-statistics/tags";
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 3, 1, 10, 5, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
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 TrackEntityFixture _trackEntityFixture = new();
private readonly TagEntityFixture _tagEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetTagConsumptionEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetTagConsumptionEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetTagConsumption_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = PATH;
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task GetTagConsumption_WhenSuccessful_ShouldReturnOnlyCallersTagsWithoutSensitiveData()
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
string callerTag = await SeedTaggedConsumptionAsync(callerId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherTag = await SeedTaggedConsumptionAsync(otherUserId);
string url = PATH;
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
AssertNoSensitiveData(content);
AssertNoDatabaseOnlyFields(content);
Assert.DoesNotContain(otherTag, content, StringComparison.OrdinalIgnoreCase);
List<TagConsumptionResponse>? tags = JsonSerializer.Deserialize<List<TagConsumptionResponse>>(content, _jsonOptions);
Assert.NotNull(tags);
TagConsumptionResponse tag = Assert.Single(tags!);
Assert.Equal(callerTag.ToLowerInvariant(), tag.Name);
Assert.Equal(1, tag.ConsumedItemCount);
Assert.Equal(60d, tag.ConsumedDurationInSeconds, 3);
}
[Fact]
public async Task GetTagConsumption_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndReturnCallersTags()
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
string callerTag = await SeedTaggedConsumptionAsync(callerId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherTag = await SeedTaggedConsumptionAsync(otherUserId);
string url = $"{PATH}?userId={otherUserId}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
List<TagConsumptionResponse>? tags = JsonSerializer.Deserialize<List<TagConsumptionResponse>>(content, _jsonOptions);
Assert.NotNull(tags);
TagConsumptionResponse tag = Assert.Single(tags!);
Assert.Equal(callerTag.ToLowerInvariant(), tag.Name);
Assert.DoesNotContain(otherTag, content, StringComparison.OrdinalIgnoreCase);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task GetTagConsumption_WithInjectionInLibraryId_ShouldRejectWithoutLeakingData(string maliciousLibraryId)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedTaggedConsumptionAsync(callerId);
string url = $"{PATH}?libraryId={Uri.EscapeDataString(maliciousLibraryId)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertValidationProblemAsync(response, PATH, "LibraryIdCannotBeEmpty");
AssertNonCacheable(response);
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
}
[Theory]
[InlineData("999")] // Out of range numeric value.
[InlineData("not-a-media-kind")] // Textual value that is not an enum member.
public async Task GetTagConsumption_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedTaggedConsumptionAsync(callerId);
string url = $"{PATH}?mediaKind={Uri.EscapeDataString(mediaKind)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
// The media kind is carried as text, so an unknown or numeric name reaches the validator and is reported as an
// unsupported kind instead of being rejected by request binding.
await AssertRejectedMediaKindAsync(response, PATH);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a uniquely tagged track in a library owned by <paramref name="userId"/> and one completed session of it.
/// </summary>
/// <param name="userId">The Id of the user that owns the records.</param>
/// <returns>The unique name of the seeded tag.</returns>
private async Task<string> SeedTaggedConsumptionAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
string suffix = Guid.NewGuid().ToString("N");
// Tag names are the primary key of a shared table, so every seeded name carries a unique suffix.
string tagName = $"tag-{suffix}";
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: $"Library-{suffix}", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: $"Artist-{suffix}", includeAlbums: false, includeContributors: false, includeMetadata: false));
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: $"Album-{suffix}", includeTracks: false, includeMetadata: false));
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: $"Track-{suffix}", includeMetadata: false);
TagEntity tag = _tagEntityFixture.Create(name: tagName);
track.Tags.Add(tag);
dbContext.Tracks.Add(track);
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: Guid.NewGuid(),
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: trackId,
status: ConsumptionStatus.Completed,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
consumedDurationMilliseconds: 60_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 60_000,
lastProgressFraction: 1.0,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return tagName;
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts the shape of a validation problem details response and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts that an unparseable media kind is rejected without returning data or disclosing internals.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]);
AssertNonCacheable(response);
AssertNoSensitiveData(content);
Assert.DoesNotContain("\"consumedItemCount\"", content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Asserts that the serialized tags expose only the fields of their documented response contract.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoDatabaseOnlyFields(string content)
{
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,480 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
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.MediaConsumption;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetTagConsumption;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.GetTagConsumption;
/// <summary>
/// Contains security tests for the <see cref="GetUserTagConsumptionEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUserTagConsumptionEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private const string PATH_PREFIX = "/api/v1/users/";
private const string PATH_SUFFIX = "/consumption-statistics/tags";
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 3, 1, 10, 5, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
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 TrackEntityFixture _trackEntityFixture = new();
private readonly TagEntityFixture _tagEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
private readonly List<Guid> _adminUserIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetUserTagConsumptionEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetUserTagConsumptionEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetUserTagConsumption_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task GetUserTagConsumption_WhenAnotherUsersTagsAreRequested_ShouldReturnForbiddenWithoutDisclosingData()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherTag = await SeedTaggedConsumptionAsync(otherUserId);
string url = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertForbiddenAsync(response, url);
AssertNonCacheable(response);
Assert.DoesNotContain(otherTag, content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("consumedItemCount", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetUserTagConsumption_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid otherUserId, _) = await SeedOtherUserAsync();
await SeedTaggedConsumptionAsync(otherUserId);
string foreignUrl = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
string missingUrl = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
// Act
HttpResponseMessage foreignResponse = await _client.GetAsync(foreignUrl);
HttpResponseMessage missingResponse = await _client.GetAsync(missingUrl);
// Assert
await AssertForbiddenAsync(foreignResponse, foreignUrl);
await AssertForbiddenAsync(missingResponse, missingUrl);
Dictionary<string, JsonElement> foreignProblem = await ReadProblemDetailsAsync(foreignResponse);
Dictionary<string, JsonElement> missingProblem = await ReadProblemDetailsAsync(missingResponse);
Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32());
Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString());
Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString());
Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString());
}
[Fact]
public async Task GetUserTagConsumption_WhenAdminRequestsAnotherUser_ShouldReturnOnlyThatUsersTags()
{
// Arrange
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherTag = await SeedTaggedConsumptionAsync(otherUserId);
HttpClient adminClient = _apiFactory.CreateClient();
Guid adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(adminClient);
_adminUserIds.Add(adminUserId);
string url = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
try
{
// Act
HttpResponseMessage response = await adminClient.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
AssertNoSensitiveData(content);
AssertNoDatabaseOnlyFields(content);
List<TagConsumptionResponse>? tags = JsonSerializer.Deserialize<List<TagConsumptionResponse>>(content, _jsonOptions);
Assert.NotNull(tags);
TagConsumptionResponse tag = Assert.Single(tags!);
Assert.Equal(otherTag.ToLowerInvariant(), tag.Name);
Assert.Equal(1, tag.ConsumedItemCount);
}
finally
{
adminClient.Dispose();
}
}
[Fact]
public async Task GetUserTagConsumption_WhenCallerNamesThemselves_ShouldReturnOwnTags()
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
string callerTag = await SeedTaggedConsumptionAsync(callerId);
string url = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
List<TagConsumptionResponse>? tags = JsonSerializer.Deserialize<List<TagConsumptionResponse>>(content, _jsonOptions);
Assert.NotNull(tags);
TagConsumptionResponse tag = Assert.Single(tags!);
Assert.Equal(callerTag.ToLowerInvariant(), tag.Name);
}
[Theory]
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // Destructive injection.
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // Stacked statement injection.
[InlineData("../../../etc/passwd")] // Path traversal.
[InlineData("<script>alert(1)</script>")] // Markup injection.
public async Task GetUserTagConsumption_WithInjectionInUserIdRouteValue_ShouldRejectWithoutLeakingData(string maliciousUserId)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedTaggedConsumptionAsync(callerId);
string url = $"{PATH_PREFIX}{Uri.EscapeDataString(maliciousUserId)}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertRejectedRouteValueAsync(response, maliciousUserId, PATH_PREFIX, PATH_SUFFIX, "TargetUserIdIsInvalid");
AssertNonCacheable(response);
Assert.DoesNotContain(maliciousUserId, content, StringComparison.Ordinal);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
}
[Theory]
[InlineData("999")] // Out of range numeric value.
[InlineData("not-a-media-kind")] // Textual value that is not an enum member.
public async Task GetUserTagConsumption_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedTaggedConsumptionAsync(callerId);
string path = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
string url = $"{path}?mediaKind={Uri.EscapeDataString(mediaKind)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
// The media kind is carried as text, so an unknown or numeric name reaches the validator and is reported as an
// unsupported kind instead of being rejected by request binding.
await AssertRejectedMediaKindAsync(response, path);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a uniquely tagged track in a library owned by <paramref name="userId"/> and one completed session of it.
/// </summary>
/// <param name="userId">The Id of the user that owns the records.</param>
/// <returns>The unique name of the seeded tag.</returns>
private async Task<string> SeedTaggedConsumptionAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
string suffix = Guid.NewGuid().ToString("N");
// Tag names are the primary key of a shared table, so every seeded name carries a unique suffix.
string tagName = $"tag-{suffix}";
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: $"Library-{suffix}", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: $"Artist-{suffix}", includeAlbums: false, includeContributors: false, includeMetadata: false));
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: $"Album-{suffix}", includeTracks: false, includeMetadata: false));
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: $"Track-{suffix}", includeMetadata: false);
TagEntity tag = _tagEntityFixture.Create(name: tagName);
track.Tags.Add(tag);
dbContext.Tracks.Add(track);
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: Guid.NewGuid(),
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: trackId,
status: ConsumptionStatus.Completed,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
consumedDurationMilliseconds: 60_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 60_000,
lastProgressFraction: 1.0,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return tagName;
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts that the response is the exact not authorized problem document and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Reads the problem details document of <paramref name="response"/>.
/// </summary>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The parsed problem details fields.</returns>
private async Task<Dictionary<string, JsonElement>> ReadProblemDetailsAsync(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
return problemDetails!;
}
/// <summary>
/// Asserts that a malicious route value is rejected without disclosing internals.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <param name="pathPrefix">The request path that precedes the malicious value.</param>
/// <param name="pathSuffix">The request path that follows the malicious value.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertRejectedRouteValueAsync(HttpResponseMessage response, string payload, string pathPrefix, string pathSuffix, string expectedErrorCode)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
// The instance is the request path with the rejected payload in place, so decoding the middle segment must give the payload back.
string? instance = problemDetails["instance"].GetString();
Assert.NotNull(instance);
Assert.StartsWith(pathPrefix, instance, StringComparison.Ordinal);
Assert.EndsWith(pathSuffix, instance, StringComparison.Ordinal);
string encodedSegment = instance![pathPrefix.Length..(instance.Length - pathSuffix.Length)];
Assert.Equal(payload, Uri.UnescapeDataString(encodedSegment));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts that an unparseable media kind is rejected without returning data or disclosing internals.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]);
AssertNonCacheable(response);
AssertNoSensitiveData(content);
Assert.DoesNotContain("\"consumedItemCount\"", content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Asserts that the serialized tags expose only the fields of their documented response contract.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoDatabaseOnlyFields(string content)
{
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users and admin users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
foreach (Guid userId in _adminUserIds)
_apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult();
}
}
@@ -0,0 +1,284 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.AddBook;
/// <summary>
/// Contains security tests for the <see cref="AddBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddBookEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly AddBookRequestFixture _addBookRequestFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
private readonly GenreDtoFixture _genreDtoFixture = new();
private readonly TagDtoFixture _tagDtoFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly TagEntityFixture _tagEntityFixture = new();
private readonly GenreEntityFixture _genreEntityFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="AddBookEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AddBookEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task AddBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
Guid libraryId = Guid.NewGuid();
AddBookRequest request = _addBookRequestFixture.Create(contributors: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/books", problemDetails["instance"].GetProperty("value").GetString());
}
[Fact]
public async Task AddBook_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
AddBookRequest request = _addBookRequestFixture.Create(contributors: []);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveTestUserAsync(requesterUsername);
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task AddBook_WithSQLInjectionInPath_ShouldNotCorruptOrDeleteData(string maliciousPath)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
string contentLocation = Path.GetTempPath();
string injectedPath = Path.Combine(contentLocation, $"{maliciousPath}.epub");
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
{
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
seedDbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [contentLocation]));
await seedDbContext.SaveChangesAsync();
}
AddBookRequest request = _addBookRequestFixture.Create(path: injectedPath, contributors: []);
// Act
HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request);
// Assert
// The malicious path passes the authenticated handler, reaches the parameterized insert, and is persisted
// verbatim: if it were concatenated into raw SQL, the insert would fail and the book would not be created.
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.Libraries.CountAsync(library => library.Id == libraryId));
// The single book in the library is the one inserted by this request, with the malicious path stored as data.
Assert.Equal(1, await dbContext.Books.CountAsync(book => book.LibraryId == libraryId));
await _apiFactory.RemoveTestUserAsync(username);
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task AddBook_WithSQLInjectionInBody_ShouldNotCorruptOrDeleteData(string maliciousTitle)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
string contentLocation = Path.GetTempPath();
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
{
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
seedDbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [contentLocation]));
await seedDbContext.SaveChangesAsync();
}
string bookPath = Path.Combine(contentLocation, $"{Guid.NewGuid()}.epub");
AddBookRequest request = _addBookRequestFixture.Create(path: bookPath, metadata: _writtenContentMetadataDtoFixture.Create(title: maliciousTitle), contributors: []);
// Act
HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request);
// Assert
// The malicious title passes the authenticated handler, reaches the parameterized insert, and is persisted
// verbatim: if it were concatenated into raw SQL, the insert would fail and the book would not be created.
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
BookEntity storedBook = await dbContext.Books.SingleAsync(book => book.LibraryId == libraryId);
Assert.Equal(maliciousTitle, storedBook.Title);
await _apiFactory.RemoveTestUserAsync(username);
}
[Theory]
[InlineData("'; DROP TABLE Tags; --")] // Destructive injection in a tag and genre name.
[InlineData("' OR '1'='1")] // Boolean-based injection in a tag and genre name.
public async Task AddBook_WithSQLInjectionInTagAndGenreNames_ShouldNotCorruptOrLeakData(string maliciousName)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
string contentLocation = Path.GetTempPath();
string suffix = Guid.NewGuid().ToString("N")[..8];
string seededTagName = $"seeded-tag-{suffix}";
string seededGenreName = $"seeded-genre-{suffix}";
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
{
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
seedDbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [contentLocation]));
seedDbContext.Set<TagEntity>().Add(_tagEntityFixture.Create(name: seededTagName));
seedDbContext.Set<GenreEntity>().Add(_genreEntityFixture.Create(name: seededGenreName));
await seedDbContext.SaveChangesAsync();
}
string injectedTagName = $"{maliciousName} {suffix}";
string injectedGenreName = $"{maliciousName} genre {suffix}";
AddBookRequest request = _addBookRequestFixture.Create(
path: Path.Combine(contentLocation, $"{Guid.NewGuid()}.epub"),
metadata: _writtenContentMetadataDtoFixture.Create(
genres: [_genreDtoFixture.Create(name: injectedGenreName)],
tags: [_tagDtoFixture.Create(name: injectedTagName)]),
contributors: []);
// Act
HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request);
string content = await response.Content.ReadAsStringAsync();
// Assert
// The malicious names are user data, not SQL: they must be stored verbatim (normalized) without breaking the request or the schema.
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.DoesNotContain("SQL", content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("StackTrace", content, StringComparison.OrdinalIgnoreCase);
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.Libraries.CountAsync(library => library.Id == libraryId));
Assert.Equal(1, await dbContext.Books.CountAsync(book => book.LibraryId == libraryId));
// The join rows must still exist and point at the normalized tag and genre that the request supplied.
BookEntity storedBook = await dbContext.Books
.Include(book => book.Tags)
.Include(book => book.Genres)
.SingleAsync(book => book.LibraryId == libraryId);
Assert.Equal(injectedTagName.ToLowerInvariant(), Assert.Single(storedBook.Tags).Name);
Assert.Equal(injectedGenreName.ToLowerInvariant(), Assert.Single(storedBook.Genres).Name);
Assert.True(await dbContext.Set<TagEntity>().AnyAsync(tag => tag.Name == seededTagName));
Assert.True(await dbContext.Set<GenreEntity>().AnyAsync(genre => genre.Name == seededGenreName));
Assert.True(await dbContext.Set<TagEntity>().AnyAsync(tag => tag.Name == injectedTagName.ToLowerInvariant()));
Assert.True(await dbContext.Set<GenreEntity>().AnyAsync(genre => genre.Name == injectedGenreName.ToLowerInvariant()));
}
await _apiFactory.RemoveTestUserAsync(username);
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task AddBook_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
AddBookRequest request = _addBookRequestFixture.Create(contributors: []);
// Act
HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/books", request);
// Assert
// The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the command
// validator, which reports it as a clean validation error. The response must not leak stack traces, database details,
// or the injected payload.
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(maliciousLibraryId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
await _apiFactory.RemoveTestUserAsync(username);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
// Nothing to clean up: each test removes its own seeded rows.
}
}
@@ -0,0 +1,225 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
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.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
/// <summary>
/// Contains security tests for the <see cref="DeleteBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteBookEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBookEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeleteBookEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task DeleteBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task DeleteBook_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/books/{Guid.NewGuid()}");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task DeleteBook_WithSQLInjectionInBookId_ShouldNotCorruptOrLeakData(string maliciousBookId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Uri.EscapeDataString(maliciousBookId)}");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task DeleteBook_WhenBookBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
Guid otherUserId = await SeedOtherUserAsync();
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(otherUserId);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}/books/{bookId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task DeleteBook_WhenBookBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutDeletingIt()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(actingUsername);
(Guid ownLibraryId, _) = await SeedLibraryAndBookAsync(actingUserId);
// The book 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 victimBookId) = await SeedLibraryAndBookAsync(victimUserId);
// Act
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{ownLibraryId}/books/{victimBookId}");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
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("BookNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
// The other user's book is untouched.
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.NotNull(await dbContext.Books.FirstOrDefaultAsync(book => book.Id == victimBookId));
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return userId;
}
/// <summary>
/// Seeds an ebook library owned by <paramref name="userId"/>, together with a book of that library.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Ids of the seeded library and book.</returns>
private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndBookAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
dbContext.Books.Add(_bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: "Test Book", includeMetadata: false));
await dbContext.SaveChangesAsync();
return (libraryId, bookId);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,71 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook;
/// <summary>
/// Contains security tests for the <see cref="GetBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBookEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly LuminaApiFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="GetBookEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetBookEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task GetBook_WithSQLInjectionInBookId_ShouldNotCorruptOrLeakData(string maliciousBookId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Uri.EscapeDataString(maliciousBookId)}");
// Assert
// The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean
// validation error instead of failing the request binding.
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(maliciousBookId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
await _apiFactory.RemoveTestUserAsync(username);
}
}
@@ -0,0 +1,153 @@
#region ========================================================================= USING =====================================================================================
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks;
/// <summary>
/// Contains security tests for the <see cref="GetBooksEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetBooksEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetBooks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task GetBooks_WhenSearchTermContainsSqlInjection_ShouldNotCorruptOrDeleteData(string maliciousSearchTerm)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, userId);
await _apiFactory.SeedBookAsync(libraryId, "Book A");
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/books?searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}");
// Assert
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(maliciousSearchTerm, content, StringComparison.Ordinal);
// The injected statement must never be executed: the Books table and the seeded rows must still be there.
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.Books.CountAsync(book => book.LibraryId == libraryId));
await _apiFactory.RemoveTestUserAsync(username);
}
[Fact]
public async Task GetBooks_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveTestUserAsync(requesterUsername);
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task GetBooks_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/books");
// Assert
// The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the query
// validator, which reports it as a clean validation error. The response must not leak stack traces, database details,
// or the injected payload.
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(maliciousLibraryId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
await _apiFactory.RemoveTestUserAsync(username);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
// Nothing to clean up: each test removes its own seeded rows.
}
}
@@ -0,0 +1,154 @@
#region ========================================================================= USING =====================================================================================
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite;
/// <summary>
/// Contains security tests for the <see cref="GetBooksLiteEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksLiteEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksLiteEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetBooksLiteEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetBooksLite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/lite");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/lite", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task GetBooksLite_WhenSearchTermContainsSqlInjection_ShouldNotCorruptOrDeleteData(string maliciousSearchTerm)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, userId);
await _apiFactory.SeedBookAsync(libraryId, "Book A");
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}");
// Assert
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(maliciousSearchTerm, content, StringComparison.Ordinal);
// The injected statement must never be executed: the Books table and the seeded rows must still be there.
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.Books.CountAsync(book => book.LibraryId == libraryId));
await _apiFactory.RemoveTestUserAsync(username);
}
[Fact]
public async Task GetBooksLite_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveTestUserAsync(requesterUsername);
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task GetBooksLite_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/books/lite");
// Assert
// The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the query
// validator, which reports it as a clean validation error. The response must not leak stack traces, database details,
// or the injected payload.
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(maliciousLibraryId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
await _apiFactory.RemoveTestUserAsync(username);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public void Dispose()
{
// Nothing to clean up: each test removes its own seeded rows.
}
}
@@ -0,0 +1,142 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetDeletedBooks;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetDeletedBooks;
/// <summary>
/// Contains security tests for the <see cref="GetDeletedBooksEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedBooksEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private readonly List<string> _seededUsernames = [];
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedBooksEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDeletedBooksEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetDeletedBooks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/deleted-items";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task GetDeletedBooks_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/books/deleted-items");
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task GetDeletedBooks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenAndNotLeakTheDeletedBook()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
const string TITLE = "Secret Deleted Book";
const string PATH = "/private/deleted-book.epub";
const string COVER_PATH = "/private/deleted-book-cover.jpg";
(Guid libraryId, _) = await SeedLibraryAndDeletedBookAsync(victimUserId, TITLE, PATH, COVER_PATH);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/books/deleted-items");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.DoesNotContain(TITLE, content, StringComparison.Ordinal);
Assert.DoesNotContain(PATH, content, StringComparison.Ordinal);
Assert.DoesNotContain(COVER_PATH, content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds an ebook library owned by <paramref name="userId"/>, together with a deleted book and its cover.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="title">The title of the deleted book.</param>
/// <param name="path">The file system path of the deleted book.</param>
/// <param name="coverPath">The stored cover path of the deleted book.</param>
/// <returns>The Id of the seeded library and the seeded book.</returns>
private async Task<(Guid libraryId, BookEntity book)> SeedLibraryAndDeletedBookAsync(Guid userId, string title, string path, string coverPath)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create(libraryId: libraryId, path: path, title: title, isDeleted: true, includeMetadata: false);
book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: coverPath)];
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.EBook, contentLocations: []));
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();
return (libraryId, book);
}
/// <summary>
/// Removes the users created by the tests.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,121 @@
#region ========================================================================= USING =====================================================================================
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
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.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability;
/// <summary>
/// Contains security tests for the <see cref="GetReadingAvailabilityEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingAvailabilityEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingAvailabilityEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetReadingAvailabilityEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetReadingAvailability_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/reading/availability");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
}
[Theory]
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Books--")] // Destructive injection.
public async Task GetReadingAvailability_WithSQLInjectionInBookId_ShouldNotLeakDatabaseDetails(string maliciousBookId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Uri.EscapeDataString(maliciousBookId)}/reading/availability");
string content = await response.Content.ReadAsStringAsync();
// Assert
// The authenticated request reaches validation, where the unparseable route Id is reported as a clean validation error,
// without executing the injected payload or leaking database details.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(maliciousBookId, content, StringComparison.Ordinal);
await _apiFactory.RemoveTestUserAsync(username);
}
[Fact]
public async Task GetReadingAvailability_WhenUserDoesNotOwnTheBookLibrary_ShouldReturnForbidden()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
await _apiFactory.SeedBookAsync(libraryId, "Other User Book");
Guid bookId;
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
bookId = dbContext.Books.Single(book => book.LibraryId == libraryId).Id;
}
HttpClient requesterClient = _apiFactory.CreateClient();
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
// Act
HttpResponseMessage response = await requesterClient.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/availability");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveTestUserAsync(requesterUsername);
}
}
@@ -0,0 +1,121 @@
#region ========================================================================= USING =====================================================================================
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
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.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest;
/// <summary>
/// Contains security tests for the <see cref="GetReadingManifestEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingManifestEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingManifestEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetReadingManifestEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetReadingManifest_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/reading/manifest");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
}
[Theory]
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Books--")] // Destructive injection.
public async Task GetReadingManifest_WithSQLInjectionInBookId_ShouldNotLeakDatabaseDetails(string maliciousBookId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Uri.EscapeDataString(maliciousBookId)}/reading/manifest");
string content = await response.Content.ReadAsStringAsync();
// Assert
// The authenticated request reaches validation, where the unparseable route Id is reported as a clean validation error,
// without executing the injected payload or leaking database details.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(maliciousBookId, content, StringComparison.Ordinal);
await _apiFactory.RemoveTestUserAsync(username);
}
[Fact]
public async Task GetReadingManifest_WhenUserDoesNotOwnTheBookLibrary_ShouldReturnForbidden()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
await _apiFactory.SeedBookAsync(libraryId, "Other User Book");
Guid bookId;
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
bookId = dbContext.Books.Single(book => book.LibraryId == libraryId).Id;
}
HttpClient requesterClient = _apiFactory.CreateClient();
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
// Act
HttpResponseMessage response = await requesterClient.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/manifest");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveTestUserAsync(requesterUsername);
}
}
@@ -0,0 +1,143 @@
#region ========================================================================= USING =====================================================================================
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
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.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource;
/// <summary>
/// Contains security tests for the <see cref="GetReadingResourceEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingResourceEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingResourceEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetReadingResourceEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetReadingResource_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/reading/resources/cover");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
}
[Theory]
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Books--")] // Destructive injection.
public async Task GetReadingResource_WithSQLInjectionInResourceKey_ShouldNotLeakDatabaseDetails(string maliciousResourceKey)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/resources/{Uri.EscapeDataString(maliciousResourceKey)}");
string content = await response.Content.ReadAsStringAsync();
// Assert
// The authenticated request reaches the handler and the database, where the book does not exist, so the request fails
// cleanly without executing the injected payload or leaking database details.
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(maliciousResourceKey, content, StringComparison.Ordinal);
await _apiFactory.RemoveTestUserAsync(username);
}
[Theory]
[InlineData("../../etc/passwd")] // Directory traversal.
[InlineData("..%2F..%2Fetc%2Fpasswd")] // Encoded directory traversal.
public async Task GetReadingResource_WithPathTraversalInResourceKey_ShouldNotExposeFilesystemPaths(string traversalPayload)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/resources/{traversalPayload}");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.DoesNotContain("etc/passwd", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
Assert.DoesNotContain("Stack Trace", content, StringComparison.Ordinal);
await _apiFactory.RemoveTestUserAsync(username);
}
[Fact]
public async Task GetReadingResource_WhenUserDoesNotOwnTheBookLibrary_ShouldReturnForbidden()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
await _apiFactory.SeedBookAsync(libraryId, "Other User Book");
Guid bookId;
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
bookId = dbContext.Books.Single(book => book.LibraryId == libraryId).Id;
}
HttpClient requesterClient = _apiFactory.CreateClient();
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
// Act
HttpResponseMessage response = await requesterClient.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/resources/cover");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveTestUserAsync(requesterUsername);
}
}
@@ -0,0 +1,143 @@
#region ========================================================================= USING =====================================================================================
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
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.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection;
/// <summary>
/// Contains security tests for the <see cref="GetReadingSectionEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetReadingSectionEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetReadingSectionEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetReadingSectionEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetReadingSection_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/reading/sections/chapter-1");
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
}
[Theory]
[InlineData("' OR '1'='1")] // Basic SQL injection.
[InlineData("'; DROP TABLE Books--")] // Destructive injection.
public async Task GetReadingSection_WithSQLInjectionInLocationRef_ShouldNotLeakDatabaseDetails(string maliciousLocationRef)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/sections/{Uri.EscapeDataString(maliciousLocationRef)}");
string content = await response.Content.ReadAsStringAsync();
// Assert
// The authenticated request reaches the handler and the database, where the book does not exist, so the request fails
// cleanly without executing the injected payload or leaking database details.
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(maliciousLocationRef, content, StringComparison.Ordinal);
await _apiFactory.RemoveTestUserAsync(username);
}
[Theory]
[InlineData("../../etc/passwd")] // Directory traversal.
[InlineData("..%2F..%2Fetc%2Fpasswd")] // Encoded directory traversal.
public async Task GetReadingSection_WithPathTraversalInLocationRef_ShouldNotExposeFilesystemPaths(string traversalPayload)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/sections/{traversalPayload}");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.DoesNotContain("etc/passwd", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
Assert.DoesNotContain("Stack Trace", content, StringComparison.Ordinal);
await _apiFactory.RemoveTestUserAsync(username);
}
[Fact]
public async Task GetReadingSection_WhenUserDoesNotOwnTheBookLibrary_ShouldReturnForbidden()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
await _apiFactory.SeedBookAsync(libraryId, "Other User Book");
Guid bookId;
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
bookId = dbContext.Books.Single(book => book.LibraryId == libraryId).Id;
}
HttpClient requesterClient = _apiFactory.CreateClient();
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
// Act
HttpResponseMessage response = await requesterClient.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/sections/chapter-1");
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
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());
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveTestUserAsync(requesterUsername);
}
}
@@ -0,0 +1,165 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
/// <summary>
/// Contains security tests for the <see cref="RestoreBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreBookEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private readonly List<string> _seededUsernames = [];
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreBookEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RestoreBookEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task RestoreBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/restore";
// Act
HttpResponseMessage response = await _client.PostAsync(url, null);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // Command execution attempt.
public async Task RestoreBook_WithSQLInjectionInRouteIds_ShouldNotCorruptOrLeakData(string maliciousId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/books/{Uri.EscapeDataString(maliciousId)}/restore", null);
// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
}
[Fact]
public async Task RestoreBook_WhenBookBelongsToAnotherUser_ShouldReturnForbiddenAndKeepItDeleted()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
(Guid libraryId, Guid bookId) = await SeedLibraryAndDeletedBookAsync(victimUserId);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/restore", null);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
BookEntity? book = await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId);
Assert.NotNull(book);
Assert.True(book!.IsDeleted);
}
[Fact]
public async Task RestoreBook_WhenBookIsRestoredThroughAnotherLibrary_ShouldReturnNotFoundAndKeepItDeleted()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(actingUsername);
(Guid ownLibraryId, _) = await SeedLibraryAndDeletedBookAsync(actingUserId, isDeleted: false);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
(_, Guid victimBookId) = await SeedLibraryAndDeletedBookAsync(victimUserId);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{ownLibraryId}/books/{victimBookId}/restore", null);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
BookEntity? victimBook = await dbContext.Books.FirstOrDefaultAsync(book => book.Id == victimBookId);
Assert.NotNull(victimBook);
Assert.True(victimBook!.IsDeleted);
}
/// <summary>
/// Seeds an ebook library owned by <paramref name="userId"/>, together with a book in the requested deletion state.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="isDeleted">Whether the seeded book is soft deleted.</param>
/// <returns>The Ids of the seeded library and book.</returns>
private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndDeletedBookAsync(Guid userId, bool isDeleted = true)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create(libraryId: libraryId, path: $"/books/{Guid.NewGuid():N}.epub", isDeleted: isDeleted, includeMetadata: false);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.EBook, contentLocations: []));
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();
return (libraryId, book.Id);
}
/// <summary>
/// Removes the users created by the tests.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,184 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook;
/// <summary>
/// Contains security tests for the <see cref="UpdateBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateBookEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly LuminaApiFactory _apiFactory;
private readonly UpdateBookRequestFixture _updateBookRequestFixture = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateBookEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdateBookEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task UpdateBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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}/books/{bookId}", problemDetails["instance"].GetProperty("value").GetString());
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task UpdateBook_WithSQLInjectionInBody_ShouldNotCorruptOrLeakData(string maliciousTitle)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: maliciousTitle));
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request);
// Assert
// The injected title is validated and handled by the parameterized update flow: the route book does not exist,
// so the request fails with a clean not found response and the injected payload is never executed as SQL.
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(maliciousTitle, content, StringComparison.Ordinal);
await _apiFactory.RemoveTestUserAsync(username);
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task UpdateBook_WithSQLInjectionInRouteId_ShouldNeverCorruptOrLeakData(string maliciousBookId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{Uri.EscapeDataString(maliciousBookId)}", request);
// Assert
// The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the command
// validator, which reports it as a clean validation error. The response must not leak stack traces, database details,
// or the injected payload.
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(maliciousBookId, content, StringComparison.Ordinal);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Contains("BookIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
await _apiFactory.RemoveTestUserAsync(username);
}
[Fact]
public async Task UpdateBook_WhenRouteBookDoesNotExist_ShouldReturnNotFound()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
Guid routeId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create();
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{routeId}", request);
// 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);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
Assert.Equal("BookNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
await _apiFactory.RemoveTestUserAsync(username);
}
[Fact]
public async Task UpdateBook_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
await _apiFactory.SeedBookAsync(libraryId, "Other User Book");
Guid bookId;
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
bookId = dbContext.Books.Single(book => book.LibraryId == libraryId).Id;
}
HttpClient requesterClient = _apiFactory.CreateClient();
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
UpdateBookRequest request = _updateBookRequestFixture.Create();
// Act
HttpResponseMessage response = await requesterClient.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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());
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveTestUserAsync(requesterUsername);
}
}
@@ -0,0 +1,158 @@
#region ========================================================================= USING =====================================================================================
using Lumina.DataAccess.Core.UoW;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover;
/// <summary>
/// Contains security tests for the <see cref="UpdateBookCoverEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdateBookCoverEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly LuminaApiFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateBookCoverEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdateBookCoverEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task UpdateBookCover_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
// Act
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", form);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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}/books/{bookId}/cover", problemDetails["instance"].GetProperty("value").GetString());
}
[Fact]
public async Task UpdateBookCover_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden()
{
// Arrange
HttpClient ownerClient = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
Guid libraryId = Guid.NewGuid();
await _apiFactory.SeedLibraryAsync(libraryId, ownerId);
await _apiFactory.SeedBookAsync(libraryId, "Other User Book");
Guid bookId;
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
bookId = dbContext.Books.Single(book => book.LibraryId == libraryId).Id;
}
HttpClient requesterClient = _apiFactory.CreateClient();
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient);
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
// Act
HttpResponseMessage response = await requesterClient.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", form);
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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());
await _apiFactory.RemoveTestUserAsync(ownerUsername);
await _apiFactory.RemoveTestUserAsync(requesterUsername);
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // Destructive injection.
[InlineData("' OR '1'='1")] // Boolean-based injection.
public async Task UpdateBookCover_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousBookId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
MultipartFormDataContent form = CreateCoverForm("cover.jpg");
// Act
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Uri.EscapeDataString(maliciousBookId)}/cover", form);
// Assert
// The unparseable route value becomes an empty book Id, which the command validator reports as a missing book Id.
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using JsonDocument problemDetails = JsonDocument.Parse(content);
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
await _apiFactory.RemoveTestUserAsync(username);
}
[Fact]
public async Task UpdateBookCover_WithMaliciousFileName_ShouldNotCorruptOrLeakData()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
MultipartFormDataContent form = CreateCoverForm("..\\..\\evil.jpg");
// Act
HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/cover", form);
// Assert
// The book 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);
await _apiFactory.RemoveTestUserAsync(username);
}
/// <summary>
/// Creates a multipart form carrying a minimal cover payload with the specified file name.
/// </summary>
/// <param name="fileName">The name of the uploaded file.</param>
/// <returns>A configured <see cref="MultipartFormDataContent"/> instance.</returns>
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;
}
}