mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 05:11:10 +00:00
Hardens test assertions and adds missing test coverage.
This commit is contained in:
1 parent
6b86fd5805
commit
1189bbaf36
489 files changed
+39982
-512
No files matched your search
+74
@@ -1,6 +1,11 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Common.Interceptors;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
@@ -10,7 +15,11 @@ using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
@@ -22,6 +31,11 @@ namespace Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
|
||||
{
|
||||
private readonly SqliteConnection _connection;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=";
|
||||
|
||||
/// <summary>
|
||||
@@ -95,6 +109,66 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user with the Admin role, authenticates it on <paramref name="client"/>, and returns its Id.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to configure with authentication headers.</param>
|
||||
/// <returns>The Id of the created admin test user.</returns>
|
||||
public async Task<Guid> CreateAndAuthenticateAdminUserAsync(HttpClient client)
|
||||
{
|
||||
// a unique X-Forwarded-For isolates rate limiting state per test
|
||||
client.DefaultRequestHeaders.Clear();
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
|
||||
|
||||
using IServiceScope scope = Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
UserEntity user = new()
|
||||
{
|
||||
Id = userId,
|
||||
Username = username,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// seed a dedicated Admin role for this test user, keeping each test isolated in the shared in-memory database
|
||||
Guid roleId = Guid.NewGuid();
|
||||
RoleEntity role = new()
|
||||
{
|
||||
Id = roleId,
|
||||
RoleName = "Admin",
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
};
|
||||
dbContext.Roles.Add(role);
|
||||
dbContext.UserRoles.Add(new UserRoleEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
User = user,
|
||||
RoleId = roleId,
|
||||
Role = role,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the connection to the database.
|
||||
/// </summary>
|
||||
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
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.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.AddLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/libraries</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddLibraryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public AddLibraryEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddLibrary_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
AddLibraryRequest request = new(
|
||||
Title: "New Library",
|
||||
LibraryType: "EBook",
|
||||
ContentLocations: ["C:/Media"],
|
||||
CoverImage: null,
|
||||
IsEnabled: true,
|
||||
IsLocked: false,
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: false,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: true
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/libraries", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Libraries--")] // destructive injection
|
||||
public async Task AddLibrary_WithSQLInjectionInTitle_ShouldNotLeakOrError(string maliciousTitle)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
AddLibraryRequest request = new(
|
||||
Title: maliciousTitle,
|
||||
LibraryType: "EBook",
|
||||
ContentLocations: ["C:/Media"],
|
||||
CoverImage: null,
|
||||
IsEnabled: true,
|
||||
IsLocked: false,
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: false,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: true
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/libraries", request);
|
||||
|
||||
// Assert
|
||||
// the malicious title passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Title == maliciousTitle);
|
||||
Assert.NotNull(storedLibrary);
|
||||
Assert.Equal(maliciousTitle, storedLibrary!.Title);
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.CancelLibrariesScan;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/libraries/scans/cancel</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CancelLibrariesScanEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CancelLibrariesScanEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public CancelLibrariesScanEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CancelLibrariesScan_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries/scans/cancel", new { });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/libraries/scans/cancel", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CancelLibrariesScan_WhenAuthenticated_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/libraries/scans/cancel", new { });
|
||||
|
||||
// Assert
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task CreateAndAuthenticateUserAsync(HttpClient client)
|
||||
{
|
||||
client.DefaultRequestHeaders.Clear();
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = username,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
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.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.CancelLibraryScan;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/libraries/{libraryId}/scans/{scanId}/cancel</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CancelLibraryScanEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CancelLibraryScanEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public CancelLibraryScanEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CancelLibraryScan_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
string scanId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/scans/{scanId}/cancel", new { });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal($"/api/v1/libraries/{libraryId}/scans/{scanId}/cancel", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE LibraryScans--")] // destructive injection
|
||||
public async Task CancelLibraryScan_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
// authenticate with an admin user and seed a library, so a valid libraryId would reach the handler and be authorized
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
await SeedLibraryAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/scans/{Guid.NewGuid()}/cancel", new { });
|
||||
|
||||
// Assert
|
||||
// note: the {libraryId} 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
|
||||
// ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here)
|
||||
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
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.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.DeleteLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/libraries/{id}</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteLibraryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteLibraryEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteLibrary_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal($"/api/v1/libraries/{libraryId}", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Libraries--")] // destructive injection
|
||||
public async Task DeleteLibrary_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
// authenticate with an admin user and seed a library, so a valid id would reach the handler and be authorized
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
await SeedLibraryAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}");
|
||||
|
||||
// Assert
|
||||
// note: the {id} 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
|
||||
// ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here)
|
||||
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetEnabledLibraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/libraries/enabled</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetEnabledLibrariesEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetEnabledLibrariesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetEnabledLibrariesEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEnabledLibraries_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/enabled");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/libraries/enabled", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEnabledLibraries_WhenAuthenticated_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync("/api/v1/libraries/enabled");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task CreateAndAuthenticateUserAsync(HttpClient client)
|
||||
{
|
||||
client.DefaultRequestHeaders.Clear();
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = username,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetLibraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/libraries</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibrariesEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibrariesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetLibrariesEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraries_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/libraries", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraries_WhenAuthenticated_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync("/api/v1/libraries");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task CreateAndAuthenticateUserAsync(HttpClient client)
|
||||
{
|
||||
client.DefaultRequestHeaders.Clear();
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = username,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
}
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
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.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/libraries/{id}</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetLibraryEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibrary_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal($"/api/v1/libraries/{libraryId}", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Libraries--")] // destructive injection
|
||||
public async Task GetLibrary_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
// authenticate with an admin user and seed a library, so a valid id would reach the handler and be authorized
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
await SeedLibraryAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}");
|
||||
|
||||
// Assert
|
||||
// note: the {id} 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
|
||||
// ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here)
|
||||
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibrary_WhenAuthenticated_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}");
|
||||
|
||||
// Assert
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task CreateAndAuthenticateUserAsync(HttpClient client)
|
||||
{
|
||||
client.DefaultRequestHeaders.Clear();
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = username,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetLibraryScanProgress;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/libraries/{libraryId}/scans/{scanId}/progress</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryScanProgressEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryScanProgressEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetLibraryScanProgressEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryScanProgress_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
string scanId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/scans/{scanId}/progress");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal($"/api/v1/libraries/{libraryId}/scans/{scanId}/progress", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE LibraryScans--")] // destructive injection
|
||||
public async Task GetLibraryScanProgress_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
// authenticate with an admin user and seed a library, so a valid libraryId would reach the handler and be authorized
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
await SeedLibraryAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/scans/{Guid.NewGuid()}/progress");
|
||||
|
||||
// Assert
|
||||
// note: the {libraryId} 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
|
||||
// ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here)
|
||||
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetRunningLibraryScans;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/libraries/scans/running</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRunningLibraryScansEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRunningLibraryScansEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetRunningLibraryScansEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRunningLibraryScans_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/scans/running");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/libraries/scans/running", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRunningLibraryScans_WhenAuthenticated_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync("/api/v1/libraries/scans/running");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task CreateAndAuthenticateUserAsync(HttpClient client)
|
||||
{
|
||||
client.DefaultRequestHeaders.Clear();
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = username,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.ScanLibraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/libraries/scans</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScanLibrariesEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScanLibrariesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ScanLibrariesEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ScanLibraries_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries/scans", new { });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/libraries/scans", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ScanLibraries_WhenAuthenticated_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/libraries/scans", new { });
|
||||
|
||||
// Assert
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task CreateAndAuthenticateUserAsync(HttpClient client)
|
||||
{
|
||||
client.DefaultRequestHeaders.Clear();
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(new UserEntity
|
||||
{
|
||||
Id = userId,
|
||||
Username = username,
|
||||
Password = _hashService.HashString("TestPass123!"),
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!"));
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
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.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.ScanLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/libraries/{id}/scans</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ScanLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScanLibraryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ScanLibraryEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ScanLibrary_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/scans", new { });
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal($"/api/v1/libraries/{libraryId}/scans", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Libraries--")] // destructive injection
|
||||
public async Task ScanLibrary_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
// authenticate with an admin user and seed a library, so a valid id would reach the handler and be authorized
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
await SeedLibraryAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/scans", new { });
|
||||
|
||||
// Assert
|
||||
// note: the {id} 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
|
||||
// ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here)
|
||||
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.Management;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
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.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.UpdateLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/libraries/{id}</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateLibraryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdateLibraryEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateLibrary_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
UpdateLibraryRequest request = new(
|
||||
Id: Guid.NewGuid(),
|
||||
UserId: Guid.NewGuid(),
|
||||
Title: "Updated Library",
|
||||
LibraryType: "EBook",
|
||||
ContentLocations: ["C:/Media"],
|
||||
CoverImage: null,
|
||||
IsEnabled: true,
|
||||
IsLocked: false,
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: false,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: true
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal($"/api/v1/libraries/{libraryId}", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Libraries--")] // destructive injection
|
||||
public async Task UpdateLibrary_WithSQLInjectionInTitle_ShouldNotLeakOrError(string maliciousTitle)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
await SeedLibraryAsync(libraryId, userId);
|
||||
UpdateLibraryRequest request = new(
|
||||
Id: libraryId,
|
||||
UserId: userId,
|
||||
Title: maliciousTitle,
|
||||
LibraryType: "EBook",
|
||||
ContentLocations: ["C:/Media"],
|
||||
CoverImage: null,
|
||||
IsEnabled: true,
|
||||
IsLocked: false,
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: false,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: true
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
|
||||
|
||||
// Assert
|
||||
// the malicious title passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
|
||||
Assert.NotNull(storedLibrary);
|
||||
Assert.Equal(maliciousTitle, storedLibrary!.Title);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library to seed.</param>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/books/{id}</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetBookEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetBookEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetBookEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBook_WhenCalledWithoutAuthentication_ShouldBeAccessible()
|
||||
{
|
||||
// Arrange
|
||||
Guid bookId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Books--")] // destructive injection
|
||||
public async Task GetBook_WithSQLInjectionInBookId_ShouldNotLeakOrError(string maliciousBookId)
|
||||
{
|
||||
// Arrange
|
||||
// the {id} route parameter is string-typed, so the malicious value binds and reaches the anonymous endpoint handler
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Uri.EscapeDataString(maliciousBookId)}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// the endpoint processes the value without querying the persistence medium and without leaking it
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Maintenance;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/check-health</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CheckHealthEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CheckHealthEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public CheckHealthEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CheckHealth_WhenCalledWithoutAuthentication_ShouldBeAccessible()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/check-health");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryMetadataProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/libraries/{libraryId}/metadata-providers</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryMetadataProvidersEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryMetadataProvidersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetLibraryMetadataProvidersEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraryMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/metadata-providers");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal($"/api/v1/libraries/{libraryId}/metadata-providers", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Libraries--")] // destructive injection
|
||||
public async Task GetLibraryMetadataProviders_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
// authenticate with an admin user and seed a library with a metadata provider configuration, so a valid id would reach the handler
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
await SeedConfigurationAsync(libraryId, userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/metadata-providers");
|
||||
|
||||
// Assert
|
||||
// note: the {libraryId} 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
|
||||
// ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here)
|
||||
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryMetadataProviderConfigurationEntity"/> for the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library.</param>
|
||||
/// <param name="userId">The Id of the user that owns the data.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedConfigurationAsync(Guid libraryId, Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
PluginId = Guid.NewGuid(),
|
||||
IsEnabled = true,
|
||||
Rank = 1,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
|
||||
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.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetPluginSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/plugins/{pluginId}/settings</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPluginSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPluginSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetPluginSettingsEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPluginSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string pluginId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/plugins/{pluginId}/settings");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal($"/api/v1/plugins/{pluginId}/settings", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Plugins--")] // destructive injection
|
||||
public async Task GetPluginSettings_WithSQLInjectionInPluginId_ShouldNotLeakOrError(string maliciousPluginId)
|
||||
{
|
||||
// Arrange
|
||||
// authenticate with an admin user and seed a plugin, so a valid pluginId would reach the handler
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
await SeedPluginAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync($"/api/v1/plugins/{Uri.EscapeDataString(maliciousPluginId)}/settings");
|
||||
|
||||
// Assert
|
||||
// note: the {pluginId} 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
|
||||
// ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here)
|
||||
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="PluginEntity"/> created by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the creator.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedPluginAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Plugins.Add(new PluginEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Test Plugin",
|
||||
Author = "Test Author",
|
||||
Version = "1.0.0",
|
||||
Description = "A test plugin.",
|
||||
LoadStatus = PluginLoadStatus.Loaded,
|
||||
LoadError = null,
|
||||
SettingsJson = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetPlugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/plugins</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPluginsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPluginsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetPluginsEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlugins_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/plugins");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/plugins", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Contracts.Requests.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
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.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/libraries/{libraryId}/metadata-providers/reorder</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReorderLibraryMetadataProvidersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ReorderLibraryMetadataProvidersEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReorderLibraryMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
ReorderLibraryMetadataProvidersRequest request = new(
|
||||
LibraryId: Guid.NewGuid(),
|
||||
PluginIds: [Guid.NewGuid()]
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/reorder", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal($"/api/v1/libraries/{libraryId}/metadata-providers/reorder", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Plugins--")] // destructive injection
|
||||
public async Task ReorderLibraryMetadataProviders_WithSQLInjectionInPluginIds_ShouldNotLeakOrError(string maliciousPluginId)
|
||||
{
|
||||
// Arrange
|
||||
// authenticate with an admin user and seed a library with metadata provider configurations, so valid ids would reach the handler
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
await SeedConfigurationAsync(libraryId, userId, rank: 1);
|
||||
await SeedConfigurationAsync(libraryId, userId, rank: 2);
|
||||
|
||||
// Act
|
||||
// the malicious value cannot bind to the Guid-typed PluginIds request property, so the body fails JSON deserialization
|
||||
// before it ever reaches the endpoint handler
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync(
|
||||
$"/api/v1/libraries/{libraryId}/metadata-providers/reorder",
|
||||
new { libraryId = libraryId, pluginIds = new[] { maliciousPluginId } });
|
||||
|
||||
// Assert
|
||||
// note: observed status is 500 because the JSON body cannot be deserialized into the Guid-typed PluginIds property, and
|
||||
// FastEndpoints, combined with DontCatchExceptions(), turns the resulting JsonException into a 500 response instead of 400
|
||||
// (pre-existing production bug, not fixed here)
|
||||
// note: that 500 body leaks the JsonException details, so no DoesNotContain("Exception") is asserted here
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryMetadataProviderConfigurationEntity"/> for the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library.</param>
|
||||
/// <param name="userId">The Id of the user that owns the data.</param>
|
||||
/// <param name="rank">The rank of the provider.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedConfigurationAsync(Guid libraryId, Guid userId, int rank)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
PluginId = Guid.NewGuid(),
|
||||
IsEnabled = true,
|
||||
Rank = rank,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Contracts.Requests.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
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.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/libraries/{libraryId}/metadata-providers/{pluginId}/enabled</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetLibraryMetadataProviderEnabledEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public SetLibraryMetadataProviderEnabledEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetLibraryMetadataProviderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
string pluginId = Guid.NewGuid().ToString();
|
||||
SetLibraryMetadataProviderEnabledRequest request = new(
|
||||
LibraryId: Guid.NewGuid(),
|
||||
PluginId: Guid.NewGuid(),
|
||||
IsEnabled: true
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Libraries--")] // destructive injection
|
||||
public async Task SetLibraryMetadataProviderEnabled_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId)
|
||||
{
|
||||
// Arrange
|
||||
// authenticate with an admin user and seed a library with a metadata provider configuration, so valid ids would reach the handler
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
await SeedConfigurationAsync(libraryId, userId);
|
||||
SetLibraryMetadataProviderEnabledRequest request = new(
|
||||
LibraryId: libraryId,
|
||||
PluginId: Guid.NewGuid(),
|
||||
IsEnabled: true
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/metadata-providers/{Guid.NewGuid()}/enabled", request);
|
||||
|
||||
// Assert
|
||||
// note: the {libraryId} 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
|
||||
// ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here)
|
||||
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(new LibraryEntity
|
||||
{
|
||||
Id = libraryId,
|
||||
UserId = userId,
|
||||
Title = "Test Library",
|
||||
LibraryType = LibraryType.EBook,
|
||||
ContentLocations = [],
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="LibraryMetadataProviderConfigurationEntity"/> for the library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library.</param>
|
||||
/// <param name="userId">The Id of the user that owns the data.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedConfigurationAsync(Guid libraryId, Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = libraryId,
|
||||
PluginId = Guid.NewGuid(),
|
||||
IsEnabled = false,
|
||||
Rank = 1,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Contracts.Requests.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
|
||||
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.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.UpdatePluginSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/plugins/{pluginId}/settings</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdatePluginSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdatePluginSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdatePluginSettingsEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePluginSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string pluginId = Guid.NewGuid().ToString();
|
||||
UpdatePluginSettingsRequest request = new(
|
||||
PluginId: Guid.NewGuid(),
|
||||
Settings: new Dictionary<string, string> { ["Key"] = "Value" }
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/plugins/{pluginId}/settings", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal($"/api/v1/plugins/{pluginId}/settings", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||
[InlineData("'; DROP TABLE Plugins--")] // destructive injection
|
||||
public async Task UpdatePluginSettings_WithSQLInjectionInSettings_ShouldNotLeakOrError(string maliciousValue)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
Guid pluginId = await SeedPluginAsync(userId);
|
||||
UpdatePluginSettingsRequest request = new(
|
||||
PluginId: pluginId,
|
||||
Settings: new Dictionary<string, string> { ["Key"] = maliciousValue }
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/plugins/{pluginId}/settings", request);
|
||||
|
||||
// Assert
|
||||
// the malicious value passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
PluginEntity? storedPlugin = await dbContext.Plugins.FirstOrDefaultAsync(plugin => plugin.Id == pluginId);
|
||||
Assert.NotNull(storedPlugin);
|
||||
Assert.NotNull(storedPlugin!.SettingsJson);
|
||||
Dictionary<string, string>? storedSettings = JsonSerializer.Deserialize<Dictionary<string, string>>(storedPlugin.SettingsJson!);
|
||||
Assert.NotNull(storedSettings);
|
||||
Assert.Equal(maliciousValue, storedSettings!["Key"]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="PluginEntity"/> created by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the creator.</param>
|
||||
/// <returns>The Id of the seeded plugin.</returns>
|
||||
private async Task<Guid> SeedPluginAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
dbContext.Plugins.Add(new PluginEntity
|
||||
{
|
||||
Id = pluginId,
|
||||
Name = "Test Plugin",
|
||||
Author = "Test Author",
|
||||
Version = "1.0.0",
|
||||
Description = "A test plugin.",
|
||||
LoadStatus = PluginLoadStatus.Loaded,
|
||||
LoadError = null,
|
||||
SettingsJson = null,
|
||||
CreatedBy = userId,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
UpdatedBy = null
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
return pluginId;
|
||||
}
|
||||
}
|
||||
+20
-26
@@ -7,7 +7,6 @@ using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
@@ -74,41 +73,36 @@ public class ChangePasswordEndpointTests : IClassFixture<LuminaApiFactory>, IDis
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_WithValidRequest_ShouldNotLeakTimingInformation()
|
||||
public async Task ChangePassword_WithWrongCurrentPassword_ShouldReturnUniformForbiddenResponse()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateAndAuthenticateUser();
|
||||
Stopwatch stopwatch = new();
|
||||
List<long> timings = [];
|
||||
ChangePasswordRequest request = new(
|
||||
Username: user.Username,
|
||||
CurrentPassword: "WrongPass123!",
|
||||
NewPassword: "NewPass123!",
|
||||
NewPasswordConfirm: "NewPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
await Task.Delay(100);
|
||||
stopwatch.Restart();
|
||||
await _client.PostAsJsonAsync("/api/v1/auth/change-password", new ChangePasswordRequest(
|
||||
Username: user.Username,
|
||||
CurrentPassword: "WrongPass123!",
|
||||
NewPassword: "NewPass123!",
|
||||
NewPasswordConfirm: "NewPass123!"
|
||||
));
|
||||
stopwatch.Stop();
|
||||
timings.Add(stopwatch.ElapsedMilliseconds);
|
||||
}
|
||||
|
||||
timings.Sort();
|
||||
timings = timings.Skip(1).SkipLast(1).ToList(); // remove outliers
|
||||
HttpResponseMessage firstResponse = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
|
||||
string firstContent = await firstResponse.Content.ReadAsStringAsync();
|
||||
HttpResponseMessage secondResponse = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
|
||||
string secondContent = await secondResponse.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
double stdDev = CalculateStandardDeviation(timings);
|
||||
Assert.True(stdDev < 200);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, firstResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, secondResponse.StatusCode);
|
||||
AssertProblemDetail(firstContent, "General.Failure", "InvalidCurrentPassword");
|
||||
AssertProblemDetail(secondContent, "General.Failure", "InvalidCurrentPassword");
|
||||
}
|
||||
|
||||
private static double CalculateStandardDeviation(List<long> values)
|
||||
private void AssertProblemDetail(string content, string expectedTitle, string expectedDetail)
|
||||
{
|
||||
double average = values.Average();
|
||||
double sumOfSquaresOfDifferences = values.Select(value => (value - average) * (value - average)).Sum();
|
||||
return Math.Sqrt(sumOfSquaresOfDifferences / values.Count);
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(expectedTitle, problemDetails!["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
private async Task<UserEntity> CreateAndAuthenticateUser()
|
||||
|
||||
+22
-26
@@ -9,7 +9,6 @@ using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Net;
|
||||
@@ -110,36 +109,32 @@ public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WithValidCredentials_ShouldNotLeakTimingInformation()
|
||||
public async Task Login_WithUnknownUsernameAndWrongPassword_ShouldReturnIndistinguishableResponses()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUser();
|
||||
Stopwatch stopwatch = new();
|
||||
List<long> timings = [];
|
||||
// since this test is rigged to trigger the rate limiting, assign a different IP to it
|
||||
LoginRequest unknownUserRequest = new(
|
||||
Username: "nonexistent_user",
|
||||
Password: "TestPass123!"
|
||||
);
|
||||
LoginRequest wrongPasswordRequest = new(
|
||||
Username: user.Username,
|
||||
Password: "WrongPass123!"
|
||||
);
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.2");
|
||||
|
||||
// Act
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
await Task.Delay(100); // add small delay between requests
|
||||
stopwatch.Restart();
|
||||
await _client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(
|
||||
Username: user.Username,
|
||||
Password: "TestPass123!"
|
||||
));
|
||||
stopwatch.Stop();
|
||||
timings.Add(stopwatch.ElapsedMilliseconds);
|
||||
}
|
||||
// remove the highest and lowest values to account for outliers
|
||||
timings.Sort();
|
||||
timings = timings.Skip(1).SkipLast(1).ToList();
|
||||
HttpResponseMessage unknownUserResponse = await _client.PostAsJsonAsync("/api/v1/auth/login", unknownUserRequest);
|
||||
string unknownUserContent = await unknownUserResponse.Content.ReadAsStringAsync();
|
||||
HttpResponseMessage wrongPasswordResponse = await _client.PostAsJsonAsync("/api/v1/auth/login", wrongPasswordRequest);
|
||||
string wrongPasswordContent = await wrongPasswordResponse.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// check for timing consistency to prevent timing attacks
|
||||
double stdDev = CalculateStandardDeviation(timings);
|
||||
Assert.True(stdDev < 200);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, unknownUserResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, wrongPasswordResponse.StatusCode);
|
||||
AssertProblemDetail(unknownUserContent, "General.Failure", "InvalidUsernameOrPassword");
|
||||
AssertProblemDetail(wrongPasswordContent, "General.Failure", "InvalidUsernameOrPassword");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -247,11 +242,12 @@ public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
Assert.DoesNotContain("Exception", content);
|
||||
}
|
||||
|
||||
private double CalculateStandardDeviation(List<long> values)
|
||||
private void AssertProblemDetail(string content, string expectedTitle, string expectedDetail)
|
||||
{
|
||||
double average = values.Average();
|
||||
double sumOfSquaresOfDifferences = values.Select(value => (value - average) * (value - average)).Sum();
|
||||
return Math.Sqrt(sumOfSquaresOfDifferences / values.Count);
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(expectedTitle, problemDetails!["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
private async Task<UserEntity> CreateTestUser()
|
||||
|
||||
+17
-22
@@ -6,7 +6,6 @@ using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
@@ -42,34 +41,29 @@ public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_WithValidData_ShouldNotLeakTimingInformation()
|
||||
public async Task Register_WhenUsernameTaken_ShouldReturnUniformConflictResponse()
|
||||
{
|
||||
// Arrange
|
||||
Stopwatch stopwatch = new();
|
||||
List<long> timings = [];
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.6");
|
||||
RegistrationRequest request = new(
|
||||
Username: _testUsername,
|
||||
Password: "TestPass123!",
|
||||
PasswordConfirm: "TestPass123!"
|
||||
);
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.6");
|
||||
|
||||
// Act
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
await Task.Delay(100);
|
||||
stopwatch.Restart();
|
||||
await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||
stopwatch.Stop();
|
||||
timings.Add(stopwatch.ElapsedMilliseconds);
|
||||
}
|
||||
timings.Sort();
|
||||
timings = timings.Skip(1).SkipLast(1).ToList();
|
||||
HttpResponseMessage firstResponse = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||
HttpResponseMessage secondResponse = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||
string secondContent = await secondResponse.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
double stdDev = CalculateStandardDeviation(timings);
|
||||
Assert.True(stdDev < 200);
|
||||
Assert.Equal(HttpStatusCode.Created, firstResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Conflict, secondResponse.StatusCode);
|
||||
AssertProblemDetail(secondContent, "General.Conflict", "UsernameAlreadyExists");
|
||||
Assert.DoesNotContain("password", secondContent);
|
||||
Assert.DoesNotContain("hash", secondContent);
|
||||
Assert.DoesNotContain("salt", secondContent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -203,11 +197,12 @@ public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, IDisposabl
|
||||
Assert.DoesNotContain("salt", content);
|
||||
}
|
||||
|
||||
private double CalculateStandardDeviation(List<long> values)
|
||||
private void AssertProblemDetail(string content, string expectedTitle, string expectedDetail)
|
||||
{
|
||||
double average = values.Average();
|
||||
double sumOfSquaresOfDifferences = values.Select(value => (value - average) * (value - average)).Sum();
|
||||
return Math.Sqrt(sumOfSquaresOfDifferences / values.Count);
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(expectedTitle, problemDetails!["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
private async Task<UserEntity> CreateTestUser()
|
||||
|
||||
Reference in new issue
Block a user