mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Hardens the library API security tests
This commit is contained in:
1 parent
3d089b063f
commit
ab5cbfb949
17 files changed
+457
-40
No files matched your search
+18
@@ -220,6 +220,24 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a test user and its owned libraries from the database.
|
||||
/// </summary>
|
||||
/// <param name="username">The username of the test user to remove.</param>
|
||||
public void RemoveTestUser(string username)
|
||||
{
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity? user = dbContext.Users.Include(candidate => candidate.Libraries).FirstOrDefault(candidate => candidate.Username == username);
|
||||
if (user is not null)
|
||||
{
|
||||
dbContext.Libraries.RemoveRange(user.Libraries);
|
||||
dbContext.Users.Remove(user);
|
||||
dbContext.SaveChanges();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a test admin user, its role, and its user-role link from the database.
|
||||
/// </summary>
|
||||
|
||||
+47
@@ -120,6 +120,53 @@ public class UpdateRoleEndpointTests : IClassFixture<LuminaApiFactory>, IAsyncDi
|
||||
Assert.Equal(maliciousRoleName, updatedRole!.RoleName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateRole_WhenAuthenticatedNonAdmin_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededPermissionId = Guid.NewGuid();
|
||||
_seededRoleId = Guid.NewGuid();
|
||||
RoleEntity seededRole = _roleEntityFixture.Create(id: _seededRoleId, roleName: "ExistingRole");
|
||||
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
seedDbContext.Permissions.Add(_permissionEntityFixture.Create(id: _seededPermissionId, permissionName: AuthorizationPermission.CanDeleteUsers));
|
||||
seedDbContext.Roles.Add(seededRole);
|
||||
await seedDbContext.SaveChangesAsync();
|
||||
}
|
||||
UpdateRoleRequest requestBody = _updateRoleRequestFixture.Create(
|
||||
roleId: seededRole.Id,
|
||||
roleName: "Hijacked",
|
||||
permissions: [_seededPermissionId]
|
||||
);
|
||||
StringContent content = new(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsync("/api/v1/auth/roles", content);
|
||||
string responseContent = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseContent, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.DoesNotContain("password", responseContent, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// The role is untouched.
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
RoleEntity? storedRole = await dbContext.Roles.FirstOrDefaultAsync(role => role.Id == seededRole.Id);
|
||||
Assert.NotNull(storedRole);
|
||||
Assert.Equal("ExistingRole", storedRole!.RoleName);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
|
||||
+12
-8
@@ -37,6 +37,7 @@ public class AddTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
@@ -103,9 +104,11 @@ public class AddTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
// Arrange
|
||||
HttpClient ownerClient = _apiFactory.CreateClient();
|
||||
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
|
||||
_seededUsernames.Add(ownerUsername);
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(ownerId);
|
||||
|
||||
(Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(requesterUsername);
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create(contributors: []);
|
||||
|
||||
// Act
|
||||
@@ -119,11 +122,10 @@ public class AddTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(ownerUsername);
|
||||
await _apiFactory.RemoveTestUserAsync(requesterUsername);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -132,9 +134,11 @@ public class AddTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
// Arrange
|
||||
HttpClient ownerClient = _apiFactory.CreateClient();
|
||||
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient);
|
||||
_seededUsernames.Add(ownerUsername);
|
||||
(Guid ownerLibraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(ownerId);
|
||||
|
||||
(Guid attackerId, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(attackerUsername);
|
||||
Guid attackerLibraryId = Guid.NewGuid();
|
||||
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
|
||||
{
|
||||
@@ -155,8 +159,6 @@ public class AddTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
Assert.DoesNotContain(ownerLibraryId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(ownerUsername);
|
||||
await _apiFactory.RemoveTestUserAsync(attackerUsername);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -166,6 +168,7 @@ public class AddTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
|
||||
string injectedPath = Path.Combine(_libraryContentLocation, $"{maliciousPath}.flac");
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create(path: injectedPath, contributors: []);
|
||||
@@ -185,7 +188,6 @@ public class AddTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
TrackEntity storedTrack = await dbContext.Tracks.SingleAsync(track => track.LibraryId == libraryId);
|
||||
Assert.Equal(injectedPath, storedTrack.Path);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -195,6 +197,7 @@ public class AddTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
(Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId);
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create(
|
||||
path: Path.Combine(_libraryContentLocation, $"{Guid.NewGuid():N}.flac"),
|
||||
@@ -215,7 +218,6 @@ public class AddTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
TrackEntity storedTrack = await dbContext.Tracks.SingleAsync(track => track.LibraryId == libraryId);
|
||||
Assert.Equal(maliciousTitle, storedTrack.Title);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -225,6 +227,7 @@ public class AddTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
{
|
||||
// Arrange
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
AddTrackRequest request = _addTrackRequestFixture.Create(contributors: []);
|
||||
|
||||
// Act
|
||||
@@ -243,7 +246,6 @@ public class AddTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -270,6 +272,8 @@ public class AddTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
// Nothing to clean up: each test removes its own seeded rows.
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+57
-11
@@ -9,9 +9,11 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteTrack;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
@@ -37,6 +39,7 @@ public class DeleteTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteTrackEndpointTests"/> class.
|
||||
@@ -82,6 +85,7 @@ public class DeleteTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
@@ -98,7 +102,6 @@ public class DeleteTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -110,6 +113,7 @@ public class DeleteTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
@@ -124,7 +128,6 @@ public class DeleteTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -136,6 +139,7 @@ public class DeleteTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks/{Guid.NewGuid()}");
|
||||
@@ -150,7 +154,6 @@ public class DeleteTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -162,6 +165,7 @@ public class DeleteTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Uri.EscapeDataString(maliciousTrackId)}");
|
||||
@@ -176,7 +180,6 @@ public class DeleteTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -188,7 +191,8 @@ public class DeleteTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{maliciousTrackId}");
|
||||
@@ -201,13 +205,17 @@ public class DeleteTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// Note: some payloads are normalized away by the server before routing, producing an empty-body 404;
|
||||
// when the value reaches the handler, the failure must still be a clean, generic problem.
|
||||
// Some payloads are normalized away by the server before routing, producing an empty-body response, while others reach the handler and
|
||||
// produce a clean problem details; either way, the status is asserted unconditionally, so an empty-bodied 500 cannot satisfy the test.
|
||||
Assert.True(response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.UnprocessableEntity,
|
||||
$"Unexpected status code {response.StatusCode}.");
|
||||
Assert.NotEqual(StatusCodes.Status500InternalServerError, (int)response.StatusCode);
|
||||
|
||||
// When the payload reaches the handler, the failure must still be a clean, generic problem.
|
||||
if (!string.IsNullOrWhiteSpace(content))
|
||||
{
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.True(response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.UnprocessableEntity);
|
||||
Assert.NotEqual(StatusCodes.Status500InternalServerError, (int)response.StatusCode);
|
||||
Assert.NotEmpty(problemDetails.RootElement.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,6 +225,7 @@ public class DeleteTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId);
|
||||
|
||||
@@ -239,7 +248,40 @@ public class DeleteTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTrack_WhenTrackBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutDeletingIt()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(actingUsername);
|
||||
(Guid ownLibraryId, _, _, _) = await SeedLibraryArtistAlbumAndTrackAsync(actingUserId);
|
||||
|
||||
// The track lives in a library owned by another user, and is referenced through the acting user's own library route.
|
||||
HttpClient victimClient = _apiFactory.CreateClient();
|
||||
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
|
||||
_seededUsernames.Add(victimUsername);
|
||||
(_, Guid victimArtistId, Guid victimAlbumId, Guid victimTrackId) = await SeedLibraryArtistAlbumAndTrackAsync(victimUserId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}/tracks/{victimTrackId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
|
||||
|
||||
// The other user's track is untouched.
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.NotNull(await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == victimTrackId));
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -251,8 +293,10 @@ public class DeleteTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return userId;
|
||||
}
|
||||
|
||||
@@ -306,5 +350,7 @@ public class DeleteTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+15
-6
@@ -37,6 +37,7 @@ public class GetTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTrackEndpointTests"/> class.
|
||||
@@ -81,6 +82,7 @@ public class GetTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
@@ -92,11 +94,11 @@ public class GetTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -107,6 +109,7 @@ public class GetTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}");
|
||||
@@ -118,11 +121,11 @@ public class GetTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -133,6 +136,7 @@ public class GetTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks/{Guid.NewGuid()}");
|
||||
@@ -145,11 +149,11 @@ public class GetTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousAlbumId, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -160,6 +164,7 @@ public class GetTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Uri.EscapeDataString(maliciousTrackId)}");
|
||||
@@ -171,11 +176,11 @@ public class GetTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousTrackId, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -183,6 +188,7 @@ public class GetTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId);
|
||||
|
||||
@@ -205,7 +211,6 @@ public class GetTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -217,8 +222,10 @@ public class GetTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return userId;
|
||||
}
|
||||
|
||||
@@ -272,5 +279,7 @@ public class GetTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+64
-14
@@ -10,6 +10,8 @@ using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.UpdateTrack;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -86,25 +88,33 @@ public class UpdateTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: maliciousTitle));
|
||||
SeedLibrary(libraryId, userId);
|
||||
(Guid artistId, Guid albumId, Guid trackId) = SeedArtistGraph(libraryId);
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create(
|
||||
path: Path.Combine(s_contentRootPath, $"injected-{Guid.NewGuid():N}.flac"),
|
||||
metadata: _audioMetadataDtoFixture.Create(title: maliciousTitle),
|
||||
moods: [],
|
||||
isrcs: [],
|
||||
contributors: [],
|
||||
ratings: []);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", request);
|
||||
|
||||
// Assert
|
||||
// The injected title is validated and handled by the parameterized update flow: the route artist does not exist, so the
|
||||
// request fails with a clean not found response and the injected payload is never executed as SQL.
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousTitle, content, StringComparison.Ordinal);
|
||||
// The malicious title passes validation, reaches the parameterized update, and is persisted verbatim: if it were
|
||||
// concatenated into raw SQL, the update would fail and the track would not be updated.
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
TrackEntity? storedTrack = await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId);
|
||||
Assert.NotNull(storedTrack);
|
||||
Assert.Equal(maliciousTitle, storedTrack!.Title);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -230,10 +240,50 @@ public class UpdateTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(403, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateTrack_WhenTrackBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutLeakingOrModifyingIt()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(actingUsername);
|
||||
Guid ownLibraryId = Guid.NewGuid();
|
||||
SeedLibrary(ownLibraryId, actingUserId);
|
||||
|
||||
// The track lives in a library owned by another user, and is referenced through the acting user's own library route.
|
||||
HttpClient victimClient = _apiFactory.CreateClient();
|
||||
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
|
||||
_seededUsernames.Add(victimUsername);
|
||||
Guid victimLibraryId = Guid.NewGuid();
|
||||
SeedLibrary(victimLibraryId, victimUserId);
|
||||
(Guid victimArtistId, Guid victimAlbumId, Guid victimTrackId) = SeedArtistGraph(victimLibraryId);
|
||||
UpdateTrackRequest request = _updateTrackRequestFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: "Hijacked"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}/tracks/{victimTrackId}", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
|
||||
|
||||
// The other user's track is untouched.
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.NotNull(await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == victimTrackId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a clean validation problem details that neither leaks internals nor echoes the injected payload.
|
||||
/// </summary>
|
||||
@@ -301,6 +351,6 @@ public class UpdateTrackEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
|
||||
}
|
||||
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUserAsync(username).GetAwaiter().GetResult();
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+2
@@ -95,6 +95,8 @@ public class AddBookEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(ownerUsername);
|
||||
|
||||
+1
@@ -63,6 +63,7 @@ public class GetBookEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousBookId, content, StringComparison.Ordinal);
|
||||
using JsonDocument problemDetails = JsonDocument.Parse(content);
|
||||
Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
|
||||
|
||||
|
||||
+3
@@ -75,6 +75,7 @@ public class GetBooksEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
response.EnsureSuccessStatusCode();
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousSearchTerm, content, StringComparison.Ordinal);
|
||||
|
||||
// the injected statement must never be executed: the Books table and the seeded rows must still be there
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
@@ -106,6 +107,8 @@ public class GetBooksEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(ownerUsername);
|
||||
|
||||
+3
@@ -76,6 +76,7 @@ public class GetBooksLiteEndpointTests : IClassFixture<LuminaApiFactory>, IDispo
|
||||
response.EnsureSuccessStatusCode();
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(maliciousSearchTerm, content, StringComparison.Ordinal);
|
||||
|
||||
// the injected statement must never be executed: the Books table and the seeded rows must still be there
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
@@ -107,6 +108,8 @@ public class GetBooksLiteEndpointTests : IClassFixture<LuminaApiFactory>, IDispo
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(ownerUsername);
|
||||
|
||||
+1
@@ -111,6 +111,7 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture<LuminaApiFactor
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
|
||||
|
||||
+1
@@ -111,6 +111,7 @@ public class GetReadingManifestEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
|
||||
|
||||
+1
@@ -133,6 +133,7 @@ public class GetReadingResourceEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
|
||||
|
||||
+1
@@ -133,6 +133,7 @@ public class GetReadingSectionEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
|
||||
|
||||
+2
@@ -174,6 +174,8 @@ public class UpdateBookEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(ownerUsername);
|
||||
|
||||
+2
@@ -88,6 +88,8 @@ public class UpdateBookCoverEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
|
||||
await _apiFactory.RemoveTestUserAsync(ownerUsername);
|
||||
|
||||
+227
-1
@@ -1,10 +1,25 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authorization;
|
||||
using Lumina.Contracts.Requests.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authorization;
|
||||
@@ -13,13 +28,22 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.A
|
||||
/// Contains security tests for the <see cref="UpdateUserRoleAndPermissionsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<LuminaApiFactory>, IAsyncDisposable
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly UpdateUserRoleAndPermissionsRequestFixture _updateUserRoleAndPermissionsRequestFixture = new();
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly PermissionEntityFixture _permissionEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
private Guid _adminUserId;
|
||||
private Guid _seededRoleId;
|
||||
private Guid _seededPermissionId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserRoleAndPermissionsEndpointTests"/> class.
|
||||
@@ -27,6 +51,7 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<LuminaApi
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdateUserRoleAndPermissionsEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
@@ -53,4 +78,205 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<LuminaApi
|
||||
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserRoleAndPermissions_WhenAuthenticatedNonAdmin_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
using HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
Guid targetUserId = Guid.NewGuid();
|
||||
string url = $"/api/v1/auth/users/{targetUserId}/role-and-permissions";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsync(url, new StringContent("{}", Encoding.UTF8, "application/json"));
|
||||
string responseContent = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseContent, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.DoesNotContain("password", responseContent, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", responseContent, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", responseContent, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserRoleAndPermissions_WhenCalledByAdminWithValidData_ShouldUpdateRoleAndPermissions()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
_adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
UserEntity targetUser = await SeedTargetUserAsync();
|
||||
RoleEntity editorRole = await SeedRoleAsync("Editor");
|
||||
PermissionEntity permission = await SeedPermissionAsync(AuthorizationPermission.CanDeleteUsers);
|
||||
UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(
|
||||
userId: targetUser.Id,
|
||||
roleId: editorRole.Id,
|
||||
permissions: [permission.Id]
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/auth/users/{targetUser.Id}/role-and-permissions", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
using JsonDocument authorizationResponse = JsonDocument.Parse(content);
|
||||
Assert.Equal(targetUser.Id, authorizationResponse.RootElement.GetProperty("userId").GetGuid());
|
||||
Assert.Equal("Editor", authorizationResponse.RootElement.GetProperty("role").GetString());
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity? updatedUser = await dbContext.Users
|
||||
.Include(user => user.UserRole).ThenInclude(userRole => userRole!.Role)
|
||||
.Include(user => user.UserPermissions)
|
||||
.FirstOrDefaultAsync(user => user.Id == targetUser.Id);
|
||||
Assert.NotNull(updatedUser);
|
||||
Assert.Equal("Editor", updatedUser!.UserRole!.Role.RoleName);
|
||||
Assert.Contains(updatedUser.UserPermissions, userPermission => userPermission.PermissionId == permission.Id);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE UserRoles; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task UpdateUserRoleAndPermissions_WithInjectionInUserIdRouteSegment_ShouldNotLeakOrExecuteSql(string maliciousUserId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
_adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(
|
||||
userId: Guid.NewGuid(),
|
||||
roleId: Guid.NewGuid(),
|
||||
permissions: []
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/auth/users/{Uri.EscapeDataString(maliciousUserId)}/role-and-permissions", request);
|
||||
|
||||
// Assert
|
||||
// note: the {userId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler
|
||||
// note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding failure into a
|
||||
// 500 response instead of 400/422 (pre-existing production bug, not fixed here), and that body leaks the binding exception details
|
||||
// note: what matters is that the injection never reaches the database, so no SQL engine error (SqliteException) may surface
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE UserPermissions; --")] // destructive injection
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
public async Task UpdateUserRoleAndPermissions_WithInjectionInPermissionsBody_ShouldNotLeakOrExecuteSql(string maliciousPermissionId)
|
||||
{
|
||||
// Arrange
|
||||
// authenticate as an admin and seed the target user, so a well-formed body would reach the handler and be authorized
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
_adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
UserEntity targetUser = await SeedTargetUserAsync();
|
||||
string jsonBody = $"{{\"userId\":\"{targetUser.Id}\",\"roleId\":\"{Guid.NewGuid()}\",\"permissions\":[\"{maliciousPermissionId}\"]}}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsync(
|
||||
$"/api/v1/auth/users/{targetUser.Id}/role-and-permissions",
|
||||
new StringContent(jsonBody, Encoding.UTF8, "application/json"));
|
||||
|
||||
// Assert
|
||||
// Note: the permission Ids are Guid-typed, so the malicious value fails model binding before it reaches the handler.
|
||||
// Note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding failure into a
|
||||
// 500 response instead of 400/422 (pre-existing production bug, not fixed here), and that body leaks the binding exception details.
|
||||
// Note: what matters is that the injection never reaches the database, so no SQL engine error (SqliteException) may surface.
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user whose role and permissions are updated, and traces its username for cleanup.
|
||||
/// </summary>
|
||||
/// <returns>The seeded user.</returns>
|
||||
private async Task<UserEntity> SeedTargetUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
string username = $"targetuser_{Guid.NewGuid()}";
|
||||
UserEntity user = _userEntityFixture.Create(id: Guid.NewGuid(), username: username, password: "HashedPassword");
|
||||
user.TotpSecret = null;
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a role that is assigned to the updated user, and traces it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="roleName">The name of the role to seed.</param>
|
||||
/// <returns>The seeded role.</returns>
|
||||
private async Task<RoleEntity> SeedRoleAsync(string roleName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
_seededRoleId = Guid.NewGuid();
|
||||
RoleEntity role = _roleEntityFixture.Create(id: _seededRoleId, roleName: roleName);
|
||||
dbContext.Roles.Add(role);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return role;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a permission that is assigned to the updated user, and traces it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="permissionName">The permission to seed.</param>
|
||||
/// <returns>The seeded permission.</returns>
|
||||
private async Task<PermissionEntity> SeedPermissionAsync(AuthorizationPermission permissionName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
_seededPermissionId = Guid.NewGuid();
|
||||
PermissionEntity permission = _permissionEntityFixture.Create(id: _seededPermissionId, permissionName: permissionName);
|
||||
dbContext.Permissions.Add(permission);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return permission;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
await _apiFactory.RemoveTestUserAsync(username).ConfigureAwait(false);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
if (_seededRoleId != Guid.Empty)
|
||||
{
|
||||
RoleEntity? role = await dbContext.Roles.FirstOrDefaultAsync(candidate => candidate.Id == _seededRoleId);
|
||||
if (role is not null)
|
||||
dbContext.Roles.Remove(role);
|
||||
}
|
||||
if (_seededPermissionId != Guid.Empty)
|
||||
{
|
||||
PermissionEntity? permission = await dbContext.Permissions.FirstOrDefaultAsync(candidate => candidate.Id == _seededPermissionId);
|
||||
if (permission is not null)
|
||||
dbContext.Permissions.Remove(permission);
|
||||
}
|
||||
await dbContext.SaveChangesAsync();
|
||||
if (_adminUserId != Guid.Empty)
|
||||
await _apiFactory.RemoveAdminUserAsync(_adminUserId).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user