mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 09:01:10 +00:00
Implements tests for commit 525ac1348d
Covers the favorites feature and the playlist and favorite pagination changes with unit, integration and security tests, and fixtures for the new request, response, DTO and entity types. Also fixes the issues found while covering the commit: declares FavoriteMediaKind.None as the default value and rejects it in every favorite operation; queues the favorite added domain event only after the persisted favorite is read back; and preserves the private, no-store cache header on view pages after the antiforgery and session middlewares overwrite it.
This commit is contained in:
1 parent
468f1846f1
commit
394f6b510c
135 files changed
+19167
-13
No files matched your search
+405
@@ -0,0 +1,405 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
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.Favorites;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.AddFavorite;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Favorites.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="AddFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteEndpointTests : 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/favorites";
|
||||
|
||||
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 UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededLibraryIds = [];
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public AddFavoriteEndpointTests(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 AddFavorite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
object body = new { mediaKind = "MusicTrack", mediaItemId = Guid.NewGuid() };
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, body);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, PATH);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Favorites")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task AddFavorite_WithInjectionInMediaKind_ShouldRejectWithoutLeakingOrChangingData(string maliciousMediaKind)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = maliciousMediaKind, mediaItemId = Guid.NewGuid() });
|
||||
|
||||
// Assert
|
||||
string content = await AssertRejectedAsync(response);
|
||||
Assert.DoesNotContain(maliciousMediaKind, content, StringComparison.Ordinal);
|
||||
await AssertFavoriteCountAsync(callerId, 0);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Favorites")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task AddFavorite_WithInjectionInMediaItemId_ShouldRejectWithoutLeakingOrChangingData(string maliciousMediaItemId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = maliciousMediaItemId });
|
||||
|
||||
// Assert
|
||||
string content = await AssertRejectedAsync(response);
|
||||
Assert.DoesNotContain(maliciousMediaItemId, content, StringComparison.Ordinal);
|
||||
await AssertFavoriteCountAsync(callerId, 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenTheMediaItemBelongsToAnotherUsersLibrary_ShouldReturnTheSameNotFoundAsAMissingItem()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
Guid otherTrackId = await SeedTrackAsync(otherUserId);
|
||||
Guid missingTrackId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage existingItemResponse = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = otherTrackId });
|
||||
HttpResponseMessage missingItemResponse = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = missingTrackId });
|
||||
|
||||
// Assert
|
||||
// Both answers are indistinguishable, so the route cannot be used as an existence oracle for another user's library.
|
||||
Assert.Equal(HttpStatusCode.NotFound, existingItemResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.NotFound, missingItemResponse.StatusCode);
|
||||
string existingItemContent = await existingItemResponse.Content.ReadAsStringAsync();
|
||||
string missingItemContent = await missingItemResponse.Content.ReadAsStringAsync();
|
||||
Assert.Equal(GetProblemDetail(existingItemContent), GetProblemDetail(missingItemContent));
|
||||
Assert.Equal("TrackNotFound", GetProblemDetail(existingItemContent));
|
||||
await AssertFavoriteCountAsync(callerId, 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenSuccessful_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid trackId = await SeedTrackAsync(callerId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = "MusicTrack", mediaItemId = trackId });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
AssertNoDatabaseOnlyFields(content);
|
||||
FavoriteResponse? favorite = JsonSerializer.Deserialize<FavoriteResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(favorite);
|
||||
Assert.Equal(trackId, favorite!.MediaItemId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenTheMediaKindIsNotSupported_ShouldRejectWithNonCacheableValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await CreateAuthenticatedUserAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, new { mediaKind = "Video", mediaItemId = Guid.NewGuid() });
|
||||
|
||||
// Assert
|
||||
string content = await AssertValidationProblemAsync(response, PATH, "FavoriteMediaKindIsNotSupported");
|
||||
AssertNonCacheable(response);
|
||||
Assert.DoesNotContain(username, content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync()
|
||||
{
|
||||
(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()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/> with one track, and returns the Id of that track.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the seeded library.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(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: $"Library-{Guid.NewGuid():N}", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Security Artist", includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: "Security Album",
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Tracks.Add(_trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
title: "Security Track",
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts how many favorites the user identified by <paramref name="userId"/> owns.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose favorites are counted.</param>
|
||||
/// <param name="expectedCount">The expected number of favorites.</param>
|
||||
private async Task AssertFavoriteCountAsync(Guid userId, int expectedCount)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Equal(expectedCount, await dbContext.Favorites.CountAsync(favorite => favorite.UserId == userId));
|
||||
}
|
||||
|
||||
/// <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 request was rejected without succeeding, and returns the raw response body.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private static async Task<string> AssertRejectedAsync(HttpResponseMessage response)
|
||||
{
|
||||
Assert.False(response.IsSuccessStatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.False(string.IsNullOrWhiteSpace(content));
|
||||
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>
|
||||
/// Reads the detail of a problem details body.
|
||||
/// </summary>
|
||||
/// <param name="content">The problem details body to read.</param>
|
||||
/// <returns>The problem detail.</returns>
|
||||
private static string? GetProblemDetail(string content)
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
return problemDetails!["detail"].GetString();
|
||||
}
|
||||
|
||||
/// <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 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 response body exposes only the fields of the documented favorite 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("createdBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the catalogue rows seeded by the test and the test users.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<Guid> libraryIds = [.. _seededLibraryIds];
|
||||
dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => libraryIds.Contains(track.LibraryId)));
|
||||
dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)));
|
||||
dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => libraryIds.Contains(artist.LibraryId)));
|
||||
dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => libraryIds.Contains(library.Id)));
|
||||
dbContext.SaveChanges();
|
||||
}
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+344
@@ -0,0 +1,344 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetFavoriteStatusEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoriteStatusEndpointTests : 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/favorites/status";
|
||||
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoriteStatusEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetFavoriteStatusEndpointTests(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 GetFavoriteStatus_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&mediaItemIds={Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, PATH);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Favorites")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task GetFavoriteStatus_WithInjectionInMediaKind_ShouldRejectWithoutLeakingOrChangingData(string maliciousMediaKind)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid favoritedItemId = await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack);
|
||||
string url = $"{PATH}?mediaKind={Uri.EscapeDataString(maliciousMediaKind)}&mediaItemIds={favoritedItemId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertRejectedAsync(response);
|
||||
Assert.DoesNotContain(maliciousMediaKind, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(favoritedItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
await AssertFavoriteCountAsync(callerId, 1);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Favorites")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task GetFavoriteStatus_WithInjectionInMediaItemIds_ShouldRejectWithoutLeakingOrChangingData(string maliciousMediaItemId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid favoritedItemId = await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack);
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&mediaItemIds={favoritedItemId}&mediaItemIds={Uri.EscapeDataString(maliciousMediaItemId)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertRejectedAsync(response);
|
||||
Assert.DoesNotContain(maliciousMediaItemId, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(favoritedItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
await AssertFavoriteCountAsync(callerId, 1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenSuccessful_ShouldReturnOnlyTheCallersFavoritesWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, string username) = await CreateAuthenticatedUserAsync();
|
||||
Guid callerFavoritedItemId = await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack);
|
||||
(Guid otherUserId, string otherUsername) = await SeedOtherUserAsync();
|
||||
Guid otherFavoritedItemId = await SeedFavoriteAsync(otherUserId, FavoriteMediaKind.MusicTrack);
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&mediaItemIds={callerFavoritedItemId}&mediaItemIds={otherFavoritedItemId}";
|
||||
|
||||
// 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(username, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(otherUsername, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(otherFavoritedItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
FavoriteStatusResponse? status = JsonSerializer.Deserialize<FavoriteStatusResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(status);
|
||||
Guid favoritedId = Assert.Single(status!.FavoritedMediaItemIds);
|
||||
Assert.Equal(callerFavoritedItemId, favoritedId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenTooManyIdsAreRequested_ShouldRejectWithNonCacheableValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid favoritedItemId = await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack);
|
||||
List<Guid> requestedIds = [favoritedItemId, .. Enumerable.Range(0, 100).Select(_ => Guid.NewGuid())];
|
||||
string url = $"{PATH}?mediaKind=MusicTrack&{string.Join("&", requestedIds.Select(requestedId => $"mediaItemIds={requestedId}"))}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertValidationProblemAsync(response, PATH, "FavoriteMediaItemIdsExceedMaximumCount");
|
||||
AssertNonCacheable(response);
|
||||
Assert.DoesNotContain(favoritedItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
await AssertFavoriteCountAsync(callerId, 1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync()
|
||||
{
|
||||
(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()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a favorite of <paramref name="userId"/> and returns the Id of the favorited media item.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the favorite.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <returns>The Id of the favorited media item.</returns>
|
||||
private async Task<Guid> SeedFavoriteAsync(Guid userId, FavoriteMediaKind mediaKind)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
dbContext.Favorites.Add(_favoriteEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
createdBy: userId,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return mediaItemId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts how many favorites the user identified by <paramref name="userId"/> owns.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose favorites are counted.</param>
|
||||
/// <param name="expectedCount">The expected number of favorites.</param>
|
||||
private async Task AssertFavoriteCountAsync(Guid userId, int expectedCount)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Equal(expectedCount, await dbContext.Favorites.CountAsync(favorite => favorite.UserId == userId));
|
||||
}
|
||||
|
||||
/// <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 request was rejected without succeeding, and returns the raw response body.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private static async Task<string> AssertRejectedAsync(HttpResponseMessage response)
|
||||
{
|
||||
Assert.False(response.IsSuccessStatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.False(string.IsNullOrWhiteSpace(content));
|
||||
AssertNoSensitiveData(content);
|
||||
Assert.DoesNotContain("\"favoritedMediaItemIds\"", content, StringComparison.Ordinal);
|
||||
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 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 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 response body exposes only the fields of the documented favorite status 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("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);
|
||||
}
|
||||
}
|
||||
+318
@@ -0,0 +1,318 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.GetFavorites;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Favorites.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetFavoritesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoritesEndpointTests : 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/favorites";
|
||||
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoritesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetFavoritesEndpointTests(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 GetFavorites_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(PATH);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, PATH);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Favorites")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task GetFavorites_WithInjectionInMediaKind_ShouldRejectWithoutLeakingOrChangingData(string maliciousMediaKind)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid favoritedItemId = await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack);
|
||||
string url = $"{PATH}?mediaKind={Uri.EscapeDataString(maliciousMediaKind)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertRejectedAsync(response);
|
||||
Assert.DoesNotContain(maliciousMediaKind, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(favoritedItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
await AssertFavoriteCountAsync(callerId, 1);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Favorites")] // stacked statement injection
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task GetFavorites_WithInjectionInCurrentPage_ShouldRejectWithoutLeakingOrChangingData(string maliciousCurrentPage)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid favoritedItemId = await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack);
|
||||
string url = $"{PATH}?currentPage={Uri.EscapeDataString(maliciousCurrentPage)}&perPage=10";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertRejectedAsync(response);
|
||||
Assert.DoesNotContain(maliciousCurrentPage, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(favoritedItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
await AssertFavoriteCountAsync(callerId, 1);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Favorites")] // stacked statement injection
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task GetFavorites_WithInjectionInPerPage_ShouldRejectWithoutLeakingOrChangingData(string maliciousPerPage)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid favoritedItemId = await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack);
|
||||
string url = $"{PATH}?currentPage=1&perPage={Uri.EscapeDataString(maliciousPerPage)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertRejectedAsync(response);
|
||||
Assert.DoesNotContain(maliciousPerPage, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(favoritedItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
await AssertFavoriteCountAsync(callerId, 1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenSuccessful_ShouldReturnOnlyTheCallersFavoritesWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, string username) = await CreateAuthenticatedUserAsync();
|
||||
Guid favoritedItemId = await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack);
|
||||
(Guid otherUserId, string otherUsername) = await SeedOtherUserAsync();
|
||||
Guid otherFavoritedItemId = await SeedFavoriteAsync(otherUserId, FavoriteMediaKind.MusicTrack);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(PATH);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
AssertNoDatabaseOnlyFields(content);
|
||||
Assert.DoesNotContain(username, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(otherUsername, content, StringComparison.Ordinal);
|
||||
Assert.Contains(favoritedItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(otherFavoritedItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(otherUserId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
PaginatedResponse<FavoriteItemResponse>? favorites = JsonSerializer.Deserialize<PaginatedResponse<FavoriteItemResponse>>(content, _jsonOptions);
|
||||
Assert.NotNull(favorites);
|
||||
FavoriteItemResponse favorite = Assert.Single(favorites!.Data);
|
||||
Assert.Equal(favoritedItemId, favorite.MediaItemId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync()
|
||||
{
|
||||
(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()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a favorite of <paramref name="userId"/> and returns the Id of the favorited media item.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the favorite.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <returns>The Id of the favorited media item.</returns>
|
||||
private async Task<Guid> SeedFavoriteAsync(Guid userId, FavoriteMediaKind mediaKind)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
dbContext.Favorites.Add(_favoriteEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
createdBy: userId,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return mediaItemId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts how many favorites the user identified by <paramref name="userId"/> owns.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose favorites are counted.</param>
|
||||
/// <param name="expectedCount">The expected number of favorites.</param>
|
||||
private async Task AssertFavoriteCountAsync(Guid userId, int expectedCount)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Equal(expectedCount, await dbContext.Favorites.CountAsync(favorite => favorite.UserId == userId));
|
||||
}
|
||||
|
||||
/// <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 request was rejected without succeeding, and returns the raw response body.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private static async Task<string> AssertRejectedAsync(HttpResponseMessage response)
|
||||
{
|
||||
Assert.False(response.IsSuccessStatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.False(string.IsNullOrWhiteSpace(content));
|
||||
AssertNoSensitiveData(content);
|
||||
Assert.DoesNotContain("\"favoritedMediaItemIds\"", 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 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 response body exposes only the fields of the documented favorites 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("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);
|
||||
}
|
||||
}
|
||||
+306
@@ -0,0 +1,306 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="RemoveFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemoveFavoriteEndpointTests : 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/favorites";
|
||||
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly FavoriteEntityFixture _favoriteEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public RemoveFavoriteEndpointTests(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 RemoveFavorite_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"{PATH}/MusicTrack/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Favorites")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task RemoveFavorite_WithInjectionInMediaKind_ShouldRejectWithoutLeakingOrChangingData(string maliciousMediaKind)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
string url = $"{PATH}/{Uri.EscapeDataString(maliciousMediaKind)}/{mediaItemId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertValidationProblemAsync(response, $"{PATH}/", "FavoriteMediaKindIsInvalid");
|
||||
AssertNonCacheable(response);
|
||||
Assert.DoesNotContain(maliciousMediaKind, content, StringComparison.Ordinal);
|
||||
await AssertFavoriteExistsAsync(callerId, mediaItemId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Favorites")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task RemoveFavorite_WithInjectionInMediaItemId_ShouldRejectWithoutLeakingOrChangingData(string maliciousMediaItemId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
string url = $"{PATH}/MusicTrack/{Uri.EscapeDataString(maliciousMediaItemId)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertValidationProblemAsync(response, $"{PATH}/MusicTrack/", "FavoriteMediaItemIdCannotBeEmpty");
|
||||
AssertNonCacheable(response);
|
||||
Assert.DoesNotContain(maliciousMediaItemId, content, StringComparison.Ordinal);
|
||||
await AssertFavoriteExistsAsync(callerId, mediaItemId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenAnotherUserFavoritedTheSameItem_ShouldRemoveOnlyTheCallersRow()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
await SeedFavoriteAsync(otherUserId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"{PATH}/MusicTrack/{mediaItemId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == callerId));
|
||||
Assert.True(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == otherUserId && favorite.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenSuccessful_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, string username) = await CreateAuthenticatedUserAsync();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
await SeedFavoriteAsync(callerId, FavoriteMediaKind.MusicTrack, mediaItemId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"{PATH}/MusicTrack/{mediaItemId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
Assert.DoesNotContain(username, content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync()
|
||||
{
|
||||
(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()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a favorite of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the favorite.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the favorited media item.</param>
|
||||
private async Task SeedFavoriteAsync(Guid userId, FavoriteMediaKind mediaKind, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Favorites.Add(_favoriteEntityFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
createdBy: userId,
|
||||
includeUpdatedOnUtc: false,
|
||||
includeUpdatedBy: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the favorite of <paramref name="userId"/> on <paramref name="mediaItemId"/> still exists.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the favorite.</param>
|
||||
/// <param name="mediaItemId">The Id of the favorited media item.</param>
|
||||
private async Task AssertFavoriteExistsAsync(Guid userId, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.True(await dbContext.Favorites.AnyAsync(favorite => favorite.UserId == userId && favorite.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
/// <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);
|
||||
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="expectedInstancePrefix">The expected prefix of the 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 expectedInstancePrefix, 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);
|
||||
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());
|
||||
// The instance is the routed path, which normalizes the escaping of some characters, so only its prefix is asserted.
|
||||
Assert.StartsWith(expectedInstancePrefix, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
|
||||
AssertNoSensitiveData(content);
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
+435
@@ -0,0 +1,435 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Playlists.GetPlaylist;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Playlists.GetPlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetPlaylistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaylistEndpointTests : 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/playlists";
|
||||
|
||||
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 PlaylistEntityFixture _playlistEntityFixture = new();
|
||||
private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<Guid> _seededLibraryIds = [];
|
||||
private readonly List<Guid> _seededPlaylistIds = [];
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaylistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetPlaylistEndpointTests(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 GetPlaylist_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"{PATH}/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE Playlists--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM Playlists")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("Ünïcödé-💥")] // non ascii input
|
||||
public async Task GetPlaylist_WithInjectionInPlaylistId_ShouldRejectWithoutLeakingOrChangingData(string maliciousPlaylistId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync();
|
||||
Guid playlistId = await SeedPlaylistAsync(callerId, "Caller playlist", trackCount: 1);
|
||||
string url = $"{PATH}/{Uri.EscapeDataString(maliciousPlaylistId)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertValidationProblemAsync(response, $"{PATH}/", "PlaylistIdCannotBeEmpty");
|
||||
AssertNonCacheable(response);
|
||||
Assert.DoesNotContain(maliciousPlaylistId, content, StringComparison.Ordinal);
|
||||
await AssertPlaylistStillExistsAsync(playlistId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenThePlaylistBelongsToAnotherUser_ShouldReturnTheSameNotFoundAsAMissingPlaylist()
|
||||
{
|
||||
// Arrange
|
||||
(_, _) = await CreateAuthenticatedUserAsync();
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Someone else's playlist", trackCount: 1);
|
||||
Guid missingPlaylistId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage existingPlaylistResponse = await _client.GetAsync($"{PATH}/{otherPlaylistId}");
|
||||
HttpResponseMessage missingPlaylistResponse = await _client.GetAsync($"{PATH}/{missingPlaylistId}");
|
||||
|
||||
// Assert
|
||||
// Both answers are indistinguishable, so the route cannot be used as an existence oracle for another user's playlist.
|
||||
Assert.Equal(HttpStatusCode.NotFound, existingPlaylistResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.NotFound, missingPlaylistResponse.StatusCode);
|
||||
string existingPlaylistContent = await existingPlaylistResponse.Content.ReadAsStringAsync();
|
||||
string missingPlaylistContent = await missingPlaylistResponse.Content.ReadAsStringAsync();
|
||||
Assert.Equal(GetProblemDetail(existingPlaylistContent), GetProblemDetail(missingPlaylistContent));
|
||||
Assert.Equal("PlaylistNotFound", GetProblemDetail(existingPlaylistContent));
|
||||
Assert.DoesNotContain("Someone else's playlist", existingPlaylistContent, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenSuccessful_ShouldReturnOnlyTheCallersPlaylistWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, string username) = await CreateAuthenticatedUserAsync();
|
||||
Guid playlistId = await SeedPlaylistAsync(callerId, "Caller playlist", trackCount: 2);
|
||||
(Guid otherUserId, string otherUsername) = await SeedOtherUserAsync();
|
||||
await SeedPlaylistAsync(otherUserId, "Other playlist", trackCount: 1);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"{PATH}/{playlistId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
AssertNoDatabaseOnlyFields(content);
|
||||
Assert.DoesNotContain(username, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(otherUsername, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Other playlist", content, StringComparison.Ordinal);
|
||||
|
||||
PlaylistResponse? playlist = JsonSerializer.Deserialize<PlaylistResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(playlist);
|
||||
Assert.Equal(playlistId, playlist!.Id);
|
||||
Assert.Equal("Caller playlist", playlist.Name);
|
||||
Assert.Equal(2, playlist.Entries.Data.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenThePlaylistDoesNotExist_ShouldRejectWithNonCacheableNotFound()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync();
|
||||
string url = $"{PATH}/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertNotFoundAsync(response, url, "PlaylistNotFound");
|
||||
AssertNonCacheable(response);
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync()
|
||||
{
|
||||
(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()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a playlist of <paramref name="userId"/> with the requested number of entries, each one referencing its own seeded track.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the playlist.</param>
|
||||
/// <param name="name">The name of the playlist.</param>
|
||||
/// <param name="trackCount">The number of entries to seed.</param>
|
||||
/// <returns>The Id of the seeded playlist.</returns>
|
||||
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int trackCount)
|
||||
{
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId, userId: userId, title: $"Library-{Guid.NewGuid():N}", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededLibraryIds.Add(libraryId);
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Playlist Artist", includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: "Playlist Album",
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
dbContext.Playlists.Add(_playlistEntityFixture.Create(
|
||||
id: playlistId,
|
||||
userId: userId,
|
||||
name: name,
|
||||
type: PlaylistType.Music,
|
||||
entryCount: trackCount,
|
||||
version: 0,
|
||||
createdBy: userId));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededPlaylistIds.Add(playlistId);
|
||||
for (int index = 0; index < trackCount; index++)
|
||||
{
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Tracks.Add(_trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
title: $"Playlist Track {index}",
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
dbContext.PlaylistEntries.Add(_playlistEntryEntityFixture.Create(
|
||||
playlistId: playlistId,
|
||||
mediaItemId: trackId,
|
||||
mediaItemType: PlaylistMediaItemType.MusicTrack,
|
||||
position: index * 1_000_000_000L));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
return playlistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the playlist identified by <paramref name="playlistId"/> still exists.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The Id of the playlist to look up.</param>
|
||||
private async Task AssertPlaylistStillExistsAsync(Guid playlistId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.True(await dbContext.Playlists.AnyAsync(playlist => playlist.Id == playlistId));
|
||||
}
|
||||
|
||||
/// <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);
|
||||
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="expectedInstancePrefix">The expected prefix of the 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 expectedInstancePrefix, 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);
|
||||
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());
|
||||
// The instance is the routed path, which normalizes the escaping of some characters, so only its prefix is asserted.
|
||||
Assert.StartsWith(expectedInstancePrefix, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
|
||||
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 not found 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="expectedDetail">The expected problem detail.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertNotFoundAsync(HttpResponseMessage response, string expectedInstance, string expectedDetail)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.NotFound, 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);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
AssertNoSensitiveData(content);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the detail of a problem details body.
|
||||
/// </summary>
|
||||
/// <param name="content">The problem details body to read.</param>
|
||||
/// <returns>The problem detail.</returns>
|
||||
private static string? GetProblemDetail(string content)
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
return problemDetails!["detail"].GetString();
|
||||
}
|
||||
|
||||
/// <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 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 response body exposes only the fields of the documented playlist response contract.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoDatabaseOnlyFields(string content)
|
||||
{
|
||||
// The creation and update times are part of the documented playlist contract, so they are not asserted absent here.
|
||||
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the catalogue rows and playlists seeded by the test and the test users.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
using (IServiceScope scope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<Guid> libraryIds = [.. _seededLibraryIds];
|
||||
List<Guid> playlistIds = [.. _seededPlaylistIds];
|
||||
dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId)));
|
||||
dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id)));
|
||||
dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => libraryIds.Contains(track.LibraryId)));
|
||||
dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId)));
|
||||
dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => libraryIds.Contains(artist.LibraryId)));
|
||||
dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => libraryIds.Contains(library.Id)));
|
||||
dbContext.SaveChanges();
|
||||
}
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.AddFavorite;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
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;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Favorites.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="AddFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites/api-add-favorite";
|
||||
private const string UPSTREAM_ENDPOINT = "users/me/favorites";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly FavoriteDtoFixture _favoriteDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public AddFavoriteEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(nameof(FavoriteMediaKind.MusicTrack), Guid.NewGuid().ToString(), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(addRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(GetAddRequests());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(nameof(FavoriteMediaKind.MusicTrack), Guid.NewGuid().ToString(), antiforgeryToken: null);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetAddRequests());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(nameof(FavoriteMediaKind.MusicTrack), Guid.NewGuid().ToString(), "invalid-token");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetAddRequests());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // script injection
|
||||
public async Task AddFavorite_WithInjectionPayloadInMediaKind_ShouldRejectItAndNotCallTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(payload, Guid.NewGuid().ToString(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The media kind is bound to an enum, so the crafted value is rejected before the endpoint executes and can never reach the API.
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
Assert.Empty(GetAddRequests());
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // script injection
|
||||
public async Task AddFavorite_WithInjectionPayloadInMediaItemId_ShouldRejectItAndNotCallTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(nameof(FavoriteMediaKind.MusicTrack), payload, webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The media item Id is bound to a Guid, so the crafted value is rejected before the endpoint executes and can never reach the API.
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
Assert.Empty(GetAddRequests());
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddFavorite_WhenCalledByAuthenticatedUserWithValidToken_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
FavoriteDto expectedFavorite = _favoriteDtoFixture.Create(mediaKind: FavoriteMediaKind.MusicTrack, mediaItemId: mediaItemId);
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(UPSTREAM_ENDPOINT, expectedFavorite);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(nameof(FavoriteMediaKind.MusicTrack), mediaItemId.ToString(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Single(GetAddRequests());
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the add favorite requests that were sent upstream, excluding the login request performed to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream add favorite requests that were sent.</returns>
|
||||
private List<(string Endpoint, object? Data)> GetAddRequests()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.PostRequests
|
||||
.Where(postRequest => postRequest.Endpoint == UPSTREAM_ENDPOINT)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the add favorite request for the specified values.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">The value of the media kind body property.</param>
|
||||
/// <param name="mediaItemId">The value of the media item identifier body property.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
|
||||
/// <returns>The configured add favorite request.</returns>
|
||||
private static HttpRequestMessage CreateAddRequest(string mediaKind, string mediaItemId, string? antiforgeryToken)
|
||||
{
|
||||
string payload = JsonSerializer.Serialize(new { mediaKind, mediaItemId });
|
||||
HttpRequestMessage addRequest = new(HttpMethod.Post, WEB_ROUTE)
|
||||
{
|
||||
Content = new StringContent(payload, Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
addRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
if (antiforgeryToken is not null)
|
||||
addRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return addRequest;
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetFavoriteStatusEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoriteStatusEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites/api-get-favorite-status";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly FavoriteStatusDtoFixture _favoriteStatusDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoriteStatusEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetFavoriteStatusEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"{WEB_ROUTE}?mediaKind=MusicTrack&mediaItemIds={Guid.NewGuid()}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(GetFavoriteStatusEndpointCalls());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // script injection
|
||||
public async Task GetFavoriteStatus_WithInjectionPayloadInMediaKind_ShouldRejectItAndNotCallTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"{WEB_ROUTE}?mediaKind={Uri.EscapeDataString(payload)}&mediaItemIds={Guid.NewGuid()}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The media kind is bound to an enum, so a crafted value is rejected before the endpoint executes and can never alter the upstream URL.
|
||||
// The model binding failure is returned through the application's JSON error envelope, so the test asserts the rejection and that the
|
||||
// value never reaches the API.
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Empty(GetFavoriteStatusEndpointCalls());
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // script injection
|
||||
public async Task GetFavoriteStatus_WithInjectionPayloadInMediaItemIds_ShouldRejectItAndNotCallTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"{WEB_ROUTE}?mediaKind=MusicTrack&mediaItemIds={Uri.EscapeDataString(payload)}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The media item Ids are bound to Guids, so a crafted value is rejected before the endpoint executes and can never alter the upstream URL.
|
||||
// The model binding failure is returned through the application's JSON error envelope, so the test asserts the rejection and that the
|
||||
// value never reaches the API.
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Empty(GetFavoriteStatusEndpointCalls());
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavoriteStatus_WhenCalledByAuthenticatedUser_ShouldReturnPrivateNoStoreResponseWithoutLeakingInternals()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
List<Guid> mediaItemIds = [Guid.NewGuid(), Guid.NewGuid()];
|
||||
string expectedUpstreamEndpoint = $"users/me/favorites/status?mediaKind=MusicTrack&mediaItemIds={mediaItemIds[0]}&mediaItemIds={mediaItemIds[1]}";
|
||||
FavoriteStatusDto expectedStatus = _favoriteStatusDtoFixture.Create(favoritedMediaItemIds: [mediaItemIds[0]]);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedUpstreamEndpoint, expectedStatus);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(
|
||||
$"{WEB_ROUTE}?mediaKind=MusicTrack&mediaItemIds={mediaItemIds[0]}&mediaItemIds={mediaItemIds[1]}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
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);
|
||||
Assert.Equal([expectedUpstreamEndpoint], GetFavoriteStatusEndpointCalls());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the favorite status endpoints that were called upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream favorite status endpoints that were called.</returns>
|
||||
private List<string> GetFavoriteStatusEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.GetEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/favorites/status", 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);
|
||||
}
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavorites;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Favorites;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Favorites.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetFavoritesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoritesEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites/api-get-favorites";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PaginatedDtoFixture<FavoriteItemDto> _paginatedDtoFixture = new();
|
||||
private readonly FavoriteItemDtoFixture _favoriteItemDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoritesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetFavoritesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_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(GetFavoritesEndpointCalls());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // script injection
|
||||
public async Task GetFavorites_WithInjectionPayloadInMediaKind_ShouldRejectItAndNotCallTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"{WEB_ROUTE}?mediaKind={Uri.EscapeDataString(payload)}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The media kind is bound to an enum, so a crafted value is rejected before the endpoint executes and can never alter the upstream URL.
|
||||
// The model binding failure is returned through the application's JSON error envelope, so the test asserts the rejection and that the
|
||||
// value never reaches the API.
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Empty(GetFavoritesEndpointCalls());
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("currentPage", "' OR '1'='1")] // basic SQL injection in the page number
|
||||
[InlineData("currentPage", "1;DROP TABLE Favorites")] // destructive injection in the page number
|
||||
[InlineData("perPage", "' OR '1'='1")] // basic SQL injection in the page size
|
||||
[InlineData("perPage", "../../admin")] // path traversal in the page size
|
||||
public async Task GetFavorites_WithInjectionPayloadInPagination_ShouldRejectItAndNotCallTheApi(string parameterName, string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"{WEB_ROUTE}?{parameterName}={Uri.EscapeDataString(payload)}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The page bounds are bound to integers and rebuilt from the typed values, so a crafted value is rejected before the endpoint executes.
|
||||
// The model binding failure is returned through the application's JSON error envelope, so the test asserts the rejection and that the
|
||||
// value never reaches the API.
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Empty(GetFavoritesEndpointCalls());
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetFavorites_WhenCalledByAuthenticatedUser_ShouldReturnPrivateNoStoreResponseWithoutLeakingInternals()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
FavoriteItemDto expectedItem = _favoriteItemDtoFixture.Create(mediaKind: FavoriteMediaKind.MusicTrack);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(
|
||||
"users/me/favorites?currentPage=1&perPage=200",
|
||||
_paginatedDtoFixture.Create(data: [expectedItem], currentPage: 1, perPage: 200, count: 1, numberOfPages: 1));
|
||||
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.True(response.Headers.CacheControl?.Private);
|
||||
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);
|
||||
Assert.Equal(["users/me/favorites?currentPage=1&perPage=200"], GetFavoritesEndpointCalls());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the favorites endpoints that were called upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream favorites endpoints that were called.</returns>
|
||||
private List<string> GetFavoritesEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.GetEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/favorites", 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);
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.Index;
|
||||
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.Favorites.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="FavoritesIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class FavoritesIndexViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/favorites";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FavoritesIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public FavoritesIndexViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FavoritesIndexView_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 FavoritesIndexView_WhenCalledByAuthenticatedUser_ShouldNotLeakTokensOrInternals()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
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("favorites-container", content, StringComparison.Ordinal);
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Contains("no-store", string.Join(", ", response.Headers.GetValues("Cache-Control")), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("StackTrace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("PasswordHash", 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);
|
||||
}
|
||||
}
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
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;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="RemoveFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemoveFavoriteEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveFavoriteEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public RemoveFavoriteEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(nameof(FavoriteMediaKind.MusicTrack), Guid.NewGuid().ToString(), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(removeRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(GetRemoveEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(nameof(FavoriteMediaKind.MusicTrack), Guid.NewGuid().ToString(), antiforgeryToken: null);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetRemoveEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFavorite_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(nameof(FavoriteMediaKind.MusicTrack), Guid.NewGuid().ToString(), "invalid-token");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetRemoveEndpointCalls());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // script injection
|
||||
[InlineData("MusicTrack/../../admin")] // path traversal through a valid media kind prefix
|
||||
public async Task RemoveFavorite_WithInjectionPayloadInMediaKind_ShouldSanitizeItAndNotForwardTheRawValue(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
string sanitizedEndpoint = $"users/me/favorites/Invalid/{mediaItemId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(sanitizedEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(Uri.EscapeDataString(payload), mediaItemId.ToString(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The route values are normalized before they are substituted into the upstream URL, so a crafted value can never escape its URL segment.
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
List<string> removeEndpoints = GetRemoveEndpointCalls();
|
||||
Assert.Equal([sanitizedEndpoint], removeEndpoints);
|
||||
Assert.DoesNotContain(payload, string.Join(",", removeEndpoints), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(Uri.EscapeDataString(payload), string.Join(",", removeEndpoints), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Favorites--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // script injection
|
||||
public async Task RemoveFavorite_WithInjectionPayloadInMediaItemId_ShouldSanitizeItAndNotForwardTheRawValue(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string sanitizedEndpoint = $"users/me/favorites/MusicTrack/{ZERO_GUID}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(sanitizedEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(nameof(FavoriteMediaKind.MusicTrack), Uri.EscapeDataString(payload), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
List<string> removeEndpoints = GetRemoveEndpointCalls();
|
||||
Assert.Equal([sanitizedEndpoint], removeEndpoints);
|
||||
Assert.DoesNotContain(payload, string.Join(",", removeEndpoints), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(Uri.EscapeDataString(payload), string.Join(",", removeEndpoints), StringComparison.Ordinal);
|
||||
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 RemoveFavorite_WhenCalledByAuthenticatedUserWithValidToken_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
string expectedUpstreamEndpoint = $"users/me/favorites/MusicTrack/{mediaItemId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(nameof(FavoriteMediaKind.MusicTrack), mediaItemId.ToString(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal([expectedUpstreamEndpoint], GetRemoveEndpointCalls());
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the remove favorite endpoints that were called upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream remove favorite endpoints that were called.</returns>
|
||||
private List<string> GetRemoveEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.DeleteEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/favorites", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the remove favorite request for the specified route values.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">The value of the media kind route segment.</param>
|
||||
/// <param name="mediaItemId">The value of the media item identifier route segment.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
|
||||
/// <returns>The configured remove favorite request.</returns>
|
||||
private static HttpRequestMessage CreateRemoveRequest(string mediaKind, string mediaItemId, string? antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage removeRequest = new(HttpMethod.Delete, $"/en-us/favorites/{mediaKind}/{mediaItemId}/api-remove-favorite")
|
||||
{
|
||||
// The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation.
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
removeRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
removeRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
if (antiforgeryToken is not null)
|
||||
removeRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return removeRequest;
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.GetPlaylist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Playlists.GetPlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetPlaylistEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaylistEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PlaylistDtoFixture _playlistDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaylistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetPlaylistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylist_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/en-us/playlists/item/{Guid.NewGuid()}/api-get-playlist");
|
||||
|
||||
// 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 GetPlaylist_WhenCalledByAuthenticatedUser_ShouldBePrivateAndNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _playlistDtoFixture.Create(id: playlistId));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/item/{playlistId}/api-get-playlist");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([expectedEndpoint], GetPlaylistEndpointCalls());
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
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 GetPlaylist_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuidAndNotTheRawValue()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(sanitizedEndpoint, _playlistDtoFixture.Create(id: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/playlists/item/not-a-guid/api-get-playlist");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> endpointCalls = GetPlaylistEndpointCalls();
|
||||
Assert.Equal([sanitizedEndpoint], endpointCalls);
|
||||
Assert.DoesNotContain("not-a-guid", string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("1;DROP TABLE")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("𝕡𝕝𝕒𝕪𝕝𝕚𝕤𝕥")] // unicode payload
|
||||
public async Task GetPlaylist_WithInjectionPayloadInPlaylistId_ShouldNormalizeItAndNotForwardTheRawValue(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(sanitizedEndpoint, _playlistDtoFixture.Create(id: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/item/{Uri.EscapeDataString(payload)}/api-get-playlist");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
List<string> endpointCalls = GetPlaylistEndpointCalls();
|
||||
Assert.All(endpointCalls, endpoint => Assert.Equal(sanitizedEndpoint, endpoint));
|
||||
Assert.DoesNotContain(payload, string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(Uri.EscapeDataString(payload), string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the playlist endpoints that were called upstream, excluding the endpoints called by the authentication helpers.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream playlist endpoints that were called.</returns>
|
||||
private List<string> GetPlaylistEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.GetEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/playlists/", 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);
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.Item;
|
||||
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.Playlists.Item;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="AddPlaylistViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddPlaylistViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/playlists/item";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public AddPlaylistViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistView_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 AddPlaylistView_WhenCalledByAuthenticatedUser_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
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.True(response.Headers.CacheControl?.Private);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Contains("no-store", string.Join(", ", response.Headers.GetValues("Cache-Control")), StringComparison.OrdinalIgnoreCase);
|
||||
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);
|
||||
Assert.DoesNotContain("TestPass123!", 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);
|
||||
}
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Enums.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.Item;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
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.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Playlists.Item;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="PlaylistItemViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistItemViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PlaylistDtoFixture _playlistDtoFixture = new();
|
||||
private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new();
|
||||
private readonly PaginatedDtoFixture<PlaylistEntryDto> _paginatedDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PlaylistItemViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public PlaylistItemViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlaylistItemView_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/en-us/playlists/item/{Guid.NewGuid()}");
|
||||
|
||||
// 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 PlaylistItemView_WhenCalledByAuthenticatedUser_ShouldBePrivateAndNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
PlaylistEntryDto expectedEntry = _playlistEntryDtoFixture.Create(mediaItemType: PlaylistMediaItemType.MusicTrack);
|
||||
PlaylistDto expectedPlaylist = _playlistDtoFixture.Create(
|
||||
id: playlistId,
|
||||
entries: _paginatedDtoFixture.Create(data: [expectedEntry], currentPage: 1, perPage: 200, count: 1, numberOfPages: 1));
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedPlaylist);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/item/{playlistId}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal([expectedEndpoint], GetPlaylistEndpointCalls());
|
||||
Assert.True(response.Headers.CacheControl?.Private);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Contains("no-store", string.Join(", ", response.Headers.GetValues("Cache-Control")), StringComparison.OrdinalIgnoreCase);
|
||||
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 PlaylistItemView_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuidAndNotTheRawValue()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(sanitizedEndpoint, _playlistDtoFixture.Create(id: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/playlists/item/not-a-guid");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> endpointCalls = GetPlaylistEndpointCalls();
|
||||
Assert.Equal([sanitizedEndpoint], endpointCalls);
|
||||
Assert.DoesNotContain("not-a-guid", string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("1;DROP TABLE")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
[InlineData("𝕡𝕝𝕒𝕪𝕝𝕚𝕤𝕥")] // unicode payload
|
||||
public async Task PlaylistItemView_WithInjectionPayloadInPlaylistId_ShouldNormalizeItAndNotForwardTheRawValue(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}?currentPage=1&perPage=200";
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(sanitizedEndpoint, _playlistDtoFixture.Create(id: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/item/{Uri.EscapeDataString(payload)}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
List<string> endpointCalls = GetPlaylistEndpointCalls();
|
||||
Assert.All(endpointCalls, endpoint => Assert.Equal(sanitizedEndpoint, endpoint));
|
||||
Assert.DoesNotContain(payload, string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(Uri.EscapeDataString(payload), string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the playlist endpoints that were called upstream, excluding the endpoints called by the authentication helpers.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream playlist endpoints that were called.</returns>
|
||||
private List<string> GetPlaylistEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.GetEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/playlists/", 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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user