mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 01:11:10 +00:00
Implements tests for commit 067e9a21d0
This commit is contained in:
1 parent
aeefa9487e
commit
a75447062f
18 files changed
+3156
No files matched your search
+353
@@ -0,0 +1,353 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="ShuffleTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Rate limiting is not exercised because the shuffle route does not declare a rate limiter policy, unlike the authentication and track streaming routes,
|
||||
/// so there is no configured limit to exceed. Token and claim correctness does not apply, because the route issues no token. Timing attack resistance does not
|
||||
/// apply either, because the route performs no credential comparison.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ShuffleTracksEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ShuffleTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ShuffleTracksEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// A unique X-Forwarded-For isolates rate limiting state per test.
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, new { count = 10 });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
|
||||
public async Task ShuffleTracks_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(
|
||||
$"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/tracks/shuffle", new { count = 10 });
|
||||
|
||||
// Assert
|
||||
// The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean validation error instead of failing the request binding.
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task ShuffleTracks_WithInjectionInCount_ShouldNotCorruptOrLeakData(string maliciousCount)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(
|
||||
$"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle", new { count = maliciousCount });
|
||||
|
||||
// Assert
|
||||
// The endpoint opts into DontCatchExceptions(), so a body value that cannot be bound is answered by the generic exception handler with the sanitized 500 problem.
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
await AssertSanitizedProblemAsync(response, maliciousCount);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task ShuffleTracks_WithInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(
|
||||
$"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle", new { count = 10, artistId = maliciousArtistId });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
await AssertSanitizedProblemAsync(response, maliciousArtistId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task ShuffleTracks_WithInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(
|
||||
$"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle", new { count = 10, albumId = maliciousAlbumId });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
await AssertSanitizedProblemAsync(response, maliciousAlbumId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task ShuffleTracks_WithInjectionInExcludedTrackIds_ShouldNotCorruptOrLeakData(string maliciousTrackId)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(
|
||||
$"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle", new { count = 10, excludedTrackIds = new[] { maliciousTrackId } });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
await AssertSanitizedProblemAsync(response, maliciousTrackId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid libraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid artistId = await SeedArtistAsync(libraryId, "Queen");
|
||||
Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
|
||||
await SeedTrackAsync(libraryId, albumId, "Hidden Song");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(
|
||||
$"/api/v1/libraries/{libraryId}/tracks/shuffle", new { count = 10 });
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.DoesNotContain("Hidden Song", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the sanitized generic API problem and never echoes the payload or leaks database details.
|
||||
/// </summary>
|
||||
/// <param name="response">The response to inspect.</param>
|
||||
/// <param name="payload">The malicious payload that must not be echoed.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private static async Task AssertSanitizedProblemAsync(HttpResponseMessage response, string payload)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("InternalServerError", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Equal(StatusCodes.Status500InternalServerError, problemDetails.RootElement.GetProperty("status").GetInt32());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded other user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an artist of the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the artist belongs to.</param>
|
||||
/// <param name="name">The name of the artist.</param>
|
||||
/// <returns>The Id of the seeded artist.</returns>
|
||||
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(
|
||||
id: artistId, libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return artistId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an album of the artist identified by <paramref name="artistId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the album belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="title">The title of the album.</param>
|
||||
/// <returns>The Id of the seeded album.</returns>
|
||||
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
AlbumEntity album = _albumEntityFixture.Create(
|
||||
id: albumId,
|
||||
artistId: artistId,
|
||||
libraryId: libraryId,
|
||||
title: title,
|
||||
includeTracks: false,
|
||||
includeMetadata: false,
|
||||
includeBarcode: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Albums.Add(album);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return albumId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of the album identified by <paramref name="albumId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library the track belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="title">The title of the track.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, Guid albumId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(
|
||||
id: trackId,
|
||||
albumId: albumId,
|
||||
libraryId: libraryId,
|
||||
path: $"/music/shuffle-{Guid.NewGuid():N}.flac",
|
||||
title: title,
|
||||
includeMetadata: false,
|
||||
includeOriginalReleaseDate: false,
|
||||
includeOriginalReleaseYear: false,
|
||||
includeReReleaseDate: false,
|
||||
includeReReleaseYear: false);
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="ShuffleTracksEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The shuffle route declares no rate limiter policy, so rate limiting is not exercised here. Token and claim correctness does not apply, because the Web
|
||||
/// layer issues no token for this route, and timing attack resistance does not apply either, because the route performs no credential comparison.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ShuffleTracksEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private const string SHUFFLE_TRACKS_PATH = "/en-us/library/audio-library/music-library/tracks/api-shuffle-tracks";
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ShuffleTracksRequestFixture _shuffleTracksRequestFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ShuffleTracksEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public ShuffleTracksEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenNotAuthenticated_ShouldRedirectToLoginWithoutCallingTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.SendAsync(CreateShuffleRequest(request));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Contains("/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => IsShuffleCall(postRequest.Endpoint));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task ShuffleTracks_WithInjectionInLibraryId_ShouldRejectTheRequestWithoutCallingTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(CreateRawShuffleRequest(
|
||||
$"{{\"libraryId\": {JsonSerializer.Serialize(payload)}, \"count\": 10}}"));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
AssertRejectedWithoutLeak(content, payload);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task ShuffleTracks_WithInjectionInCount_ShouldRejectTheRequestWithoutCallingTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(CreateRawShuffleRequest(
|
||||
$"{{\"libraryId\": \"{Guid.NewGuid()}\", \"count\": {JsonSerializer.Serialize(payload)}}}"));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
AssertRejectedWithoutLeak(content, payload);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Tracks; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task ShuffleTracks_WithInjectionInExcludedTrackIds_ShouldRejectTheRequestWithoutCallingTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(CreateRawShuffleRequest(
|
||||
$"{{\"libraryId\": \"{Guid.NewGuid()}\", \"count\": 10, \"excludedTrackIds\": [{JsonSerializer.Serialize(payload)}]}}"));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
AssertRejectedWithoutLeak(content, payload);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ShuffleTracks_WhenApiRejectsTheRequest_ShouldReturnACleanErrorWithoutLeakingData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(libraryId: libraryId);
|
||||
string expectedEndpoint = ApiRoutes.Music.SHUFFLE_TRACKS.Replace("{libraryId}", libraryId.ToString());
|
||||
_apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Unauthorized", detail: "NotAuthorized"),
|
||||
HttpStatusCode.Forbidden,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(CreateShuffleRequest(request));
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The Web layer answers programmatic callers with a sanitized JSON error instead of forwarding the upstream problem details verbatim.
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Contains("not authorized", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == expectedEndpoint);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that a request rejected before reaching the API was answered with a sanitized JSON error that does not echo the payload.
|
||||
/// </summary>
|
||||
/// <param name="content">The body of the response.</param>
|
||||
/// <param name="payload">The malicious payload that must not be echoed.</param>
|
||||
private void AssertRejectedWithoutLeak(string content, string payload)
|
||||
{
|
||||
// The Web layer reports binding failures to programmatic callers as a JSON error with the success flag cleared, and never forwards the request upstream.
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => IsShuffleCall(postRequest.Endpoint));
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether the specified upstream endpoint is the shuffle endpoint.
|
||||
/// </summary>
|
||||
/// <param name="endpoint">The upstream endpoint to check.</param>
|
||||
/// <returns><see langword="true"/> when the endpoint is the shuffle endpoint, <see langword="false"/> otherwise.</returns>
|
||||
private static bool IsShuffleCall(string endpoint)
|
||||
{
|
||||
return endpoint.EndsWith("/tracks/shuffle", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the Web shuffle request that posts the given <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The shuffle request to send.</param>
|
||||
/// <returns>The configured Web request.</returns>
|
||||
private static HttpRequestMessage CreateShuffleRequest(ShuffleTracksRequest request)
|
||||
{
|
||||
HttpRequestMessage shuffleRequest = new(HttpMethod.Post, SHUFFLE_TRACKS_PATH)
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
shuffleRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
shuffleRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return shuffleRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the Web shuffle request that posts the given raw JSON body.
|
||||
/// </summary>
|
||||
/// <param name="jsonBody">The raw JSON body to send.</param>
|
||||
/// <returns>The configured Web request.</returns>
|
||||
private static HttpRequestMessage CreateRawShuffleRequest(string jsonBody)
|
||||
{
|
||||
HttpRequestMessage shuffleRequest = new(HttpMethod.Post, SHUFFLE_TRACKS_PATH)
|
||||
{
|
||||
Content = new StringContent(jsonBody, Encoding.UTF8, "application/json")
|
||||
};
|
||||
shuffleRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
shuffleRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
return shuffleRequest;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user