Implements tests for commit 00d7eff777

Covers genre consumption and delete-item-history across application, contracts, API, and Web. Changes the new string-bound request pipelines to return validation problems instead of 500 for malformed values.
This commit is contained in:
BinaryAlley committed 2026-10-28 12:27:34 +02:00
1 parent 968061e89a
commit 1afb078efc
91 files changed
+14499 -50

No files matched your search

@@ -0,0 +1,465 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
/// <summary>
/// Contains security tests for the <see cref="DeleteConsumptionItemHistoryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteConsumptionItemHistoryEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private static readonly DateTime s_startedOnUtc = new(2026, 5, 1, 9, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 5, 1, 9, 10, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="DeleteConsumptionItemHistoryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeleteConsumptionItemHistoryEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task DeleteConsumptionItemHistory_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task DeleteConsumptionItemHistory_WhenOwnItemIsDeleted_ShouldReturnNonCacheableResponseWithoutSensitiveData()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
await AssertRecordsAreDeletedAsync(recordId);
}
[Fact]
public async Task DeleteConsumptionItemHistory_WhenAnotherUsersItemIdIsUsed_ShouldSucceedAndPreserveThatUsersRecords()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid ownLibraryId = await SeedLibraryAsync(userId);
Guid ownRecordId = await SeedRecordAsync(userId, ownLibraryId, MediaKind.MusicTrack, Guid.NewGuid(), 60_000);
(Guid otherUserId, _) = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId);
Guid sharedItemId = Guid.NewGuid();
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId, MediaKind.MusicTrack, sharedItemId, 60_000);
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{sharedItemId}/{otherUserLibraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
// Deleting an item that does not belong to the caller succeeds, but it must never remove the other user's rows.
await AssertRecordsArePreservedAsync(otherUserRecordId, ownRecordId);
}
[Fact]
public async Task DeleteConsumptionItemHistory_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndDeleteOnlyTheMatchingRecords()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid ownLibraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid ownRecordId = await SeedRecordAsync(userId, ownLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
(Guid otherUserId, _) = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId);
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{ownLibraryId}?userId={otherUserId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
// The route identifier belongs to the caller, so the spoofed query parameter cannot redirect the deletion.
await AssertRecordsAreDeletedAsync(ownRecordId);
await AssertRecordsArePreservedAsync(otherUserRecordId);
}
[Fact]
public async Task DeleteConsumptionItemHistory_WhenCalledTwice_ShouldSucceedAndStayDeleted()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
// Act
HttpResponseMessage firstResponse = await _client.DeleteAsync(url);
await AssertRecordsAreDeletedAsync(recordId);
HttpResponseMessage secondResponse = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
AssertNonCacheable(secondResponse);
await AssertRecordsAreDeletedAsync(recordId);
}
[Theory]
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
[InlineData("../../../etc/passwd")] // path traversal
[InlineData("<script>alert(1)</script>")] // markup injection
public async Task DeleteConsumptionItemHistory_WithInjectionInMediaKind_ShouldRejectWithoutDeletingRows(string maliciousMediaKind)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"/api/v1/users/me/consumption-history/media-items/{Uri.EscapeDataString(maliciousMediaKind)}/{mediaItemId}/{libraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedInjectionAsync(response, maliciousMediaKind, url, "UnsupportedMediaKind");
await AssertRecordsArePreservedAsync(recordId);
}
[Theory]
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
[InlineData("../../../etc/passwd")] // path traversal
[InlineData("<script>alert(1)</script>")] // markup injection
public async Task DeleteConsumptionItemHistory_WithInjectionInMediaItemId_ShouldRejectWithoutDeletingRows(string maliciousMediaItemId)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Uri.EscapeDataString(maliciousMediaItemId)}/{libraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedInjectionAsync(response, maliciousMediaItemId, url, "MediaItemIdCannotBeEmpty");
await AssertRecordsArePreservedAsync(recordId);
}
[Theory]
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
[InlineData("../../../etc/passwd")] // path traversal
[InlineData("<script>alert(1)</script>")] // markup injection
public async Task DeleteConsumptionItemHistory_WithInjectionInLibraryId_ShouldRejectWithoutDeletingRows(string maliciousLibraryId)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{Uri.EscapeDataString(maliciousLibraryId)}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedInjectionAsync(response, maliciousLibraryId, url, "LibraryIdCannotBeEmpty");
await AssertRecordsArePreservedAsync(recordId);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a media library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Owner Library", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the record.</param>
/// <param name="libraryId">The Id of the library that contains the media item.</param>
/// <param name="mediaKind">The kind of the consumed media item.</param>
/// <param name="mediaItemId">The Id of the consumed media item.</param>
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
/// <returns>The Id of the seeded record.</returns>
private async Task<Guid> SeedRecordAsync(Guid userId, Guid libraryId, MediaKind mediaKind, Guid mediaItemId, long consumedDurationMilliseconds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid recordId = Guid.NewGuid();
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: recordId,
userId: userId,
libraryId: libraryId,
mediaKind: mediaKind,
mediaItemId: mediaItemId,
status: ConsumptionStatus.Stopped,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
consumedDurationMilliseconds: consumedDurationMilliseconds,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 45_000,
lastPositionLocation: null,
lastProgressFraction: 0.5,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return recordId;
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts that a malicious route value is rejected with a client error that never discloses internals or deletes rows.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <param name="requestPath">The request path the value was sent in.</param>
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
private async Task AssertRejectedInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode)
{
string content = await response.Content.ReadAsStringAsync();
// An unparseable route value must never become a server error, and it must never be reported as a successful request.
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.NotEqual(HttpStatusCode.OK, response.StatusCode);
if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
{
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
// The instance is the request path with the rejected payload still in place, independent of how the server escapes it.
string escapedPayload = Uri.EscapeDataString(payload);
int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal);
string? instance = problemDetails["instance"].GetString();
Assert.NotNull(instance);
Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path.");
Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal);
Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNonCacheable(response);
}
else
{
// A payload that carries encoded path separators is rejected by routing before it reaches the endpoint. That is still a safe rejection.
Assert.Contains("/", payload, StringComparison.Ordinal);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
AssertNoSensitiveData(content);
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
// has run, instead of assuming that it already has.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
if (storedRecords.Count == 0)
return;
await Task.Delay(100);
}
Assert.Empty(storedRecords);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
// completion has run, instead of trusting the state observed right after the response.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
Assert.Equal(recordIds.Length, storedRecords.Count);
await Task.Delay(100);
}
Assert.Equal(recordIds.Length, storedRecords.Count);
}
/// <summary>
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,540 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
/// <summary>
/// Contains security tests for the <see cref="DeleteUserConsumptionItemHistoryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteUserConsumptionItemHistoryEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private const string PATH_PREFIX = "/api/v1/users/";
private const string PATH_SUFFIX = "/consumption-history/media-items/";
private static readonly DateTime s_startedOnUtc = new(2026, 5, 2, 9, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 5, 2, 9, 10, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
private readonly List<Guid> _adminUserIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="DeleteUserConsumptionItemHistoryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeleteUserConsumptionItemHistoryEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task DeleteUserConsumptionItemHistory_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task DeleteUserConsumptionItemHistory_WhenCallerNamesThemselves_ShouldDeleteTheOwnRecords()
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"{PATH_PREFIX}{userId}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
await AssertRecordsAreDeletedAsync(recordId);
}
[Fact]
public async Task DeleteUserConsumptionItemHistory_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheRecords()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid targetUserId, _) = await SeedOtherUserAsync();
Guid targetLibraryId = await SeedLibraryAsync(targetUserId);
Guid mediaItemId = Guid.NewGuid();
Guid targetRecordId = await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"{PATH_PREFIX}{targetUserId}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{targetLibraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
string content = await AssertForbiddenAsync(response, url);
AssertNonCacheable(response);
AssertNoSensitiveData(content);
await AssertRecordsArePreservedAsync(targetRecordId);
}
[Fact]
public async Task DeleteUserConsumptionItemHistory_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid otherUserId, _) = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId);
Guid mediaItemId = Guid.NewGuid();
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string foreignUrl = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{otherUserLibraryId}";
string missingUrl = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
// Act
HttpResponseMessage foreignResponse = await _client.DeleteAsync(foreignUrl);
HttpResponseMessage missingResponse = await _client.DeleteAsync(missingUrl);
// Assert
await AssertForbiddenAsync(foreignResponse, foreignUrl);
await AssertForbiddenAsync(missingResponse, missingUrl);
Dictionary<string, JsonElement> foreignProblem = await ReadProblemDetailsAsync(foreignResponse);
Dictionary<string, JsonElement> missingProblem = await ReadProblemDetailsAsync(missingResponse);
Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32());
Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString());
Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString());
Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString());
await AssertRecordsArePreservedAsync(otherUserRecordId);
}
[Fact]
public async Task DeleteUserConsumptionItemHistory_WhenAdminNamesAnotherUser_ShouldDeleteThatUsersRecords()
{
// Arrange
(Guid targetUserId, _) = await SeedOtherUserAsync();
Guid targetLibraryId = await SeedLibraryAsync(targetUserId);
Guid mediaItemId = Guid.NewGuid();
Guid targetRecordId = await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"{PATH_PREFIX}{targetUserId}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{targetLibraryId}";
HttpClient adminClient = _apiFactory.CreateClient();
Guid adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(adminClient);
_adminUserIds.Add(adminUserId);
try
{
// Act
HttpResponseMessage response = await adminClient.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
await AssertRecordsAreDeletedAsync(targetRecordId);
}
finally
{
adminClient.Dispose();
}
}
[Theory]
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
[InlineData("../../../etc/passwd")] // path traversal
[InlineData("<script>alert(1)</script>")] // markup injection
public async Task DeleteUserConsumptionItemHistory_WithInjectionInUserIdRouteValue_ShouldRejectWithoutDeletingRows(string maliciousUserId)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"{PATH_PREFIX}{Uri.EscapeDataString(maliciousUserId)}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedInjectionAsync(response, maliciousUserId, url, "TargetUserIdIsInvalid");
await AssertRecordsArePreservedAsync(recordId);
}
[Theory]
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
[InlineData("../../../etc/passwd")] // path traversal
[InlineData("<script>alert(1)</script>")] // markup injection
public async Task DeleteUserConsumptionItemHistory_WithInjectionInMediaKind_ShouldRejectWithoutDeletingRows(string maliciousMediaKind)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"{PATH_PREFIX}{userId}{PATH_SUFFIX}{Uri.EscapeDataString(maliciousMediaKind)}/{mediaItemId}/{libraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedInjectionAsync(response, maliciousMediaKind, url, "UnsupportedMediaKind");
await AssertRecordsArePreservedAsync(recordId);
}
[Theory]
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
[InlineData("../../../etc/passwd")] // path traversal
[InlineData("<script>alert(1)</script>")] // markup injection
public async Task DeleteUserConsumptionItemHistory_WithInjectionInMediaItemId_ShouldRejectWithoutDeletingRows(string maliciousMediaItemId)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"{PATH_PREFIX}{userId}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{Uri.EscapeDataString(maliciousMediaItemId)}/{libraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedInjectionAsync(response, maliciousMediaItemId, url, "MediaItemIdCannotBeEmpty");
await AssertRecordsArePreservedAsync(recordId);
}
[Theory]
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
[InlineData("../../../etc/passwd")] // path traversal
[InlineData("<script>alert(1)</script>")] // markup injection
public async Task DeleteUserConsumptionItemHistory_WithInjectionInLibraryId_ShouldRejectWithoutDeletingRows(string maliciousLibraryId)
{
// Arrange
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
Guid libraryId = await SeedLibraryAsync(userId);
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"{PATH_PREFIX}{userId}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{Uri.EscapeDataString(maliciousLibraryId)}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertRejectedInjectionAsync(response, maliciousLibraryId, url, "LibraryIdCannotBeEmpty");
await AssertRecordsArePreservedAsync(recordId);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a media library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Owner Library", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
await dbContext.SaveChangesAsync();
return libraryId;
}
/// <summary>
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the record.</param>
/// <param name="libraryId">The Id of the library that contains the media item.</param>
/// <param name="mediaKind">The kind of the consumed media item.</param>
/// <param name="mediaItemId">The Id of the consumed media item.</param>
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
/// <returns>The Id of the seeded record.</returns>
private async Task<Guid> SeedRecordAsync(Guid userId, Guid libraryId, MediaKind mediaKind, Guid mediaItemId, long consumedDurationMilliseconds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid recordId = Guid.NewGuid();
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: recordId,
userId: userId,
libraryId: libraryId,
mediaKind: mediaKind,
mediaItemId: mediaItemId,
status: ConsumptionStatus.Stopped,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
consumedDurationMilliseconds: consumedDurationMilliseconds,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 45_000,
lastPositionLocation: null,
lastProgressFraction: 0.5,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return recordId;
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts that the response is the exact not authorized problem document and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Reads the problem details document of <paramref name="response"/>.
/// </summary>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The parsed problem details fields.</returns>
private async Task<Dictionary<string, JsonElement>> ReadProblemDetailsAsync(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
return problemDetails!;
}
/// <summary>
/// Asserts that a malicious route value is rejected with a client error that never discloses internals or deletes rows.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <param name="requestPath">The request path the value was sent in.</param>
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
private async Task AssertRejectedInjectionAsync(
HttpResponseMessage response,
string payload,
string requestPath,
string expectedErrorCode)
{
string content = await response.Content.ReadAsStringAsync();
// An unparseable route value must never become a server error, and it must never be reported as a successful request.
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.NotEqual(HttpStatusCode.OK, response.StatusCode);
if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
{
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
// The instance is the request path with the rejected payload still in place, independent of how the server escapes it.
string escapedPayload = Uri.EscapeDataString(payload);
int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal);
string? instance = problemDetails["instance"].GetString();
Assert.NotNull(instance);
Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path.");
Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal);
Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNonCacheable(response);
}
else
{
// A payload that carries encoded path separators is rejected by routing before it reaches the endpoint. That is still a safe rejection.
Assert.Contains("/", payload, StringComparison.Ordinal);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
AssertNoSensitiveData(content);
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
// has run, instead of assuming that it already has.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
if (storedRecords.Count == 0)
return;
await Task.Delay(100);
}
Assert.Empty(storedRecords);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
// completion has run, instead of trusting the state observed right after the response.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
Assert.Equal(recordIds.Length, storedRecords.Count);
await Task.Delay(100);
}
Assert.Equal(recordIds.Length, storedRecords.Count);
}
/// <summary>
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users and admin users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
foreach (Guid userId in _adminUserIds)
_apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult();
}
}
@@ -0,0 +1,460 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.MediaConsumption;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.GetGenreConsumption;
/// <summary>
/// Contains security tests for the <see cref="GetGenreConsumptionEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetGenreConsumptionEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private const string PATH = "/api/v1/users/me/consumption-statistics/genres";
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 3, 1, 10, 5, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly GenreEntityFixture _genreEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetGenreConsumptionEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetGenreConsumptionEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetGenreConsumption_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = PATH;
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task GetGenreConsumption_WhenSuccessful_ShouldReturnOnlyCallersGenresWithoutSensitiveData()
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
string callerGenre = await SeedGenreConsumptionAsync(callerId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
string url = PATH;
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
AssertNoSensitiveData(content);
AssertNoDatabaseOnlyFields(content);
Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
List<GenreConsumptionResponse>? genres = JsonSerializer.Deserialize<List<GenreConsumptionResponse>>(content, _jsonOptions);
Assert.NotNull(genres);
GenreConsumptionResponse genre = Assert.Single(genres!);
Assert.Equal(callerGenre.ToLowerInvariant(), genre.Name);
Assert.Equal(1, genre.ConsumedItemCount);
Assert.Equal(60d, genre.ConsumedDurationInSeconds, 3);
}
[Fact]
public async Task GetGenreConsumption_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndReturnCallersGenres()
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
string callerGenre = await SeedGenreConsumptionAsync(callerId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
string url = $"{PATH}?userId={otherUserId}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
List<GenreConsumptionResponse>? genres = JsonSerializer.Deserialize<List<GenreConsumptionResponse>>(content, _jsonOptions);
Assert.NotNull(genres);
GenreConsumptionResponse genre = Assert.Single(genres!);
Assert.Equal(callerGenre.ToLowerInvariant(), genre.Name);
Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
}
[Theory]
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
[InlineData("../../../etc/passwd")] // path traversal
[InlineData("<script>alert(1)</script>")] // markup injection
public async Task GetGenreConsumption_WithInjectionInLibraryId_ShouldRejectWithoutLeakingData(string maliciousLibraryId)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedGenreConsumptionAsync(callerId);
string url = $"{PATH}?libraryId={Uri.EscapeDataString(maliciousLibraryId)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertValidationProblemAsync(response, PATH, "LibraryIdCannotBeEmpty");
AssertNonCacheable(response);
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
}
[Theory]
[InlineData("999")] // out of range numeric value
[InlineData("not-a-media-kind")] // textual value that is not an enum member
public async Task GetGenreConsumption_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedGenreConsumptionAsync(callerId);
string url = $"{PATH}?mediaKind={Uri.EscapeDataString(mediaKind)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
// The media kind is carried as text, so an unknown or numeric name reaches the validator and is reported as an
// unsupported kind instead of being rejected by request binding.
await AssertRejectedMediaKindAsync(response, PATH);
}
[Theory]
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
[InlineData("../../../etc/passwd")] // path traversal
[InlineData("<script>alert(1)</script>")] // markup injection
public async Task GetGenreConsumption_WithInjectionInFromUtc_ShouldRejectWithoutLeakingData(string maliciousFromUtc)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedGenreConsumptionAsync(callerId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
string url = $"{PATH}?fromUtc={Uri.EscapeDataString(maliciousFromUtc)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertSafeDatePayloadResponseAsync(response, maliciousFromUtc);
Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == otherUserId));
}
[Theory]
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
[InlineData("../../../etc/passwd")] // path traversal
[InlineData("<script>alert(1)</script>")] // markup injection
public async Task GetGenreConsumption_WithInjectionInToUtc_ShouldRejectWithoutLeakingData(string maliciousToUtc)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedGenreConsumptionAsync(callerId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
string url = $"{PATH}?toUtc={Uri.EscapeDataString(maliciousToUtc)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertSafeDatePayloadResponseAsync(response, maliciousToUtc);
Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == otherUserId));
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a uniquely genred track in a library owned by <paramref name="userId"/> and one completed session of it.
/// </summary>
/// <param name="userId">The Id of the user that owns the records.</param>
/// <returns>The unique name of the seeded genre.</returns>
private async Task<string> SeedGenreConsumptionAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
string suffix = Guid.NewGuid().ToString("N")[..8];
// Genre names are the primary key of a shared table, so every seeded name carries a unique suffix.
string genreName = $"Genre-{suffix}";
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: $"Library-{suffix}", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: $"Artist-{suffix}", includeAlbums: false, includeContributors: false, includeMetadata: false));
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: $"Album-{suffix}", includeTracks: false, includeMetadata: false));
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: $"Track-{suffix}", includeMetadata: false);
GenreEntity genre = _genreEntityFixture.Create(name: genreName);
track.Genres.Add(genre);
dbContext.Tracks.Add(track);
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: Guid.NewGuid(),
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: trackId,
status: ConsumptionStatus.Completed,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
consumedDurationMilliseconds: 60_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 60_000,
lastProgressFraction: 1.0,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return genreName;
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts the shape of a validation problem details response and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts that an unparseable media kind is rejected without returning data or disclosing internals.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]);
AssertNonCacheable(response);
AssertNoSensitiveData(content);
Assert.DoesNotContain("\"consumedItemCount\"", content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that a malicious date bound never causes a server error, never leaks internals, and never returns data of another user.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertSafeDatePayloadResponseAsync(HttpResponseMessage response, string payload)
{
string content = await response.Content.ReadAsStringAsync();
// A bound date is parsed before the handler runs, so an unparseable value must either be ignored or rejected, but it must never reach the
// storage medium, fail the request, or disclose internals.
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.True(
response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.BadRequest || response.StatusCode == HttpStatusCode.UnprocessableEntity,
$"Unexpected status code {response.StatusCode} for a date bound payload.");
AssertNoSensitiveData(content);
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
return content;
}
/// <summary>
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Asserts that the serialized genres expose only the fields of their documented response contract.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoDatabaseOnlyFields(string content)
{
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,617 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Responses.MediaConsumption;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.GetGenreConsumption;
/// <summary>
/// Contains security tests for the <see cref="GetUserGenreConsumptionEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUserGenreConsumptionEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
private const string PATH_PREFIX = "/api/v1/users/";
private const string PATH_SUFFIX = "/consumption-statistics/genres";
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_lastActivityOnUtc = new(2026, 3, 1, 10, 5, 0, DateTimeKind.Utc);
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly GenreEntityFixture _genreEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
private readonly List<Guid> _adminUserIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetUserGenreConsumptionEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetUserGenreConsumptionEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
// A unique X-Forwarded-For isolates rate limiting state per test.
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetUserGenreConsumption_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task GetUserGenreConsumption_WhenAnotherUsersGenresAreRequested_ShouldReturnForbiddenWithoutDisclosingData()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
string url = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertForbiddenAsync(response, url);
AssertNonCacheable(response);
Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("consumedItemCount", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetUserGenreConsumption_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
{
// Arrange
await CreateAuthenticatedUserAsync(_client);
(Guid otherUserId, _) = await SeedOtherUserAsync();
await SeedGenreConsumptionAsync(otherUserId);
string foreignUrl = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
string missingUrl = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
// Act
HttpResponseMessage foreignResponse = await _client.GetAsync(foreignUrl);
HttpResponseMessage missingResponse = await _client.GetAsync(missingUrl);
// Assert
await AssertForbiddenAsync(foreignResponse, foreignUrl);
await AssertForbiddenAsync(missingResponse, missingUrl);
Dictionary<string, JsonElement> foreignProblem = await ReadProblemDetailsAsync(foreignResponse);
Dictionary<string, JsonElement> missingProblem = await ReadProblemDetailsAsync(missingResponse);
Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32());
Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString());
Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString());
Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString());
}
[Fact]
public async Task GetUserGenreConsumption_WhenAdminRequestsAnotherUser_ShouldReturnOnlyThatUsersGenres()
{
// Arrange
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
HttpClient adminClient = _apiFactory.CreateClient();
Guid adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(adminClient);
_adminUserIds.Add(adminUserId);
string url = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
try
{
// Act
HttpResponseMessage response = await adminClient.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
AssertNoSensitiveData(content);
AssertNoDatabaseOnlyFields(content);
List<GenreConsumptionResponse>? genres = JsonSerializer.Deserialize<List<GenreConsumptionResponse>>(content, _jsonOptions);
Assert.NotNull(genres);
GenreConsumptionResponse genre = Assert.Single(genres!);
Assert.Equal(otherGenre.ToLowerInvariant(), genre.Name);
Assert.Equal(1, genre.ConsumedItemCount);
}
finally
{
adminClient.Dispose();
}
}
[Fact]
public async Task GetUserGenreConsumption_WhenCallerNamesThemselves_ShouldReturnOwnGenres()
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
string callerGenre = await SeedGenreConsumptionAsync(callerId);
string url = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertNonCacheable(response);
string content = await response.Content.ReadAsStringAsync();
List<GenreConsumptionResponse>? genres = JsonSerializer.Deserialize<List<GenreConsumptionResponse>>(content, _jsonOptions);
Assert.NotNull(genres);
GenreConsumptionResponse genre = Assert.Single(genres!);
Assert.Equal(callerGenre.ToLowerInvariant(), genre.Name);
}
[Theory]
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
[InlineData("../../../etc/passwd")] // path traversal
[InlineData("<script>alert(1)</script>")] // markup injection
public async Task GetUserGenreConsumption_WithInjectionInUserIdRouteValue_ShouldRejectWithoutLeakingData(string maliciousUserId)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedGenreConsumptionAsync(callerId);
string url = $"{PATH_PREFIX}{Uri.EscapeDataString(maliciousUserId)}{PATH_SUFFIX}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertRejectedRouteValueAsync(response, maliciousUserId, PATH_PREFIX, PATH_SUFFIX, "TargetUserIdIsInvalid");
AssertNonCacheable(response);
Assert.DoesNotContain(maliciousUserId, content, StringComparison.Ordinal);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
}
[Theory]
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
[InlineData("../../../etc/passwd")] // path traversal
[InlineData("<script>alert(1)</script>")] // markup injection
public async Task GetUserGenreConsumption_WithInjectionInLibraryId_ShouldRejectWithoutLeakingData(string maliciousLibraryId)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedGenreConsumptionAsync(callerId);
string path = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
string url = $"{path}?libraryId={Uri.EscapeDataString(maliciousLibraryId)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertValidationProblemAsync(response, path, "LibraryIdCannotBeEmpty");
AssertNonCacheable(response);
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
}
[Theory]
[InlineData("999")] // out of range numeric value
[InlineData("not-a-media-kind")] // textual value that is not an enum member
public async Task GetUserGenreConsumption_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedGenreConsumptionAsync(callerId);
string path = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
string url = $"{path}?mediaKind={Uri.EscapeDataString(mediaKind)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
// The media kind is carried as text, so an unknown or numeric name reaches the validator and is reported as an
// unsupported kind instead of being rejected by request binding.
await AssertRejectedMediaKindAsync(response, path);
}
[Theory]
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
[InlineData("../../../etc/passwd")] // path traversal
[InlineData("<script>alert(1)</script>")] // markup injection
public async Task GetUserGenreConsumption_WithInjectionInFromUtc_ShouldRejectWithoutLeakingData(string maliciousFromUtc)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedGenreConsumptionAsync(callerId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
string path = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
string url = $"{path}?fromUtc={Uri.EscapeDataString(maliciousFromUtc)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertSafeDatePayloadResponseAsync(response, maliciousFromUtc);
Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == otherUserId));
}
[Theory]
[InlineData("' OR '1'='1")] // boolean-based injection
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
[InlineData("../../../etc/passwd")] // path traversal
[InlineData("<script>alert(1)</script>")] // markup injection
public async Task GetUserGenreConsumption_WithInjectionInToUtc_ShouldRejectWithoutLeakingData(string maliciousToUtc)
{
// Arrange
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
await SeedGenreConsumptionAsync(callerId);
(Guid otherUserId, _) = await SeedOtherUserAsync();
string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
string path = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
string url = $"{path}?toUtc={Uri.EscapeDataString(maliciousToUtc)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
string content = await AssertSafeDatePayloadResponseAsync(response, maliciousToUtc);
Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == otherUserId));
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
/// </summary>
/// <returns>The Id and username of the seeded user.</returns>
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a uniquely genred track in a library owned by <paramref name="userId"/> and one completed session of it.
/// </summary>
/// <param name="userId">The Id of the user that owns the records.</param>
/// <returns>The unique name of the seeded genre.</returns>
private async Task<string> SeedGenreConsumptionAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
string suffix = Guid.NewGuid().ToString("N")[..8];
// Genre names are the primary key of a shared table, so every seeded name carries a unique suffix.
string genreName = $"Genre-{suffix}";
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid trackId = Guid.NewGuid();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: $"Library-{suffix}", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: $"Artist-{suffix}", includeAlbums: false, includeContributors: false, includeMetadata: false));
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: $"Album-{suffix}", includeTracks: false, includeMetadata: false));
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: $"Track-{suffix}", includeMetadata: false);
GenreEntity genre = _genreEntityFixture.Create(name: genreName);
track.Genres.Add(genre);
dbContext.Tracks.Add(track);
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
id: Guid.NewGuid(),
userId: userId,
libraryId: libraryId,
mediaKind: MediaKind.MusicTrack,
mediaItemId: trackId,
status: ConsumptionStatus.Completed,
startedOnUtc: s_startedOnUtc,
lastActivityOnUtc: s_lastActivityOnUtc,
consumedDurationMilliseconds: 60_000,
lastPositionKind: MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: 60_000,
lastProgressFraction: 1.0,
consecutivePagesRead: 0));
await dbContext.SaveChangesAsync();
return genreName;
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
AssertNoSensitiveData(content);
}
/// <summary>
/// Asserts that the response is the exact not authorized problem document and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Reads the problem details document of <paramref name="response"/>.
/// </summary>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The parsed problem details fields.</returns>
private async Task<Dictionary<string, JsonElement>> ReadProblemDetailsAsync(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
return problemDetails!;
}
/// <summary>
/// Asserts that a malicious route value is rejected without disclosing internals.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <param name="pathPrefix">The request path that precedes the malicious value.</param>
/// <param name="pathSuffix">The request path that follows the malicious value.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertRejectedRouteValueAsync(HttpResponseMessage response, string payload, string pathPrefix, string pathSuffix, string expectedErrorCode)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
// The instance is the request path with the rejected payload in place, so decoding the middle segment must give the payload back.
string? instance = problemDetails["instance"].GetString();
Assert.NotNull(instance);
Assert.StartsWith(pathPrefix, instance, StringComparison.Ordinal);
Assert.EndsWith(pathSuffix, instance, StringComparison.Ordinal);
string encodedSegment = instance![pathPrefix.Length..(instance.Length - pathSuffix.Length)];
Assert.Equal(payload, Uri.UnescapeDataString(encodedSegment));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts the shape of a validation problem details response and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts that an unparseable media kind is rejected without returning data or disclosing internals.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]);
AssertNonCacheable(response);
AssertNoSensitiveData(content);
Assert.DoesNotContain("\"consumedItemCount\"", content, StringComparison.Ordinal);
}
/// <summary>
/// Asserts that a malicious date bound never causes a server error, never leaks internals, and never returns data of another user.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="payload">The malicious value that was sent.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private static async Task<string> AssertSafeDatePayloadResponseAsync(HttpResponseMessage response, string payload)
{
string content = await response.Content.ReadAsStringAsync();
// A bound date is parsed before the handler runs, so an unparseable value must either be ignored or rejected, but it must never reach the
// storage medium, fail the request, or disclose internals.
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.True(
response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.BadRequest || response.StatusCode == HttpStatusCode.UnprocessableEntity,
$"Unexpected status code {response.StatusCode} for a date bound payload.");
AssertNoSensitiveData(content);
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
return content;
}
/// <summary>
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
private static void AssertNonCacheable(HttpResponseMessage response)
{
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoSensitiveData(string content)
{
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Asserts that the serialized genres expose only the fields of their documented response contract.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoDatabaseOnlyFields(string content)
{
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the test users and admin users created by the test.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
foreach (Guid userId in _adminUserIds)
_apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult();
}
}
@@ -0,0 +1,161 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
/// <summary>
/// Contains security tests for the <see cref="ClearConsumptionHistoryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ClearConsumptionHistoryEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
{
private static readonly string s_userId = Guid.NewGuid().ToString();
private readonly LuminaWebFactory _apiFactory;
private readonly ClearConsumptionHistoryRequestFixture _clearConsumptionHistoryRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ClearConsumptionHistoryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public ClearConsumptionHistoryEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task ClearConsumptionHistory_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create(userId: s_userId);
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
deleteRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
// Act
HttpResponseMessage response = await client.SendAsync(deleteRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
}
[Fact]
public async Task ClearConsumptionHistory_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create(userId: s_userId);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
}
[Fact]
public async Task ClearConsumptionHistory_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create(userId: s_userId);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
deleteRequest.Headers.Add("RequestVerificationToken", "invalid-token");
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
}
[Fact]
public async Task ClearConsumptionHistory_WithCraftedUserId_ShouldEscapeTheValueAndKeepTheDocumentedUpstreamPath()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
const string CRAFTED_USER_ID = "user/../admin?x=1&y=2";
const string EXPECTED_UPSTREAM_PATH = "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-history";
ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create(userId: CRAFTED_USER_ID);
_apiFactory.ApiClientStub.RegisterDeleteSuccess(EXPECTED_UPSTREAM_PATH);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Equal([EXPECTED_UPSTREAM_PATH], _apiFactory.ApiClientStub.DeleteEndpointsCalled);
Assert.True(response.Headers.CacheControl?.NoStore);
Assert.True(response.Headers.CacheControl?.Private);
Assert.Contains("Cookie", response.Headers.Vary);
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
/// <summary>
/// Builds the path of the Web route that clears the consumption history described by <paramref name="request"/>.
/// </summary>
/// <param name="request">The request describing the history to clear.</param>
/// <returns>The path of the Web route, including the escaped user identifier.</returns>
private static string BuildRequestPath(ClearConsumptionHistoryRequest request)
{
return string.IsNullOrWhiteSpace(request.UserId)
? "/en-us/library/statistics/api-clear-consumption-history"
: $"/en-us/library/statistics/api-clear-consumption-history?userId={Uri.EscapeDataString(request.UserId)}";
}
/// <summary>
/// Builds a DELETE request for <paramref name="path"/> that carries the JSON content type required by the antiforgery middleware.
/// </summary>
/// <param name="path">The path of the Web route to call.</param>
/// <returns>The configured DELETE request.</returns>
private static HttpRequestMessage CreateDeleteRequest(string path)
{
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, path)
{
Content = new StringContent("{}", Encoding.UTF8, "application/json")
};
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return deleteRequest;
}
}
@@ -0,0 +1,168 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.ClearResumePoints;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.ClearResumePoints;
/// <summary>
/// Contains security tests for the <see cref="ClearResumePointsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ClearResumePointsEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
{
private static readonly string s_userId = Guid.NewGuid().ToString();
private readonly LuminaWebFactory _apiFactory;
private readonly ClearResumePointsRequestFixture _clearResumePointsRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ClearResumePointsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public ClearResumePointsEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task ClearResumePoints_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(userId: s_userId);
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
deleteRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
// Act
HttpResponseMessage response = await client.SendAsync(deleteRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
}
[Fact]
public async Task ClearResumePoints_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(userId: s_userId);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
}
[Fact]
public async Task ClearResumePoints_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(userId: s_userId);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
deleteRequest.Headers.Add("RequestVerificationToken", "invalid-token");
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
}
[Fact]
public async Task ClearResumePoints_WithCraftedUserAndLibraryIds_ShouldEscapeTheValuesAndKeepTheDocumentedUpstreamPath()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
const string CRAFTED_USER_ID = "user/../admin?x=1&y=2";
const string CRAFTED_LIBRARY_ID = "lib?x=1&y=2";
const string EXPECTED_UPSTREAM_PATH = "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/media-resume-points?libraryId=lib%3Fx%3D1%26y%3D2";
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(userId: CRAFTED_USER_ID, libraryId: CRAFTED_LIBRARY_ID);
_apiFactory.ApiClientStub.RegisterDeleteSuccess(EXPECTED_UPSTREAM_PATH);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Equal([EXPECTED_UPSTREAM_PATH], _apiFactory.ApiClientStub.DeleteEndpointsCalled);
Assert.True(response.Headers.CacheControl?.NoStore);
Assert.True(response.Headers.CacheControl?.Private);
Assert.Contains("Cookie", response.Headers.Vary);
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
/// <summary>
/// Builds the path of the Web route that clears the resume points described by <paramref name="request"/>.
/// </summary>
/// <param name="request">The request describing the resume points to clear.</param>
/// <returns>The path of the Web route, including the escaped query string.</returns>
private static string BuildRequestPath(ClearResumePointsRequest request)
{
List<string> parameters = [];
if (!string.IsNullOrWhiteSpace(request.UserId))
parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
if (!string.IsNullOrWhiteSpace(request.LibraryId))
parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
return parameters.Count == 0
? "/en-us/library/statistics/api-clear-resume-points"
: $"/en-us/library/statistics/api-clear-resume-points?{string.Join("&", parameters)}";
}
/// <summary>
/// Builds a DELETE request for <paramref name="path"/> that carries the JSON content type required by the antiforgery middleware.
/// </summary>
/// <param name="path">The path of the Web route to call.</param>
/// <returns>The configured DELETE request.</returns>
private static HttpRequestMessage CreateDeleteRequest(string path)
{
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, path)
{
Content = new StringContent("{}", Encoding.UTF8, "application/json")
};
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return deleteRequest;
}
}
@@ -0,0 +1,206 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
/// <summary>
/// Contains security tests for the <see cref="DeleteConsumptionItemHistoryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteConsumptionItemHistoryEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
{
private static readonly string s_userId = Guid.NewGuid().ToString();
private static readonly Guid s_mediaItemId = Guid.Parse("11111111-1111-1111-1111-111111111111");
private static readonly Guid s_libraryId = Guid.Parse("22222222-2222-2222-2222-222222222222");
private readonly LuminaWebFactory _apiFactory;
private readonly DeleteConsumptionItemHistoryRequestFixture _deleteConsumptionItemHistoryRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="DeleteConsumptionItemHistoryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public DeleteConsumptionItemHistoryEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task DeleteConsumptionItemHistory_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
DeleteConsumptionItemHistoryRequest request = CreateRequest(s_userId);
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
deleteRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
// Act
HttpResponseMessage response = await client.SendAsync(deleteRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
}
[Fact]
public async Task DeleteConsumptionItemHistory_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
DeleteConsumptionItemHistoryRequest request = CreateRequest(s_userId);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
}
[Fact]
public async Task DeleteConsumptionItemHistory_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
DeleteConsumptionItemHistoryRequest request = CreateRequest(s_userId);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
deleteRequest.Headers.Add("RequestVerificationToken", "invalid-token");
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
}
[Theory]
[InlineData("Movie%2F..%2Fadmin%3Fx%3D1")] // path traversal attempt in the media kind
[InlineData("NotAMediaKind")] // undefined enum member
public async Task DeleteConsumptionItemHistory_WithCraftedMediaKind_ShouldRejectRequestAndNotCallApi(string craftedMediaKind)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
string path = $"/en-us/library/statistics/api-delete-consumption-item-history?userId={Uri.EscapeDataString(s_userId)}&mediaKind={craftedMediaKind}&mediaItemId={s_mediaItemId}&libraryId={s_libraryId}";
HttpRequestMessage deleteRequest = CreateDeleteRequest(path);
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
using JsonDocument json = JsonDocument.Parse(content);
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
}
[Fact]
public async Task DeleteConsumptionItemHistory_WithCraftedUserId_ShouldEscapeTheValueAndKeepTheDocumentedUpstreamPath()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
const string CRAFTED_USER_ID = "user/../admin?x=1&y=2";
const string EXPECTED_UPSTREAM_PATH = "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-history/media-items/Movie/11111111-1111-1111-1111-111111111111/22222222-2222-2222-2222-222222222222";
DeleteConsumptionItemHistoryRequest request = CreateRequest(CRAFTED_USER_ID);
_apiFactory.ApiClientStub.RegisterDeleteSuccess(EXPECTED_UPSTREAM_PATH);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Equal([EXPECTED_UPSTREAM_PATH], _apiFactory.ApiClientStub.DeleteEndpointsCalled);
Assert.True(response.Headers.CacheControl?.NoStore);
Assert.True(response.Headers.CacheControl?.Private);
Assert.Contains("Cookie", response.Headers.Vary);
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
/// <summary>
/// Creates the request used by the tests for the specified user.
/// </summary>
/// <param name="userId">The Id of the user whose item history is deleted.</param>
/// <returns>The configured request.</returns>
private DeleteConsumptionItemHistoryRequest CreateRequest(string userId)
{
return _deleteConsumptionItemHistoryRequestFixture.Create(
userId: userId,
mediaKind: MediaKind.Movie,
mediaItemId: s_mediaItemId,
libraryId: s_libraryId);
}
/// <summary>
/// Builds the path of the Web route that deletes the item history described by <paramref name="request"/>.
/// </summary>
/// <param name="request">The request describing the item history to delete.</param>
/// <returns>The path of the Web route, including the escaped query string.</returns>
private static string BuildRequestPath(DeleteConsumptionItemHistoryRequest request)
{
List<string> parameters = [];
if (!string.IsNullOrWhiteSpace(request.UserId))
parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.ToString())}");
parameters.Add($"mediaItemId={request.MediaItemId}");
parameters.Add($"libraryId={request.LibraryId}");
return $"/en-us/library/statistics/api-delete-consumption-item-history?{string.Join("&", parameters)}";
}
/// <summary>
/// Builds a DELETE request for <paramref name="path"/> that carries the JSON content type required by the antiforgery middleware.
/// </summary>
/// <param name="path">The path of the Web route to call.</param>
/// <returns>The configured DELETE request.</returns>
private static HttpRequestMessage CreateDeleteRequest(string path)
{
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, path)
{
Content = new StringContent("{}", Encoding.UTF8, "application/json")
};
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return deleteRequest;
}
}
@@ -0,0 +1,163 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics;
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics;
/// <summary>
/// Contains security tests for the <see cref="GetAllUsersConsumptionStatisticsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetAllUsersConsumptionStatisticsEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
{
private const string WEB_ROUTE = "/en-us/library/statistics/api-get-all-users-statistics";
private readonly LuminaWebFactory _apiFactory;
private readonly GetAllUsersConsumptionStatisticsRequestFixture _getAllUsersConsumptionStatisticsRequestFixture = new();
private readonly AllUsersConsumptionStatisticsDtoFixture _allUsersConsumptionStatisticsDtoFixture = new();
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetAllUsersConsumptionStatisticsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public GetAllUsersConsumptionStatisticsEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetAllUsersConsumptionStatistics_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, WEB_ROUTE);
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
HttpResponseMessage response = await client.SendAsync(getRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Fact]
public async Task GetAllUsersConsumptionStatistics_WhenCalledByNonAdminUser_ShouldRedirectToAccessDeniedAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Contains("access-denied", response.Headers.Location!.ToString());
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal));
}
[Fact]
public async Task GetAllUsersConsumptionStatistics_WhenCalledByAdminUser_ShouldReturnStatisticsWithoutLeakingSecrets()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
const string EXPECTED_UPSTREAM_PATH = "users/consumption-statistics";
AllUsersConsumptionStatisticsDto expectedStatistics = _allUsersConsumptionStatisticsDtoFixture.Create();
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedStatistics);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
Assert.True(response.Headers.CacheControl?.NoStore);
Assert.True(response.Headers.CacheControl?.Private);
Assert.Contains("Cookie", response.Headers.Vary);
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
}
[Fact]
public async Task GetAllUsersConsumptionStatistics_WithCraftedLibraryId_ShouldEscapeTheValueAndKeepTheDocumentedUpstreamPath()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
const string CRAFTED_LIBRARY_ID = "lib?x=1&y=2";
const string EXPECTED_UPSTREAM_PATH = "users/consumption-statistics?libraryId=lib%3Fx%3D1%26y%3D2";
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
libraryId: CRAFTED_LIBRARY_ID,
includeMediaKind: false,
includeFromUtc: false,
includeToUtc: false);
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, _allUsersConsumptionStatisticsDtoFixture.Create(includeUsers: false));
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string[] dataEndpoints = [.. _apiFactory.ApiClientStub.GetEndpointsCalled.Where(endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal))];
Assert.Equal([EXPECTED_UPSTREAM_PATH], dataEndpoints);
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
/// <summary>
/// Builds the path of the Web route for <paramref name="request"/>.
/// </summary>
/// <param name="request">The request whose filters are forwarded.</param>
/// <returns>The path of the Web route, including the query string built from the request filters.</returns>
private static string BuildRequestPath(GetAllUsersConsumptionStatisticsRequest request)
{
List<string> parameters = [];
if (!string.IsNullOrWhiteSpace(request.LibraryId))
parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
return parameters.Count == 0
? WEB_ROUTE
: $"{WEB_ROUTE}?{string.Join("&", parameters)}";
}
}
@@ -0,0 +1,145 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
/// <summary>
/// Contains security tests for the <see cref="GetConsumptionStatisticsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetConsumptionStatisticsEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
{
private const string WEB_ROUTE = "/en-us/library/statistics/api-get-statistics";
private readonly LuminaWebFactory _apiFactory;
private readonly GetConsumptionStatisticsRequestFixture _getConsumptionStatisticsRequestFixture = new();
private readonly ConsumptionSummaryDtoFixture _consumptionSummaryDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetConsumptionStatisticsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public GetConsumptionStatisticsEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetConsumptionStatistics_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, WEB_ROUTE);
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
HttpResponseMessage response = await client.SendAsync(getRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Theory]
[InlineData("Movie%2F..%2Fadmin%3Fx%3D1")] // path traversal attempt in the media kind
[InlineData("NotAMediaKind")] // undefined enum member
public async Task GetConsumptionStatistics_WithCraftedMediaKind_ShouldRejectRequestAndNotCallApi(string craftedMediaKind)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, $"{WEB_ROUTE}?mediaKind={craftedMediaKind}");
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
using JsonDocument json = JsonDocument.Parse(content);
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal));
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
}
[Fact]
public async Task GetConsumptionStatistics_WithCraftedUserAndLibraryIds_ShouldEscapeTheValuesAndKeepTheDocumentedUpstreamPath()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
const string CRAFTED_USER_ID = "user/../admin?x=1&y=2";
const string CRAFTED_LIBRARY_ID = "lib?x=1&y=2";
const string EXPECTED_UPSTREAM_PATH = "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-statistics?libraryId=lib%3Fx%3D1%26y%3D2";
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(
userId: CRAFTED_USER_ID,
libraryId: CRAFTED_LIBRARY_ID,
includeMediaKind: false,
includeFromUtc: false,
includeToUtc: false);
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, _consumptionSummaryDtoFixture.Create(includeMediaKindSummaries: false));
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
string[] dataEndpoints = [.. _apiFactory.ApiClientStub.GetEndpointsCalled.Where(endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal))];
Assert.Equal([EXPECTED_UPSTREAM_PATH], dataEndpoints);
Assert.True(response.Headers.CacheControl?.NoStore);
Assert.True(response.Headers.CacheControl?.Private);
Assert.Contains("Cookie", response.Headers.Vary);
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
/// <summary>
/// Builds the path of the Web route for <paramref name="request"/>.
/// </summary>
/// <param name="request">The request whose filters are forwarded.</param>
/// <returns>The path of the Web route, including the query string built from the request values.</returns>
private static string BuildRequestPath(GetConsumptionStatisticsRequest request)
{
List<string> parameters = [];
if (!string.IsNullOrWhiteSpace(request.UserId))
parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
if (!string.IsNullOrWhiteSpace(request.LibraryId))
parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
return parameters.Count == 0
? WEB_ROUTE
: $"{WEB_ROUTE}?{string.Join("&", parameters)}";
}
}
@@ -0,0 +1,123 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetGenreConsumption;
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.GetGenreConsumption;
/// <summary>
/// Contains security tests for the <see cref="GetGenreConsumptionEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetGenreConsumptionEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
{
private const string WEB_ROUTE = "/en-us/library/statistics/api-get-genre-consumption";
private readonly LuminaWebFactory _apiFactory;
private readonly GetGenreConsumptionRequestFixture _getGenreConsumptionRequestFixture = new();
private readonly GenreConsumptionDtoFixture _genreConsumptionDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetGenreConsumptionEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public GetGenreConsumptionEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetGenreConsumption_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, WEB_ROUTE);
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
HttpResponseMessage response = await client.SendAsync(getRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Fact]
public async Task GetGenreConsumption_WithCraftedUserAndLibraryIds_ShouldEscapeTheValuesAndKeepTheDocumentedUpstreamPath()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
const string CRAFTED_USER_ID = "user/../admin?x=1&y=2";
const string CRAFTED_LIBRARY_ID = "lib?x=1&y=2";
const string EXPECTED_UPSTREAM_PATH = "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-statistics/genres?libraryId=lib%3Fx%3D1%26y%3D2";
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
userId: CRAFTED_USER_ID,
libraryId: CRAFTED_LIBRARY_ID,
includeMediaKind: false,
includeFromUtc: false,
includeToUtc: false);
GenreConsumptionDto[] expectedGenres = [_genreConsumptionDtoFixture.Create()];
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedGenres);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
string[] dataEndpoints = [.. _apiFactory.ApiClientStub.GetEndpointsCalled.Where(endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal))];
Assert.Equal([EXPECTED_UPSTREAM_PATH], dataEndpoints);
Assert.True(response.Headers.CacheControl?.NoStore);
Assert.True(response.Headers.CacheControl?.Private);
Assert.Contains("Cookie", response.Headers.Vary);
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
/// <summary>
/// Builds the path of the Web route for <paramref name="request"/>.
/// </summary>
/// <param name="request">The request whose filters are forwarded.</param>
/// <returns>The path of the Web route, including the query string built from the request values.</returns>
private static string BuildRequestPath(GetGenreConsumptionRequest request)
{
List<string> parameters = [];
if (!string.IsNullOrWhiteSpace(request.UserId))
parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
if (!string.IsNullOrWhiteSpace(request.LibraryId))
parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
return parameters.Count == 0
? WEB_ROUTE
: $"{WEB_ROUTE}?{string.Join("&", parameters)}";
}
}
@@ -0,0 +1,93 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetLibraries;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.GetLibraries;
/// <summary>
/// Contains security tests for the <see cref="GetLibrariesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibrariesEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
{
private const string WEB_ROUTE = "/en-us/library/statistics/api-get-libraries";
private const string EXPECTED_UPSTREAM_PATH = "libraries/enabled";
private readonly LuminaWebFactory _apiFactory;
private readonly LibraryDtoFixture _libraryDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibrariesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public GetLibrariesEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetLibraries_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, WEB_ROUTE);
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
HttpResponseMessage response = await client.SendAsync(getRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Fact]
public async Task GetLibraries_WhenCalledByAuthenticatedUser_ShouldReturnLibrariesWithoutLeakingSecrets()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
LibraryDto[] expectedLibraries = [_libraryDtoFixture.Create(title: "Books", isEnabled: true)];
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedLibraries);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Equal(1, json.RootElement.GetProperty("data").GetArrayLength());
Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
Assert.True(response.Headers.CacheControl?.NoStore);
Assert.True(response.Headers.CacheControl?.Private);
Assert.Contains("Cookie", response.Headers.Vary);
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
}
@@ -0,0 +1,128 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetMostConsumed;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.GetMostConsumed;
/// <summary>
/// Contains security tests for the <see cref="GetMostConsumedEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetMostConsumedEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
{
private const string WEB_ROUTE = "/en-us/library/statistics/api-get-most-consumed";
private readonly LuminaWebFactory _apiFactory;
private readonly GetMostConsumedRequestFixture _getMostConsumedRequestFixture = new();
private readonly ConsumedItemDtoFixture _consumedItemDtoFixture = new();
private readonly PaginatedDtoFixture<ConsumedItemDto> _paginatedDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetMostConsumedEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public GetMostConsumedEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetMostConsumed_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, WEB_ROUTE);
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
HttpResponseMessage response = await client.SendAsync(getRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Fact]
public async Task GetMostConsumed_WithCraftedUserAndLibraryIds_ShouldEscapeTheValuesAndKeepTheDocumentedUpstreamPath()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
const string CRAFTED_USER_ID = "user/../admin?x=1&y=2";
const string CRAFTED_LIBRARY_ID = "lib?x=1&y=2";
const string EXPECTED_UPSTREAM_PATH = "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-history/most-consumed?libraryId=lib%3Fx%3D1%26y%3D2&currentPage=1&perPage=10";
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
userId: CRAFTED_USER_ID,
libraryId: CRAFTED_LIBRARY_ID,
includeMediaKind: false,
includeFromUtc: false,
includeToUtc: false,
includeCurrentPage: false,
includePerPage: false);
PaginatedDto<ConsumedItemDto> expectedPage = _paginatedDtoFixture.Create(data: [_consumedItemDtoFixture.Create()]);
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedPage);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
string[] dataEndpoints = [.. _apiFactory.ApiClientStub.GetEndpointsCalled.Where(endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal))];
Assert.Equal([EXPECTED_UPSTREAM_PATH], dataEndpoints);
Assert.True(response.Headers.CacheControl?.NoStore);
Assert.True(response.Headers.CacheControl?.Private);
Assert.Contains("Cookie", response.Headers.Vary);
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
/// <summary>
/// Builds the path of the Web route for <paramref name="request"/>.
/// </summary>
/// <param name="request">The request whose filters are forwarded.</param>
/// <returns>The path of the Web route, including the query string built from the request values.</returns>
private static string BuildRequestPath(GetMostConsumedRequest request)
{
List<string> parameters = [];
if (!string.IsNullOrWhiteSpace(request.UserId))
parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
if (!string.IsNullOrWhiteSpace(request.LibraryId))
parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
return parameters.Count == 0
? WEB_ROUTE
: $"{WEB_ROUTE}?{string.Join("&", parameters)}";
}
}
@@ -0,0 +1,128 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
/// <summary>
/// Contains security tests for the <see cref="GetRecentlyConsumedEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetRecentlyConsumedEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
{
private const string WEB_ROUTE = "/en-us/library/statistics/api-get-recently-consumed";
private readonly LuminaWebFactory _apiFactory;
private readonly GetRecentlyConsumedRequestFixture _getRecentlyConsumedRequestFixture = new();
private readonly ConsumedItemDtoFixture _consumedItemDtoFixture = new();
private readonly PaginatedDtoFixture<ConsumedItemDto> _paginatedDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetRecentlyConsumedEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public GetRecentlyConsumedEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetRecentlyConsumed_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, WEB_ROUTE);
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
HttpResponseMessage response = await client.SendAsync(getRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Fact]
public async Task GetRecentlyConsumed_WithCraftedUserAndLibraryIds_ShouldEscapeTheValuesAndKeepTheDocumentedUpstreamPath()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
const string CRAFTED_USER_ID = "user/../admin?x=1&y=2";
const string CRAFTED_LIBRARY_ID = "lib?x=1&y=2";
const string EXPECTED_UPSTREAM_PATH = "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-history/recently-consumed?libraryId=lib%3Fx%3D1%26y%3D2&currentPage=1&perPage=10";
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
userId: CRAFTED_USER_ID,
libraryId: CRAFTED_LIBRARY_ID,
includeMediaKind: false,
includeFromUtc: false,
includeToUtc: false,
includeCurrentPage: false,
includePerPage: false);
PaginatedDto<ConsumedItemDto> expectedPage = _paginatedDtoFixture.Create(data: [_consumedItemDtoFixture.Create()]);
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedPage);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
string[] dataEndpoints = [.. _apiFactory.ApiClientStub.GetEndpointsCalled.Where(endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal))];
Assert.Equal([EXPECTED_UPSTREAM_PATH], dataEndpoints);
Assert.True(response.Headers.CacheControl?.NoStore);
Assert.True(response.Headers.CacheControl?.Private);
Assert.Contains("Cookie", response.Headers.Vary);
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
/// <summary>
/// Builds the path of the Web route for <paramref name="request"/>.
/// </summary>
/// <param name="request">The request whose filters are forwarded.</param>
/// <returns>The path of the Web route, including the query string built from the request values.</returns>
private static string BuildRequestPath(GetRecentlyConsumedRequest request)
{
List<string> parameters = [];
if (!string.IsNullOrWhiteSpace(request.UserId))
parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
if (!string.IsNullOrWhiteSpace(request.LibraryId))
parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
return parameters.Count == 0
? WEB_ROUTE
: $"{WEB_ROUTE}?{string.Join("&", parameters)}";
}
}
@@ -0,0 +1,123 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetTagConsumption;
using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.GetTagConsumption;
/// <summary>
/// Contains security tests for the <see cref="GetTagConsumptionEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTagConsumptionEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
{
private const string WEB_ROUTE = "/en-us/library/statistics/api-get-tag-consumption";
private readonly LuminaWebFactory _apiFactory;
private readonly GetTagConsumptionRequestFixture _getTagConsumptionRequestFixture = new();
private readonly TagConsumptionDtoFixture _tagConsumptionDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetTagConsumptionEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public GetTagConsumptionEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetTagConsumption_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, WEB_ROUTE);
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
HttpResponseMessage response = await client.SendAsync(getRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Fact]
public async Task GetTagConsumption_WithCraftedUserAndLibraryIds_ShouldEscapeTheValuesAndKeepTheDocumentedUpstreamPath()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
const string CRAFTED_USER_ID = "user/../admin?x=1&y=2";
const string CRAFTED_LIBRARY_ID = "lib?x=1&y=2";
const string EXPECTED_UPSTREAM_PATH = "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-statistics/tags?libraryId=lib%3Fx%3D1%26y%3D2";
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(
userId: CRAFTED_USER_ID,
libraryId: CRAFTED_LIBRARY_ID,
includeMediaKind: false,
includeFromUtc: false,
includeToUtc: false);
TagConsumptionDto[] expectedTags = [_tagConsumptionDtoFixture.Create()];
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedTags);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
string[] dataEndpoints = [.. _apiFactory.ApiClientStub.GetEndpointsCalled.Where(endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal))];
Assert.Equal([EXPECTED_UPSTREAM_PATH], dataEndpoints);
Assert.True(response.Headers.CacheControl?.NoStore);
Assert.True(response.Headers.CacheControl?.Private);
Assert.Contains("Cookie", response.Headers.Vary);
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
/// <summary>
/// Builds the path of the Web route for <paramref name="request"/>.
/// </summary>
/// <param name="request">The request whose filters are forwarded.</param>
/// <returns>The path of the Web route, including the query string built from the request values.</returns>
private static string BuildRequestPath(GetTagConsumptionRequest request)
{
List<string> parameters = [];
if (!string.IsNullOrWhiteSpace(request.UserId))
parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
if (!string.IsNullOrWhiteSpace(request.LibraryId))
parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
return parameters.Count == 0
? WEB_ROUTE
: $"{WEB_ROUTE}?{string.Join("&", parameters)}";
}
}
@@ -0,0 +1,115 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.UsersManagement;
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetUsers;
using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement;
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.GetUsers;
/// <summary>
/// Contains security tests for the <see cref="GetUsersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUsersEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
{
private const string WEB_ROUTE = "/en-us/library/statistics/api-get-users";
private const string EXPECTED_UPSTREAM_PATH = "auth/users";
private readonly LuminaWebFactory _apiFactory;
private readonly UserDtoFixture _userDtoFixture = new();
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetUsersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public GetUsersEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetUsers_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, WEB_ROUTE);
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
HttpResponseMessage response = await client.SendAsync(getRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Fact]
public async Task GetUsers_WhenCalledByNonAdminUser_ShouldRedirectToAccessDeniedAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Contains("access-denied", response.Headers.Location!.ToString());
Assert.DoesNotContain(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Fact]
public async Task GetUsers_WhenCalledByAdminUser_ShouldReturnUsersWithoutLeakingCredentials()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
UserDto[] expectedUsers = [_userDtoFixture.Create(username: "alice")];
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedUsers);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Equal(1, json.RootElement.GetProperty("data").GetArrayLength());
Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
Assert.True(response.Headers.CacheControl?.NoStore);
Assert.True(response.Headers.CacheControl?.Private);
Assert.Contains("Cookie", response.Headers.Vary);
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
}
@@ -0,0 +1,103 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.Index;
using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.Index;
/// <summary>
/// Contains security tests for the <see cref="StatisticsIndexViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StatisticsIndexViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
{
private const string WEB_ROUTE = "/en-us/library/statistics";
private readonly LuminaWebFactory _apiFactory;
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="StatisticsIndexViewEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public StatisticsIndexViewEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task StatisticsIndexView_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
// Act
HttpResponseMessage response = await client.GetAsync(WEB_ROUTE);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Fact]
public async Task StatisticsIndexView_WhenCalledByRegularUser_ShouldHideAdministrativeDataAndNotLeakSecrets()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.DoesNotContain("statistics-user-selector", content, StringComparison.Ordinal);
Assert.DoesNotContain("api-get-users", content, StringComparison.Ordinal);
Assert.DoesNotContain("auth/users", _apiFactory.ApiClientStub.GetEndpointsCalled);
Assert.True(response.Headers.CacheControl?.NoStore);
Assert.Contains("Cookie", response.Headers.Vary);
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
}
[Fact]
public async Task StatisticsIndexView_WhenCalledByAdminUser_ShouldRenderAdministrativeUserSelector()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("statistics-user-selector", content, StringComparison.Ordinal);
Assert.Contains("api-get-users", content, StringComparison.Ordinal);
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
}