mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 08:11:10 +00:00
Adds music stack test coverage and fixes playlist cache and stream error handling
This commit is contained in:
1 parent
394f6b510c
commit
aba803b106
197 files changed
+29081
-34
No files matched your search
+167
@@ -0,0 +1,167 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack;
|
||||
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.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="StreamMusicTrackEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The concurrency rate limiter of the stream route is not exercised, because it requires four concurrent long lived streams, which needs a real
|
||||
/// normalization pipeline and ffmpeg, neither of which is available in the test environment.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StreamMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamMusicTrackEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public StreamMusicTrackEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StreamMusicTrack_WhenNotAuthenticated_ShouldRedirectToLoginWithoutCallingTheApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await anonymousClient.GetAsync(BuildBrowserPath(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("artistId")] // injection in the artist Id
|
||||
[InlineData("albumId")] // injection in the album Id
|
||||
[InlineData("trackId")] // injection in the track Id
|
||||
public async Task StreamMusicTrack_WithAnInjectionPayloadInATrackRouteId_ShouldNormalizeTheIdWithoutLeakingData(string routeValue)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
const string PAYLOAD = "'; DROP TABLE Tracks; --";
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string validArtistId = Guid.NewGuid().ToString();
|
||||
string validAlbumId = Guid.NewGuid().ToString();
|
||||
string validTrackId = Guid.NewGuid().ToString();
|
||||
string artistId = routeValue == "artistId" ? Uri.EscapeDataString(PAYLOAD) : validArtistId;
|
||||
string albumId = routeValue == "albumId" ? Uri.EscapeDataString(PAYLOAD) : validAlbumId;
|
||||
string trackId = routeValue == "trackId" ? Uri.EscapeDataString(PAYLOAD) : validTrackId;
|
||||
string expectedEndpoint = ApiRoutes.Music.STREAM_TRACK
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", routeValue == "artistId" ? Guid.Empty.ToString() : validArtistId)
|
||||
.Replace("{albumId}", routeValue == "albumId" ? Guid.Empty.ToString() : validAlbumId)
|
||||
.Replace("{trackId}", routeValue == "trackId" ? Guid.Empty.ToString() : validTrackId);
|
||||
byte[] contentBytes = CreateBytes(128);
|
||||
_apiFactory.StreamingApiClientStub.RegisterStreamResponse(expectedEndpoint, await CreateStreamResultAsync(contentBytes));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(
|
||||
$"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track?libraryId={libraryId}");
|
||||
byte[] responseBytes = await response.Content.ReadAsByteArrayAsync();
|
||||
string responseText = Encoding.UTF8.GetString(responseBytes);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal(contentBytes, responseBytes);
|
||||
Assert.DoesNotContain("SQL", responseText, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", responseText, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("at Lumina", responseText, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(PAYLOAD, responseText, StringComparison.Ordinal);
|
||||
Assert.Single(_apiFactory.StreamingApiClientStub.GetEndpointsCalled);
|
||||
Assert.Equal(expectedEndpoint, _apiFactory.StreamingApiClientStub.GetEndpointsCalled[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StreamMusicTrack_WhenTheApiDeclaresAPublicCache_ShouldNeverExposeAPublicCacheControl()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.StreamingApiClientStub.Reset();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
string expectedEndpoint = ApiRoutes.Music.STREAM_TRACK
|
||||
.Replace("{libraryId}", libraryId.ToString())
|
||||
.Replace("{artistId}", artistId.ToString())
|
||||
.Replace("{albumId}", albumId.ToString())
|
||||
.Replace("{trackId}", trackId.ToString());
|
||||
_apiFactory.StreamingApiClientStub.RegisterStreamResponse(expectedEndpoint, await CreateStreamResultAsync(CreateBytes(64)));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(BuildBrowserPath(libraryId, artistId, albumId, trackId));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string cacheControl = response.Headers.CacheControl?.ToString() ?? string.Empty;
|
||||
Assert.DoesNotContain("public", cacheControl, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the browser facing route of the direct stream of a track.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The Id of the track.</param>
|
||||
/// <returns>The browser facing route of the requested stream.</returns>
|
||||
private static string BuildBrowserPath(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
|
||||
{
|
||||
return $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track?libraryId={libraryId}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a streamed API response with an ok status and a body.
|
||||
/// </summary>
|
||||
/// <param name="contentBytes">The bytes of the content of the response.</param>
|
||||
/// <returns>The created streamed response.</returns>
|
||||
private static async Task<ApiStreamResult> CreateStreamResultAsync(byte[] contentBytes)
|
||||
{
|
||||
HttpResponseMessage response = new(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new ByteArrayContent(contentBytes)
|
||||
};
|
||||
response.Content.Headers.ContentType = new MediaTypeHeaderValue("audio/mpeg");
|
||||
response.Headers.CacheControl = new CacheControlHeaderValue { Public = true, MaxAge = TimeSpan.FromSeconds(120) };
|
||||
return await ApiStreamResult.CreateAsync(response, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a deterministic byte array that stands in for the content of a stream.
|
||||
/// </summary>
|
||||
/// <param name="length">The number of bytes to create.</param>
|
||||
/// <returns>The created bytes.</returns>
|
||||
private static byte[] CreateBytes(int length)
|
||||
{
|
||||
return [.. Enumerable.Range(0, length).Select(index => (byte)(index % 256))];
|
||||
}
|
||||
}
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistEntries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.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.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.Playlists.AddPlaylistEntries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="AddPlaylistEntriesEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route
|
||||
/// performs no credential comparison, and token or claim correctness does not apply because the Web layer issues no token for this route.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddPlaylistEntriesEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly AddPlaylistEntriesRequestFixture _addPlaylistEntriesRequestFixture = new();
|
||||
private readonly PlaylistEntriesAddedDtoFixture _playlistEntriesAddedDtoFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
private readonly string _clientIp;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistEntriesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public AddPlaylistEntriesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistEntries_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create();
|
||||
HttpRequestMessage addRequest = CreateAddRequest(Guid.NewGuid().ToString(), request, 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 AddPlaylistEntries_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create();
|
||||
HttpRequestMessage addRequest = CreateAddRequest(Guid.NewGuid().ToString(), request, antiforgeryToken: null);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetAddRequests());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistEntries_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create();
|
||||
HttpRequestMessage addRequest = CreateAddRequest(Guid.NewGuid().ToString(), request, "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 Playlists--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task AddPlaylistEntries_WithInjectionPayloadInPlaylistId_ShouldNormalizeItAndNotForwardTheRawValue(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}/entries-batch";
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(sanitizedEndpoint, _playlistEntriesAddedDtoFixture.Create(playlistId: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(Uri.EscapeDataString(payload), _addPlaylistEntriesRequestFixture.Create(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
List<string> endpointCalls = GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint).ToList();
|
||||
Assert.All(endpointCalls, endpoint => Assert.Equal(sanitizedEndpoint, endpoint));
|
||||
Assert.DoesNotContain(payload, string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(payload, 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 Playlists--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
public async Task AddPlaylistEntries_WithInjectionPayloadInTrackIds_ShouldRejectTheRequestWithoutCallingTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage addRequest = CreateRawAddRequest(
|
||||
Guid.NewGuid().ToString(),
|
||||
$"{{\"trackIds\": [{JsonSerializer.Serialize(payload)}]}}",
|
||||
webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistEntries_WhenBodyTriesToTargetAnotherUser_ShouldKeepTheUsersMeScope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
Guid otherUserId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-batch";
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, _playlistEntriesAddedDtoFixture.Create(playlistId: playlistId));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage addRequest = CreateRawAddRequest(
|
||||
playlistId.ToString(),
|
||||
$"{{\"trackIds\": [\"{Guid.NewGuid()}\"], \"userId\": \"{otherUserId}\"}}",
|
||||
webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> endpointCalls = GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint).ToList();
|
||||
Assert.Equal([expectedEndpoint], endpointCalls);
|
||||
Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, StringComparison.Ordinal));
|
||||
Assert.DoesNotContain(otherUserId.ToString(), string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistEntries_WhenApiReportsForbidden_ShouldReturnASanitizedErrorWithoutLeakingData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-batch";
|
||||
_apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Forbidden", detail: "PlaylistAccessDenied"),
|
||||
HttpStatusCode.Forbidden,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), _addPlaylistEntriesRequestFixture.Create(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
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 entries requests that were sent upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream add entries requests that were sent.</returns>
|
||||
private List<(string Endpoint, object? Data)> GetAddRequests()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.PostRequests
|
||||
.Where(postRequest => postRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal)
|
||||
&& postRequest.Endpoint.EndsWith("/entries-batch", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the add entries request for the specified playlist route value.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
/// <param name="request">The request payload to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
|
||||
/// <returns>The configured add entries request.</returns>
|
||||
private static HttpRequestMessage CreateAddRequest(string playlistId, AddPlaylistEntriesRequest request, string? antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage addRequest = new(HttpMethod.Post, $"/en-us/playlists/item/{playlistId}/api-add-entries")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
// 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>
|
||||
/// Builds the add entries request that posts the given raw JSON body.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
/// <param name="jsonBody">The raw JSON body to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request.</param>
|
||||
/// <returns>The configured add entries request.</returns>
|
||||
private static HttpRequestMessage CreateRawAddRequest(string playlistId, string jsonBody, string antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage addRequest = new(HttpMethod.Post, $"/en-us/playlists/item/{playlistId}/api-add-entries")
|
||||
{
|
||||
Content = new StringContent(jsonBody, Encoding.UTF8, "application/json")
|
||||
};
|
||||
addRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
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);
|
||||
}
|
||||
}
|
||||
+280
@@ -0,0 +1,280 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistEntry;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.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.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.Playlists.AddPlaylistEntry;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="AddPlaylistEntryEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route
|
||||
/// performs no credential comparison, and token or claim correctness does not apply because the Web layer issues no token for this route.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddPlaylistEntryEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly AddPlaylistEntryRequestFixture _addPlaylistEntryRequestFixture = new();
|
||||
private readonly PlaylistEntryAddedDtoFixture _playlistEntryAddedDtoFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
private readonly string _clientIp;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistEntryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public AddPlaylistEntryEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistEntry_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(Guid.NewGuid().ToString(), _addPlaylistEntryRequestFixture.Create(), 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 AddPlaylistEntry_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(Guid.NewGuid().ToString(), _addPlaylistEntryRequestFixture.Create(), antiforgeryToken: null);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetAddRequests());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistEntry_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(Guid.NewGuid().ToString(), _addPlaylistEntryRequestFixture.Create(), "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 Playlists--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task AddPlaylistEntry_WithInjectionPayloadInPlaylistId_ShouldNormalizeItAndNotForwardTheRawValue(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}/entries";
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(sanitizedEndpoint, _playlistEntryAddedDtoFixture.Create(playlistId: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(Uri.EscapeDataString(payload), _addPlaylistEntryRequestFixture.Create(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
List<string> endpointCalls = GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint).ToList();
|
||||
Assert.All(endpointCalls, endpoint => Assert.Equal(sanitizedEndpoint, endpoint));
|
||||
Assert.DoesNotContain(payload, string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(payload, 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 Playlists--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
public async Task AddPlaylistEntry_WithInjectionPayloadInTrackId_ShouldRejectTheRequestWithoutCallingTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage addRequest = CreateRawAddRequest(
|
||||
Guid.NewGuid().ToString(),
|
||||
$"{{\"trackId\": {JsonSerializer.Serialize(payload)}}}",
|
||||
webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistEntry_WhenBodyTriesToTargetAnotherUser_ShouldKeepTheUsersMeScope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
Guid otherUserId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries";
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, _playlistEntryAddedDtoFixture.Create(playlistId: playlistId));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage addRequest = CreateRawAddRequest(
|
||||
playlistId.ToString(),
|
||||
$"{{\"trackId\": \"{Guid.NewGuid()}\", \"userId\": \"{otherUserId}\"}}",
|
||||
webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> endpointCalls = GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint).ToList();
|
||||
Assert.Equal([expectedEndpoint], endpointCalls);
|
||||
Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, StringComparison.Ordinal));
|
||||
Assert.DoesNotContain(otherUserId.ToString(), string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistEntry_WhenApiReportsForbidden_ShouldReturnASanitizedErrorWithoutLeakingData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries";
|
||||
_apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Forbidden", detail: "PlaylistAccessDenied"),
|
||||
HttpStatusCode.Forbidden,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), _addPlaylistEntryRequestFixture.Create(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
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 entry requests that were sent upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream add entry requests that were sent.</returns>
|
||||
private List<(string Endpoint, object? Data)> GetAddRequests()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.PostRequests
|
||||
.Where(postRequest => postRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal)
|
||||
&& postRequest.Endpoint.EndsWith("/entries", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the add entry request for the specified playlist route value.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
/// <param name="request">The request payload to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
|
||||
/// <returns>The configured add entry request.</returns>
|
||||
private static HttpRequestMessage CreateAddRequest(string playlistId, AddPlaylistEntryRequest request, string? antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage addRequest = new(HttpMethod.Post, $"/en-us/playlists/item/{playlistId}/entries/api-add-entry")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
// 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>
|
||||
/// Builds the add entry request that posts the given raw JSON body.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
/// <param name="jsonBody">The raw JSON body to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request.</param>
|
||||
/// <returns>The configured add entry request.</returns>
|
||||
private static HttpRequestMessage CreateRawAddRequest(string playlistId, string jsonBody, string antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage addRequest = new(HttpMethod.Post, $"/en-us/playlists/item/{playlistId}/entries/api-add-entry")
|
||||
{
|
||||
Content = new StringContent(jsonBody, Encoding.UTF8, "application/json")
|
||||
};
|
||||
addRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
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);
|
||||
}
|
||||
}
|
||||
+281
@@ -0,0 +1,281 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistScopeEntries;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.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.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.Playlists.AddPlaylistScopeEntries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="AddPlaylistScopeEntriesEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route
|
||||
/// performs no credential comparison, and token or claim correctness does not apply because the Web layer issues no token for this route.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddPlaylistScopeEntriesEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly AddPlaylistScopeEntriesRequestFixture _addPlaylistScopeEntriesRequestFixture = new();
|
||||
private readonly PlaylistEntriesAddedDtoFixture _playlistEntriesAddedDtoFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
private readonly string _clientIp;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistScopeEntriesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public AddPlaylistScopeEntriesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistScopeEntries_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(Guid.NewGuid().ToString(), _addPlaylistScopeEntriesRequestFixture.Create(), 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 AddPlaylistScopeEntries_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(Guid.NewGuid().ToString(), _addPlaylistScopeEntriesRequestFixture.Create(), antiforgeryToken: null);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetAddRequests());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistScopeEntries_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(Guid.NewGuid().ToString(), _addPlaylistScopeEntriesRequestFixture.Create(), "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 Playlists--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task AddPlaylistScopeEntries_WithInjectionPayloadInPlaylistId_ShouldNormalizeItAndNotForwardTheRawValue(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}/entries-scope";
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(sanitizedEndpoint, _playlistEntriesAddedDtoFixture.Create(playlistId: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(Uri.EscapeDataString(payload), _addPlaylistScopeEntriesRequestFixture.Create(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
List<string> endpointCalls = GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint).ToList();
|
||||
Assert.All(endpointCalls, endpoint => Assert.Equal(sanitizedEndpoint, endpoint));
|
||||
Assert.DoesNotContain(payload, string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("libraryId")] // required scope identifier
|
||||
[InlineData("artistId")] // optional scope identifier
|
||||
[InlineData("albumId")] // optional scope identifier
|
||||
public async Task AddPlaylistScopeEntries_WithInjectionPayloadInScopeIds_ShouldRejectTheRequestWithoutCallingTheApi(string propertyName)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
const string payload = "'; DROP TABLE Playlists--";
|
||||
HttpRequestMessage addRequest = CreateRawAddRequest(
|
||||
Guid.NewGuid().ToString(),
|
||||
$"{{\"libraryId\": \"{Guid.NewGuid()}\", \"{propertyName}\": {JsonSerializer.Serialize(payload)}}}",
|
||||
webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistScopeEntries_WhenBodyTriesToTargetAnotherUser_ShouldKeepTheUsersMeScope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
Guid otherUserId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-scope";
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, _playlistEntriesAddedDtoFixture.Create(playlistId: playlistId));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage addRequest = CreateRawAddRequest(
|
||||
playlistId.ToString(),
|
||||
$"{{\"libraryId\": \"{Guid.NewGuid()}\", \"userId\": \"{otherUserId}\"}}",
|
||||
webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> endpointCalls = GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint).ToList();
|
||||
Assert.Equal([expectedEndpoint], endpointCalls);
|
||||
Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, StringComparison.Ordinal));
|
||||
Assert.DoesNotContain(otherUserId.ToString(), string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddPlaylistScopeEntries_WhenApiReportsForbidden_ShouldReturnASanitizedErrorWithoutLeakingData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-scope";
|
||||
_apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Forbidden", detail: "PlaylistAccessDenied"),
|
||||
HttpStatusCode.Forbidden,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), _addPlaylistScopeEntriesRequestFixture.Create(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(addRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
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 scope entries requests that were sent upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream add scope entries requests that were sent.</returns>
|
||||
private List<(string Endpoint, object? Data)> GetAddRequests()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.PostRequests
|
||||
.Where(postRequest => postRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal)
|
||||
&& postRequest.Endpoint.EndsWith("/entries-scope", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the add scope entries request for the specified playlist route value.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
/// <param name="request">The request payload to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
|
||||
/// <returns>The configured add scope entries request.</returns>
|
||||
private static HttpRequestMessage CreateAddRequest(string playlistId, AddPlaylistScopeEntriesRequest request, string? antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage addRequest = new(HttpMethod.Post, $"/en-us/playlists/item/{playlistId}/api-add-scope-entries")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
// 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>
|
||||
/// Builds the add scope entries request that posts the given raw JSON body.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
/// <param name="jsonBody">The raw JSON body to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request.</param>
|
||||
/// <returns>The configured add scope entries request.</returns>
|
||||
private static HttpRequestMessage CreateRawAddRequest(string playlistId, string jsonBody, string antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage addRequest = new(HttpMethod.Post, $"/en-us/playlists/item/{playlistId}/api-add-scope-entries")
|
||||
{
|
||||
Content = new StringContent(jsonBody, Encoding.UTF8, "application/json")
|
||||
};
|
||||
addRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
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);
|
||||
}
|
||||
}
|
||||
+270
@@ -0,0 +1,270 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Enums.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.CreatePlaylist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.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.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.Playlists.CreatePlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="CreatePlaylistEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route
|
||||
/// performs no credential comparison, and token or claim correctness does not apply because the Web layer issues no token for this route.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CreatePlaylistEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string UPSTREAM_ENDPOINT = "users/me/playlists";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly CreatePlaylistRequestFixture _createPlaylistRequestFixture = new();
|
||||
private readonly PlaylistDtoFixture _playlistDtoFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
private readonly string _clientIp;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CreatePlaylistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public CreatePlaylistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreatePlaylist_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage createRequest = CreateCreateRequest(_createPlaylistRequestFixture.Create(), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(createRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(GetCreateRequests());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreatePlaylist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage createRequest = CreateCreateRequest(_createPlaylistRequestFixture.Create(), antiforgeryToken: null);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(createRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetCreateRequests());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreatePlaylist_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage createRequest = CreateCreateRequest(_createPlaylistRequestFixture.Create(), "invalid-token");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(createRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetCreateRequests());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Playlists--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task CreatePlaylist_WithInjectionPayloadInName_ShouldNotFailOrLeakThePayload(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(UPSTREAM_ENDPOINT, _playlistDtoFixture.Create(name: "Injected playlist"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage createRequest = CreateCreateRequest(_createPlaylistRequestFixture.Create(name: payload), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(createRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// A playlist name is a free-form string, so the Web layer forwards it and the API is responsible for storing it safely; the Web layer must never echo it back.
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
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(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Playlists--")] // destructive injection
|
||||
public async Task CreatePlaylist_WithInjectionPayloadInType_ShouldRejectTheRequestWithoutCallingTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage createRequest = CreateRawCreateRequest(
|
||||
$"{{\"name\": \"Test playlist\", \"type\": {JsonSerializer.Serialize(payload)}}}",
|
||||
webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(createRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// The media type 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);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Empty(GetCreateRequests());
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreatePlaylist_WhenBodyTriesToTargetAnotherUser_ShouldKeepTheUsersMeScope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid otherUserId = Guid.NewGuid();
|
||||
_apiFactory.ApiClientStub.RegisterPostResponse(UPSTREAM_ENDPOINT, _playlistDtoFixture.Create());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage createRequest = CreateRawCreateRequest(
|
||||
$"{{\"name\": \"Test playlist\", \"type\": \"{PlaylistType.Music}\", \"userId\": \"{otherUserId}\"}}",
|
||||
webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(createRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> endpointCalls = GetCreateRequests().Select(createRequestCall => createRequestCall.Endpoint).ToList();
|
||||
Assert.Equal([UPSTREAM_ENDPOINT], endpointCalls);
|
||||
Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, StringComparison.Ordinal));
|
||||
Assert.DoesNotContain(otherUserId.ToString(), string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreatePlaylist_WhenApiReportsForbidden_ShouldReturnASanitizedErrorWithoutLeakingData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPostException(UPSTREAM_ENDPOINT, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Forbidden", detail: "PlaylistCreationForbidden"),
|
||||
HttpStatusCode.Forbidden,
|
||||
UPSTREAM_ENDPOINT));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage createRequest = CreateCreateRequest(_createPlaylistRequestFixture.Create(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(createRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the create playlist requests that were sent upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream create playlist requests that were sent.</returns>
|
||||
private List<(string Endpoint, object? Data)> GetCreateRequests()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.PostRequests
|
||||
.Where(postRequest => postRequest.Endpoint == UPSTREAM_ENDPOINT)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the create playlist request that sends the given <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request payload to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
|
||||
/// <returns>The configured create playlist request.</returns>
|
||||
private static HttpRequestMessage CreateCreateRequest(CreatePlaylistRequest request, string? antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/playlists/api-create-playlist")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
createRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
if (antiforgeryToken is not null)
|
||||
createRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return createRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the create playlist request that posts the given raw JSON body.
|
||||
/// </summary>
|
||||
/// <param name="jsonBody">The raw JSON body to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request.</param>
|
||||
/// <returns>The configured create playlist request.</returns>
|
||||
private static HttpRequestMessage CreateRawCreateRequest(string jsonBody, string antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/playlists/api-create-playlist")
|
||||
{
|
||||
Content = new StringContent(jsonBody, Encoding.UTF8, "application/json")
|
||||
};
|
||||
createRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
createRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return createRequest;
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.DeletePlaylist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
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.Playlists.DeletePlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="DeletePlaylistEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route
|
||||
/// performs no credential comparison, and token or claim correctness does not apply because the Web layer issues no token for this route.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeletePlaylistEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
private readonly string _clientIp;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeletePlaylistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DeletePlaylistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletePlaylist_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid().ToString(), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(GetDeleteEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletePlaylist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid().ToString(), antiforgeryToken: null);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetDeleteEndpointCalls());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletePlaylist_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid().ToString(), "invalid-token");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetDeleteEndpointCalls());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Playlists--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task DeletePlaylist_WithInjectionPayloadInPlaylistId_ShouldNormalizeItAndNotForwardTheRawValue(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(sanitizedEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(Uri.EscapeDataString(payload), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
List<string> endpointCalls = GetDeleteEndpointCalls();
|
||||
Assert.All(endpointCalls, endpoint => Assert.Equal(sanitizedEndpoint, endpoint));
|
||||
Assert.DoesNotContain(payload, string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletePlaylist_WhenPlaylistBelongsToAnotherUser_ShouldKeepTheUsersMeScopeAndNotLeakData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid otherUsersPlaylistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{otherUsersPlaylistId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteException(expectedEndpoint, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Forbidden", detail: "PlaylistAccessDenied"),
|
||||
HttpStatusCode.Forbidden,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(otherUsersPlaylistId.ToString(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
List<string> endpointCalls = GetDeleteEndpointCalls();
|
||||
Assert.Equal([expectedEndpoint], endpointCalls);
|
||||
Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, 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 delete playlist endpoints that were called upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream delete playlist endpoints that were called.</returns>
|
||||
private List<string> GetDeleteEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.DeleteEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the delete playlist request for the specified route value.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist 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 delete playlist request.</returns>
|
||||
private static HttpRequestMessage CreateDeleteRequest(string playlistId, string? antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/playlists/item/{playlistId}/api-delete-playlist")
|
||||
{
|
||||
// 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.
|
||||
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
if (antiforgeryToken is not null)
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return deleteRequest;
|
||||
}
|
||||
|
||||
/// <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.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.GetPlaylists;
|
||||
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.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Playlists.GetPlaylists;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetPlaylistsEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route
|
||||
/// performs no credential comparison, and token or claim correctness does not apply because the Web layer issues no token for this route.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaylistsEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string UPSTREAM_ENDPOINT = "users/me/playlists";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PlaylistSummaryDtoFixture _playlistSummaryDtoFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
private readonly string _clientIp;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaylistsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetPlaylistsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylists_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync("/en-us/playlists/api-get-playlists");
|
||||
|
||||
// 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 GetPlaylists_WhenCalledByAuthenticatedUser_ShouldBePrivateAndNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(UPSTREAM_ENDPOINT, new[] { _playlistSummaryDtoFixture.Create() });
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/playlists/api-get-playlists");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
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);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("other-user-id")] // a plain identifier of another user
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Playlists--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
public async Task GetPlaylists_WithAnotherUserIdInTheQueryString_ShouldKeepTheUsersMeScope(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(UPSTREAM_ENDPOINT, new[] { _playlistSummaryDtoFixture.Create() });
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/api-get-playlists?userId={Uri.EscapeDataString(payload)}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> endpointCalls = GetPlaylistEndpointCalls();
|
||||
Assert.Equal([UPSTREAM_ENDPOINT], endpointCalls);
|
||||
Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, StringComparison.Ordinal));
|
||||
Assert.DoesNotContain(payload, string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaylists_WhenApiReportsForbidden_ShouldReturnASanitizedErrorWithoutLeakingAnotherUsersPlaylists()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterGetException(UPSTREAM_ENDPOINT, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Forbidden", detail: "PlaylistsAccessDenied"),
|
||||
HttpStatusCode.Forbidden,
|
||||
UPSTREAM_ENDPOINT));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/playlists/api-get-playlists");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
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 == UPSTREAM_ENDPOINT)];
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.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.Playlists.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="PlaylistsIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route
|
||||
/// performs no credential comparison, token or claim correctness does not apply because the Web layer issues no token for this route, and
|
||||
/// cross-user isolation does not apply because the page accepts no user or resource identifier and shows only the signed-in user's own data.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PlaylistsIndexViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/playlists";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly string _clientIp;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PlaylistsIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public PlaylistsIndexViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlaylistsIndexView_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
|
||||
// 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 PlaylistsIndexView_WhenCalledByAuthenticatedUser_ShouldBePrivateAndNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
|
||||
// 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.Contains("__RequestVerificationToken", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("TestPass123!", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlaylistsIndexView_WhenCalledByAuthenticatedUser_ShouldNotProxyAnyPlaylistCall()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, 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);
|
||||
}
|
||||
}
|
||||
+297
@@ -0,0 +1,297 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.MovePlaylistEntry;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.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.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.Playlists.MovePlaylistEntry;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="MovePlaylistEntryEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route
|
||||
/// performs no credential comparison, and token or claim correctness does not apply because the Web layer issues no token for this route.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MovePlaylistEntryEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly MovePlaylistEntryRequestFixture _movePlaylistEntryRequestFixture = new();
|
||||
private readonly PlaylistEntryMovedDtoFixture _playlistEntryMovedDtoFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
private readonly string _clientIp;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MovePlaylistEntryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public MovePlaylistEntryEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MovePlaylistEntry_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage moveRequest = CreateMoveRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), _movePlaylistEntryRequestFixture.Create(), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(moveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(GetMoveRequests());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MovePlaylistEntry_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage moveRequest = CreateMoveRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), _movePlaylistEntryRequestFixture.Create(), antiforgeryToken: null);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetMoveRequests());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MovePlaylistEntry_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage moveRequest = CreateMoveRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), _movePlaylistEntryRequestFixture.Create(), "invalid-token");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetMoveRequests());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Playlists--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task MovePlaylistEntry_WithInjectionPayloadInRouteIds_ShouldNormalizeThemAndNotForwardTheRawValues(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}/entries/{ZERO_GUID}/move";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse(sanitizedEndpoint, _playlistEntryMovedDtoFixture.Create(playlistId: Guid.Empty, entryId: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage moveRequest = CreateMoveRequest(
|
||||
Uri.EscapeDataString(payload),
|
||||
Uri.EscapeDataString(payload),
|
||||
_movePlaylistEntryRequestFixture.Create(),
|
||||
webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
List<string> endpointCalls = GetMoveRequests().Select(moveRequestCall => moveRequestCall.Endpoint).ToList();
|
||||
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("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Playlists--")] // destructive injection
|
||||
public async Task MovePlaylistEntry_WithInjectionPayloadInTargetPosition_ShouldRejectTheRequestWithoutCallingTheApi(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage moveRequest = CreateRawMoveRequest(
|
||||
Guid.NewGuid().ToString(),
|
||||
Guid.NewGuid().ToString(),
|
||||
$"{{\"targetPosition\": {JsonSerializer.Serialize(payload)}}}",
|
||||
webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Empty(GetMoveRequests());
|
||||
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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MovePlaylistEntry_WhenBodyTriesToTargetAnotherUser_ShouldKeepTheUsersMeScope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
Guid playlistEntryId = Guid.NewGuid();
|
||||
Guid otherUserId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}/entries/{playlistEntryId}/move";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse(expectedEndpoint, _playlistEntryMovedDtoFixture.Create(playlistId: playlistId, entryId: playlistEntryId));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage moveRequest = CreateRawMoveRequest(
|
||||
playlistId.ToString(),
|
||||
playlistEntryId.ToString(),
|
||||
$"{{\"targetPosition\": 1, \"userId\": \"{otherUserId}\"}}",
|
||||
webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> endpointCalls = GetMoveRequests().Select(moveRequestCall => moveRequestCall.Endpoint).ToList();
|
||||
Assert.Equal([expectedEndpoint], endpointCalls);
|
||||
Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, StringComparison.Ordinal));
|
||||
Assert.DoesNotContain(otherUserId.ToString(), string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MovePlaylistEntry_WhenPlaylistBelongsToAnotherUser_ShouldKeepTheUsersMeScopeAndNotLeakData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid otherUsersPlaylistId = Guid.NewGuid();
|
||||
Guid playlistEntryId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{otherUsersPlaylistId}/entries/{playlistEntryId}/move";
|
||||
_apiFactory.ApiClientStub.RegisterPutException(expectedEndpoint, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Forbidden", detail: "PlaylistAccessDenied"),
|
||||
HttpStatusCode.Forbidden,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage moveRequest = CreateMoveRequest(
|
||||
otherUsersPlaylistId.ToString(),
|
||||
playlistEntryId.ToString(),
|
||||
_movePlaylistEntryRequestFixture.Create(),
|
||||
webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
List<string> endpointCalls = GetMoveRequests().Select(moveRequestCall => moveRequestCall.Endpoint).ToList();
|
||||
Assert.Equal([expectedEndpoint], endpointCalls);
|
||||
Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, 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 move entry requests that were sent upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream move entry requests that were sent.</returns>
|
||||
private List<(string Endpoint, object? Data)> GetMoveRequests()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.PutRequests
|
||||
.Where(putRequest => putRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal)
|
||||
&& putRequest.Endpoint.EndsWith("/move", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the move entry request for the specified route values.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
/// <param name="playlistEntryId">The value of the playlist entry identifier route segment.</param>
|
||||
/// <param name="request">The request payload to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
|
||||
/// <returns>The configured move entry request.</returns>
|
||||
private static HttpRequestMessage CreateMoveRequest(string playlistId, string playlistEntryId, MovePlaylistEntryRequest request, string? antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage moveRequest = new(HttpMethod.Put, $"/en-us/playlists/item/{playlistId}/entries/{playlistEntryId}/api-move-entry")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
moveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
moveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
if (antiforgeryToken is not null)
|
||||
moveRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return moveRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the move entry request that posts the given raw JSON body.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
/// <param name="playlistEntryId">The value of the playlist entry identifier route segment.</param>
|
||||
/// <param name="jsonBody">The raw JSON body to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request.</param>
|
||||
/// <returns>The configured move entry request.</returns>
|
||||
private static HttpRequestMessage CreateRawMoveRequest(string playlistId, string playlistEntryId, string jsonBody, string antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage moveRequest = new(HttpMethod.Put, $"/en-us/playlists/item/{playlistId}/entries/{playlistEntryId}/api-move-entry")
|
||||
{
|
||||
Content = new StringContent(jsonBody, Encoding.UTF8, "application/json")
|
||||
};
|
||||
moveRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
moveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
moveRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return moveRequest;
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.RemovePlaylistEntry;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
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.Playlists.RemovePlaylistEntry;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="RemovePlaylistEntryEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route
|
||||
/// performs no credential comparison, and token or claim correctness does not apply because the Web layer issues no token for this route.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemovePlaylistEntryEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
private readonly string _clientIp;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemovePlaylistEntryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public RemovePlaylistEntryEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemovePlaylistEntry_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(Guid.NewGuid().ToString(), 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 RemovePlaylistEntry_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(Guid.NewGuid().ToString(), 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 RemovePlaylistEntry_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(Guid.NewGuid().ToString(), 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 Playlists--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task RemovePlaylistEntry_WithInjectionPayloadInRouteIds_ShouldNormalizeThemAndNotForwardTheRawValues(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}/entries/{ZERO_GUID}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(sanitizedEndpoint);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(
|
||||
Uri.EscapeDataString(payload),
|
||||
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> endpointCalls = GetRemoveEndpointCalls();
|
||||
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("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemovePlaylistEntry_WhenEntryBelongsToAnotherUser_ShouldKeepTheUsersMeScopeAndNotLeakData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid otherUsersPlaylistId = Guid.NewGuid();
|
||||
Guid otherUsersPlaylistEntryId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{otherUsersPlaylistId}/entries/{otherUsersPlaylistEntryId}";
|
||||
_apiFactory.ApiClientStub.RegisterDeleteException(expectedEndpoint, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Forbidden", detail: "PlaylistEntryAccessDenied"),
|
||||
HttpStatusCode.Forbidden,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage removeRequest = CreateRemoveRequest(
|
||||
otherUsersPlaylistId.ToString(),
|
||||
otherUsersPlaylistEntryId.ToString(),
|
||||
webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
List<string> endpointCalls = GetRemoveEndpointCalls();
|
||||
Assert.Equal([expectedEndpoint], endpointCalls);
|
||||
Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, 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 remove entry endpoints that were called upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream remove entry endpoints that were called.</returns>
|
||||
private List<string> GetRemoveEndpointCalls()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.DeleteEndpointsCalled
|
||||
.Where(endpoint => endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal)
|
||||
&& endpoint.Contains("/entries/", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the remove entry request for the specified route values.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
/// <param name="playlistEntryId">The value of the playlist entry 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 entry request.</returns>
|
||||
private static HttpRequestMessage CreateRemoveRequest(string playlistId, string playlistEntryId, string? antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage removeRequest = new(HttpMethod.Delete, $"/en-us/playlists/item/{playlistId}/entries/{playlistEntryId}/api-remove-entry")
|
||||
{
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Requests.Playlists;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Playlists.UpdatePlaylist;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.Requests.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.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.Playlists.UpdatePlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="UpdatePlaylistEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route
|
||||
/// performs no credential comparison, and token or claim correctness does not apply because the Web layer issues no token for this route.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdatePlaylistEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly UpdatePlaylistRequestFixture _updatePlaylistRequestFixture = new();
|
||||
private readonly PlaylistDetailsDtoFixture _playlistDetailsDtoFixture = new();
|
||||
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
|
||||
private readonly string _clientIp;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdatePlaylistEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public UpdatePlaylistEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaylist_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage updateRequest = CreateUpdateRequest(Guid.NewGuid().ToString(), _updatePlaylistRequestFixture.Create(), antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(updateRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(GetUpdateRequests());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaylist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage updateRequest = CreateUpdateRequest(Guid.NewGuid().ToString(), _updatePlaylistRequestFixture.Create(), antiforgeryToken: null);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetUpdateRequests());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaylist_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage updateRequest = CreateUpdateRequest(Guid.NewGuid().ToString(), _updatePlaylistRequestFixture.Create(), "invalid-token");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(GetUpdateRequests());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Playlists--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task UpdatePlaylist_WithInjectionPayloadInPlaylistId_ShouldNormalizeItAndNotForwardTheRawValue(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse(sanitizedEndpoint, _playlistDetailsDtoFixture.Create(id: Guid.Empty));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage updateRequest = CreateUpdateRequest(Uri.EscapeDataString(payload), _updatePlaylistRequestFixture.Create(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
List<string> endpointCalls = GetUpdateRequests().Select(updateRequestCall => updateRequestCall.Endpoint).ToList();
|
||||
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("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Playlists--")] // destructive injection
|
||||
[InlineData("../../admin")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task UpdatePlaylist_WithInjectionPayloadInName_ShouldNotFailOrLeakThePayload(string payload)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse(expectedEndpoint, _playlistDetailsDtoFixture.Create(id: playlistId, name: "Updated playlist"));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage updateRequest = CreateUpdateRequest(playlistId.ToString(), _updatePlaylistRequestFixture.Create(name: payload), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// A playlist name is a free-form string, so the Web layer forwards it and the API is responsible for storing it safely; the Web layer must never echo it back.
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
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(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaylist_WhenBodyTriesToTargetAnotherUser_ShouldKeepTheUsersMeScope()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid playlistId = Guid.NewGuid();
|
||||
Guid otherUserId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{playlistId}";
|
||||
_apiFactory.ApiClientStub.RegisterPutResponse(expectedEndpoint, _playlistDetailsDtoFixture.Create(id: playlistId));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage updateRequest = CreateRawUpdateRequest(
|
||||
playlistId.ToString(),
|
||||
$"{{\"name\": \"Updated playlist\", \"userId\": \"{otherUserId}\"}}",
|
||||
webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
List<string> endpointCalls = GetUpdateRequests().Select(updateRequestCall => updateRequestCall.Endpoint).ToList();
|
||||
Assert.Equal([expectedEndpoint], endpointCalls);
|
||||
Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, StringComparison.Ordinal));
|
||||
Assert.DoesNotContain(otherUserId.ToString(), string.Join(",", endpointCalls), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaylist_WhenPlaylistBelongsToAnotherUser_ShouldKeepTheUsersMeScopeAndNotLeakData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
Guid otherUsersPlaylistId = Guid.NewGuid();
|
||||
string expectedEndpoint = $"users/me/playlists/{otherUsersPlaylistId}";
|
||||
_apiFactory.ApiClientStub.RegisterPutException(expectedEndpoint, new ApiException(
|
||||
_problemDetailsDtoFixture.Create(title: "General.Forbidden", detail: "PlaylistAccessDenied"),
|
||||
HttpStatusCode.Forbidden,
|
||||
expectedEndpoint));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp);
|
||||
HttpRequestMessage updateRequest = CreateUpdateRequest(otherUsersPlaylistId.ToString(), _updatePlaylistRequestFixture.Create(), webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(json.RootElement.TryGetProperty("data", out _));
|
||||
List<string> endpointCalls = GetUpdateRequests().Select(updateRequestCall => updateRequestCall.Endpoint).ToList();
|
||||
Assert.Equal([expectedEndpoint], endpointCalls);
|
||||
Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, 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 update playlist requests that were sent upstream, excluding the requests made to authenticate the test client.
|
||||
/// </summary>
|
||||
/// <returns>The list of upstream update playlist requests that were sent.</returns>
|
||||
private List<(string Endpoint, object? Data)> GetUpdateRequests()
|
||||
{
|
||||
return [.. _apiFactory.ApiClientStub.PutRequests
|
||||
.Where(putRequest => putRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the update playlist request for the specified route value.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
/// <param name="request">The request payload to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
|
||||
/// <returns>The configured update playlist request.</returns>
|
||||
private static HttpRequestMessage CreateUpdateRequest(string playlistId, UpdatePlaylistRequest request, string? antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, $"/en-us/playlists/item/{playlistId}/api-update-playlist")
|
||||
{
|
||||
Content = JsonContent.Create(request)
|
||||
};
|
||||
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
if (antiforgeryToken is not null)
|
||||
updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return updateRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the update playlist request that posts the given raw JSON body.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
|
||||
/// <param name="jsonBody">The raw JSON body to send.</param>
|
||||
/// <param name="antiforgeryToken">The antiforgery token to include in the request.</param>
|
||||
/// <returns>The configured update playlist request.</returns>
|
||||
private static HttpRequestMessage CreateRawUpdateRequest(string playlistId, string jsonBody, string antiforgeryToken)
|
||||
{
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Put, $"/en-us/playlists/item/{playlistId}/api-update-playlist")
|
||||
{
|
||||
Content = new StringContent(jsonBody, Encoding.UTF8, "application/json")
|
||||
};
|
||||
updateRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
return updateRequest;
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetPlaybackState;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Tools.Settings.GetPlaybackState;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetPlaybackStateEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The route takes no user controlled input, has no configured rate limiting policy and never issues a token, so injection resistance, rate
|
||||
/// limiting, timing attack resistance and token claim correctness are not applicable to it.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaybackStateEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PlaybackStateDtoFixture _playbackStateDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaybackStateEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetPlaybackStateEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackState_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/tools/settings/api-get-playback-state");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "users/me/settings/playback-state");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackState_WhenCalledByAuthenticatedUser_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse("users/me/settings/playback-state", _playbackStateDtoFixture.Create(volume: 0.35, isMuted: true));
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/tools/settings/api-get-playback-state");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
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.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "users/me/settings/playback-state");
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Common.Requests.Common;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdatePlaybackState;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Tools.Settings.UpdatePlaybackState;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="UpdatePlaybackStateEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The route accepts only numeric and boolean fields, has no configured rate limiting policy and never issues a token, so injection resistance,
|
||||
/// rate limiting, timing attack resistance and token claim correctness are not applicable to it.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdatePlaybackStateEndpointTests : IClassFixture<LuminaWebFactory>
|
||||
{
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly PlaybackStateDtoFixture _playbackStateDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdatePlaybackStateEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public UpdatePlaybackStateEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaybackState_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Post, "/en-us/tools/settings/api-update-playback-state")
|
||||
{
|
||||
Content = JsonContent.Create(_playbackStateDtoFixture.Create())
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(updateRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "users/me/settings/playback-state");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaybackState_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Post, "/en-us/tools/settings/api-update-playback-state")
|
||||
{
|
||||
Content = JsonContent.Create(_playbackStateDtoFixture.Create())
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "users/me/settings/playback-state");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaybackState_WhenCalledByAuthenticatedUser_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings/playback-state", _ => new EmptyRequest());
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
PlaybackStateDto state = _playbackStateDtoFixture.Create(volume: 0.35, isMuted: true);
|
||||
HttpRequestMessage updateRequest = new(HttpMethod.Post, "/en-us/tools/settings/api-update-playback-state")
|
||||
{
|
||||
Content = JsonContent.Create(state)
|
||||
};
|
||||
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user