Implements tests for commit dfd979ec1e

This commit is contained in:
BinaryAlley committed 2026-10-28 10:07:57 +02:00
1 parent d8adf3c1b6
commit 968061e89a
111 files changed
+19955 -292

No files matched your search

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