mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 04:01:10 +00:00
Adds the security tests for the theming feature
This commit is contained in:
1 parent
02f27655f8
commit
531450b3db
9 files changed
+1400
No files matched your search
+132
@@ -0,0 +1,132 @@
|
||||
#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.Themes.Management.DeleteTheme;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>DELETE /api/v1/themes/{themeId}</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteThemeEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteThemeEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteThemeEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// a unique X-Forwarded-For isolates rate limiting state per test
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTheme_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/themes/{Guid.NewGuid():N}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteTheme_WhenAuthenticatedNonAdmin_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
string url = $"/api/v1/themes/{Guid.NewGuid():N}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync(url);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.Equal(url, problemDetails["instance"].GetString());
|
||||
Assert.True(problemDetails.ContainsKey("traceId"));
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("..%2F..%2Fevil")] // encoded slash traversal
|
||||
[InlineData("%2e%2e%2f%2e%2e%2fevil")] // encoded dot-slash traversal
|
||||
[InlineData("..%5Cevil")] // encoded backslash traversal
|
||||
[InlineData("..%2F")] // encoded trailing slash traversal
|
||||
public async Task DeleteTheme_WithPathTraversalInThemeId_ShouldReturnCleanNotFoundProblemDetails(string maliciousThemeId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
string url = $"/api/v1/themes/{maliciousThemeId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.DeleteAsync(url);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// note: some payloads are normalized away by the server before routing, producing an empty-body 404;
|
||||
// when the value reaches the handler, the failure must still be the generic theme-not-found problem
|
||||
if (!string.IsNullOrWhiteSpace(content))
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
|
||||
Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
}
|
||||
}
|
||||
+333
@@ -0,0 +1,333 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO.Compression;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Management.InstallTheme;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>POST /api/v1/themes</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class InstallThemeEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private const long MAX_ARCHIVE_BYTES = 8 * 1024 * 1024;
|
||||
private const string VALID_MANIFEST_JSON = """
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "valid-theme",
|
||||
"name": "Valid Theme",
|
||||
"description": "description",
|
||||
"author": "author",
|
||||
"version": "1.0.0",
|
||||
"templates": {
|
||||
"default": "templates/default.html"
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InstallThemeEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public InstallThemeEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// a unique X-Forwarded-For isolates rate limiting state per test
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallTheme_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/themes", 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/themes", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallTheme_WhenAuthenticatedNonAdmin_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
using MultipartFormDataContent form = CreateMultipartForm(Encoding.UTF8.GetBytes("not-a-zip"), "pack.zip", "application/zip");
|
||||
HttpResponseMessage response = await client.PostAsync("/api/v1/themes", form);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/themes", problemDetails["instance"].GetString());
|
||||
Assert.True(problemDetails.ContainsKey("traceId"));
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallTheme_WithNonZipBody_ShouldReturnCleanProblemDetails()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
|
||||
// Act
|
||||
using MultipartFormDataContent form = CreateMultipartForm(Encoding.UTF8.GetBytes("this is not a zip archive"), "pack.zip", "application/zip");
|
||||
HttpResponseMessage response = await client.PostAsync("/api/v1/themes", form);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Failure", problemDetails["title"].GetString());
|
||||
Assert.Equal("ThemeArchiveNotReadable", problemDetails["detail"].GetString());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallTheme_WithEmptyArchiveFile_ShouldReturnCleanPackageInvalidProblemDetails()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
|
||||
// Act
|
||||
// a multipart upload carrying a 0 byte archive reaches the theme service, which must reject it without crashing
|
||||
using MultipartFormDataContent form = CreateMultipartForm([], "pack.zip", "application/zip");
|
||||
HttpResponseMessage response = await client.PostAsync("/api/v1/themes", form);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.True(problemDetails["errors"].GetProperty("Theme.Package.Invalid").GetArrayLength() > 0);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallTheme_WithOversizedArchive_ShouldReturnCleanProblemDetails()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
|
||||
// Act
|
||||
using MultipartFormDataContent form = CreateMultipartForm(new byte[MAX_ARCHIVE_BYTES + 1], "pack.zip", "application/zip");
|
||||
HttpResponseMessage response = await client.PostAsync("/api/v1/themes", form);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.True(problemDetails["errors"].GetProperty("Theme.Archive.TooLarge").GetArrayLength() > 0);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallTheme_WithZipContainingTraversalEntry_ShouldReturnCleanProblemDetails()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
byte[] zipBytes = CreateZipWithEntries(new Dictionary<string, string>
|
||||
{
|
||||
["theme.json"] = VALID_MANIFEST_JSON,
|
||||
["templates/default.html"] = "<html><body>default</body></html>",
|
||||
[@"..\evil.txt"] = "evil" // path traversal entry inside the archive
|
||||
});
|
||||
|
||||
// Act
|
||||
using MultipartFormDataContent form = CreateMultipartForm(zipBytes, "pack.zip", "application/zip");
|
||||
HttpResponseMessage response = await client.PostAsync("/api/v1/themes", form);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.True(problemDetails["errors"].GetProperty("Theme.Package.Invalid").GetArrayLength() > 0);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallTheme_WithManifestDeclaringTraversalTemplate_ShouldReturnCleanProblemDetails()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
const string MALICIOUS_MANIFEST = """
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "evil-theme",
|
||||
"name": "Evil Theme",
|
||||
"description": "description",
|
||||
"author": "author",
|
||||
"version": "1.0.0",
|
||||
"templates": {
|
||||
"default": "templates/default.html",
|
||||
"admin": "../secret.html"
|
||||
}
|
||||
}
|
||||
""";
|
||||
byte[] zipBytes = CreateZipWithEntries(new Dictionary<string, string>
|
||||
{
|
||||
["theme.json"] = MALICIOUS_MANIFEST,
|
||||
["templates/default.html"] = "<html><body>default</body></html>"
|
||||
});
|
||||
|
||||
// Act
|
||||
using MultipartFormDataContent form = CreateMultipartForm(zipBytes, "pack.zip", "application/zip");
|
||||
HttpResponseMessage response = await client.PostAsync("/api/v1/themes", form);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.True(problemDetails["errors"].GetProperty("Theme.Package.Invalid").GetArrayLength() > 0);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallTheme_WithEmptyMultipartBody_ShouldReturnCleanValidationProblemDetails()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
using MultipartFormDataContent emptyForm = [];
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsync("/api/v1/themes", emptyForm);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a multipart form containing a single file part.
|
||||
/// </summary>
|
||||
/// <param name="fileBytes">The file content bytes.</param>
|
||||
/// <param name="fileName">The name of the uploaded file.</param>
|
||||
/// <param name="contentType">The content type of the uploaded file.</param>
|
||||
/// <returns>The multipart form content.</returns>
|
||||
private static MultipartFormDataContent CreateMultipartForm(byte[] fileBytes, string fileName, string contentType)
|
||||
{
|
||||
MultipartFormDataContent form = [];
|
||||
ByteArrayContent fileContent = new(fileBytes);
|
||||
fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
|
||||
form.Add(fileContent, "archive", fileName);
|
||||
return form;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds an in-memory ZIP archive from the given entry paths and contents.
|
||||
/// </summary>
|
||||
/// <param name="entries">The entry paths mapped to their contents.</param>
|
||||
/// <returns>The ZIP archive bytes.</returns>
|
||||
private static byte[] CreateZipWithEntries(IReadOnlyDictionary<string, string> entries)
|
||||
{
|
||||
using MemoryStream memoryStream = new();
|
||||
using (ZipArchive zipArchive = new(memoryStream, ZipArchiveMode.Create, leaveOpen: true))
|
||||
{
|
||||
foreach ((string path, string content) in entries)
|
||||
{
|
||||
ZipArchiveEntry entry = zipArchive.CreateEntry(path);
|
||||
using StreamWriter writer = new(entry.Open());
|
||||
writer.Write(content);
|
||||
}
|
||||
}
|
||||
|
||||
return memoryStream.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
}
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Requests.Themes;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
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.Themes.Management.SetCurrentTheme;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>PUT /api/v1/themes/current</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class SetCurrentThemeEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetCurrentThemeEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public SetCurrentThemeEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// a unique X-Forwarded-For isolates rate limiting state per test
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetCurrentTheme_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
SetCurrentThemeRequest request = new("some-theme");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/themes/current", 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/themes/current", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetCurrentTheme_WhenAuthenticatedNonAdmin_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
SetCurrentThemeRequest request = new("some-theme");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/themes/current", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.Equal("/api/v1/themes/current", problemDetails["instance"].GetString());
|
||||
Assert.True(problemDetails.ContainsKey("traceId"));
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("../evil")] // dot-dot path traversal
|
||||
[InlineData("..\\..\\evil")] // backslash path traversal
|
||||
[InlineData("/etc/passwd")] // absolute path traversal
|
||||
[InlineData("C:\\windows\\system32")] // absolute windows path traversal
|
||||
[InlineData("' OR '1'='1")] // SQL injection attempt
|
||||
public async Task SetCurrentTheme_WithPathTraversalInThemeId_ShouldReturnCleanNotFoundProblemDetails(string maliciousThemeId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
SetCurrentThemeRequest request = new(maliciousThemeId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/themes/current", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
|
||||
Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString());
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
#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.Themes.Queries.GetCurrentTheme;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/api/v1/themes/current</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetCurrentThemeEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetCurrentThemeEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetCurrentThemeEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
// a unique X-Forwarded-For isolates rate limiting state per test
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetCurrentTheme_WhenAnonymous_ShouldNotRequireAuthenticationOrLeakInternalDetails()
|
||||
{
|
||||
// Arrange
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/themes/current");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// the route is AllowAnonymous, so anonymous callers must never be challenged for credentials
|
||||
Assert.NotEqual(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// when no active theme exists yet, the failure must be a clean, generic 404 that discloses nothing internal
|
||||
if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
|
||||
Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
#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.Themes.Queries.GetThemeArchive;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/api/v1/themes/{themeId}/archive</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetThemeArchiveEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetThemeArchiveEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetThemeArchiveEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// a unique X-Forwarded-For isolates rate limiting state per test
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThemeArchive_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/themes/{Guid.NewGuid():N}/archive";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("..%2F..%2Fevil")] // encoded slash traversal
|
||||
[InlineData("%2e%2e%2f%2e%2e%2fevil")] // encoded dot-slash traversal
|
||||
[InlineData("..%5Cevil")] // encoded backslash traversal
|
||||
[InlineData("..%2F")] // encoded trailing slash traversal
|
||||
public async Task GetThemeArchive_WithPathTraversalInThemeId_ShouldReturnCleanNotFoundProblemDetails(string maliciousThemeId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
string url = $"/api/v1/themes/{maliciousThemeId}/archive";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync(url);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// note: some payloads are normalized away by the server before routing, producing an empty-body 404;
|
||||
// when the value reaches the handler, the failure must still be the generic theme-not-found problem
|
||||
if (!string.IsNullOrWhiteSpace(content))
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
|
||||
Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
}
|
||||
}
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Themes;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
|
||||
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.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Queries.GetThemeAsset;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/api/v1/themes/{themeId}/assets/{*assetPath}</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetThemeAssetEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private const string DECOY_FILE_NAME = "decoy-secret.txt";
|
||||
private const string DECOY_CONTENT = "DECOY-SECRET-CONTENT";
|
||||
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly string _themeId;
|
||||
private readonly ThemeEntityFixture _themeEntityFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetThemeAssetEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetThemeAssetEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// a unique X-Forwarded-For isolates rate limiting state per test
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
_themeId = $"testtheme{Guid.NewGuid():N}";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThemeAsset_WhenThemeDoesNotExist_ShouldReturnCleanNotFoundProblemDetails()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/themes/does-not-exist/assets/logo.txt";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
|
||||
Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString());
|
||||
Assert.Equal(url, problemDetails["instance"].GetString());
|
||||
Assert.True(problemDetails.ContainsKey("traceId"));
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("..%2F..%2Fevil.txt")] // encoded slash path traversal
|
||||
[InlineData("%2e%2e%2f%2e%2e%2fevil.txt")] // encoded dot-slash path traversal
|
||||
[InlineData("..%5C..%5Cevil.txt")] // encoded backslash path traversal
|
||||
[InlineData("assets%2F..%2F..%2Fevil.txt")] // traversal hiding behind the assets prefix
|
||||
[InlineData("C:%5Cwindows%5Csystem32%5Cdrivers%5Cetc%5Chosts")] // absolute windows path
|
||||
[InlineData("..%2F..%2F..%2F..%2Fdecoy-secret.txt")] // deep traversal targeting a decoy file outside the pack
|
||||
public async Task GetThemeAsset_WithEncodedPathTraversalInAssetPath_ShouldReturnPackageInvalid(string maliciousAssetPath)
|
||||
{
|
||||
// Arrange
|
||||
await SeedThemeAsync();
|
||||
EnsureThemePackOnDisk();
|
||||
EnsureDecoyFileOnDisk();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/themes/{_themeId}/assets/{maliciousAssetPath}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
// the encoded traversal is rejected either by the server before it reaches the handler (403) or by the theme service validation (422);
|
||||
// in both cases it must be a clean client error that never serves or leaks the decoy
|
||||
Assert.True(response.StatusCode >= HttpStatusCode.BadRequest && response.StatusCode < HttpStatusCode.InternalServerError, $"Unexpected status code {response.StatusCode}.");
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(DECOY_CONTENT, content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThemeAsset_WithRawPathTraversalInAssetPath_ShouldNotLeakOrServeOutsideThemePack()
|
||||
{
|
||||
// Arrange
|
||||
await SeedThemeAsync();
|
||||
EnsureThemePackOnDisk();
|
||||
EnsureDecoyFileOnDisk();
|
||||
|
||||
// Act
|
||||
// note: Kestrel normalizes literal dot-segments out of the raw path, so the request is re-routed or rejected before the handler
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/themes/{_themeId}/assets/../evil.txt");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(DECOY_CONTENT, content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("..%2F..%2Fevil")] // encoded slash traversal
|
||||
[InlineData("%2e%2e%2f%2e%2e%2fevil")] // encoded dot-slash traversal
|
||||
[InlineData("..%5Cevil")] // encoded backslash traversal
|
||||
[InlineData("..%2F")] // encoded trailing slash traversal
|
||||
public async Task GetThemeAsset_WithPathTraversalInThemeId_ShouldReturnCleanNotFoundProblemDetails(string maliciousThemeId)
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/themes/{maliciousThemeId}/assets/logo.txt";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// note: some payloads are normalized away by the server before routing, producing an empty-body 404;
|
||||
// when the value reaches the handler, the failure must still be the generic theme-not-found problem
|
||||
if (!string.IsNullOrWhiteSpace(content))
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
|
||||
Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="ThemeEntity"/> with the unique test theme id.
|
||||
/// </summary>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedThemeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Themes.Add(_themeEntityFixture.Create(themeId: _themeId, isDeleted: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a valid theme pack for the unique test theme into the server storage directory.
|
||||
/// </summary>
|
||||
private void EnsureThemePackOnDisk()
|
||||
{
|
||||
string themeRoot = Path.Combine(AppContext.BaseDirectory, "themes", _themeId);
|
||||
Directory.CreateDirectory(Path.Combine(themeRoot, "templates"));
|
||||
Directory.CreateDirectory(Path.Combine(themeRoot, "assets"));
|
||||
string manifest = $$"""
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "{{_themeId}}",
|
||||
"name": "Test Theme",
|
||||
"description": "Test theme description",
|
||||
"author": "Tester",
|
||||
"version": "1.0.0",
|
||||
"templates": {
|
||||
"default": "templates/default.html",
|
||||
"home": "templates/home.html"
|
||||
}
|
||||
}
|
||||
""";
|
||||
File.WriteAllText(Path.Combine(themeRoot, "theme.json"), manifest);
|
||||
File.WriteAllText(Path.Combine(themeRoot, "templates", "default.html"), "<html><body>default-template</body></html>");
|
||||
File.WriteAllText(Path.Combine(themeRoot, "templates", "home.html"), "<html><body>home-template</body></html>");
|
||||
File.WriteAllText(Path.Combine(themeRoot, "assets", "logo.txt"), "logo-content");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a decoy file outside any theme pack, used to prove traversal payloads never escape the pack root.
|
||||
/// </summary>
|
||||
private static void EnsureDecoyFileOnDisk()
|
||||
{
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, DECOY_FILE_NAME), DECOY_CONTENT);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the seeded theme, its pack directory, and the decoy file.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
ThemeEntity? theme = dbContext.Themes.FirstOrDefault(candidate => candidate.ThemeId == _themeId);
|
||||
if (theme is not null)
|
||||
{
|
||||
dbContext.Themes.Remove(theme);
|
||||
dbContext.SaveChanges();
|
||||
}
|
||||
|
||||
string themeRoot = Path.Combine(AppContext.BaseDirectory, "themes", _themeId);
|
||||
if (Directory.Exists(themeRoot))
|
||||
Directory.Delete(themeRoot, recursive: true);
|
||||
|
||||
string decoyPath = Path.Combine(AppContext.BaseDirectory, DECOY_FILE_NAME);
|
||||
if (File.Exists(decoyPath))
|
||||
File.Delete(decoyPath);
|
||||
|
||||
_client.Dispose();
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
#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.Themes.Queries.GetThemeSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/api/v1/themes/settings</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetThemeSettingsEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetThemeSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetThemeSettingsEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
// a unique X-Forwarded-For isolates rate limiting state per test
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThemeSettings_WhenAnonymous_ShouldNotRequireAuthentication()
|
||||
{
|
||||
// Arrange
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/themes/settings");
|
||||
|
||||
// Assert
|
||||
// the route is AllowAnonymous, so anonymous callers must never be challenged for credentials
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThemeSettings_WhenAnonymous_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/themes/settings");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
}
|
||||
}
|
||||
+235
@@ -0,0 +1,235 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Themes;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
|
||||
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.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Queries.GetThemeTemplate;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/api/v1/themes/{themeId}/templates/{*pageKey}</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetThemeTemplateEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private const string DECOY_FILE_NAME = "decoy-secret.txt";
|
||||
private const string DECOY_CONTENT = "DECOY-SECRET-CONTENT";
|
||||
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly string _themeId;
|
||||
private readonly ThemeEntityFixture _themeEntityFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetThemeTemplateEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetThemeTemplateEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// a unique X-Forwarded-For isolates rate limiting state per test
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
_themeId = $"testtheme{Guid.NewGuid():N}";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThemeTemplate_WhenThemeDoesNotExist_ShouldReturnCleanNotFoundProblemDetails()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/themes/does-not-exist/templates/home";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
|
||||
Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString());
|
||||
Assert.Equal(url, problemDetails["instance"].GetString());
|
||||
Assert.True(problemDetails.ContainsKey("traceId"));
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("..%2F..%2Fevil.html")] // encoded slash path traversal
|
||||
[InlineData("%2e%2e%2f%2e%2e%2fevil.html")] // encoded dot-slash path traversal
|
||||
[InlineData("..%5C..%5Cevil.html")] // encoded backslash path traversal
|
||||
[InlineData("..%2F..%2F..%2F..%2Fdecoy-secret.txt")] // deep traversal targeting a decoy file outside the pack
|
||||
public async Task GetThemeTemplate_WithEncodedPathTraversalInPageKey_ShouldOnlyServeInPackTemplates(string maliciousPageKey)
|
||||
{
|
||||
// Arrange
|
||||
await SeedThemeAsync();
|
||||
EnsureThemePackOnDisk();
|
||||
EnsureDecoyFileOnDisk();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/themes/{_themeId}/templates/{maliciousPageKey}");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(DECOY_CONTENT, content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// a successful render must only ever come from a template inside the theme pack
|
||||
if (response.StatusCode == HttpStatusCode.OK)
|
||||
Assert.Contains("default-template", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThemeTemplate_WithRawPathTraversalInPageKey_ShouldNotLeakOrError()
|
||||
{
|
||||
// Arrange
|
||||
await SeedThemeAsync();
|
||||
EnsureThemePackOnDisk();
|
||||
EnsureDecoyFileOnDisk();
|
||||
|
||||
// Act
|
||||
// note: Kestrel normalizes literal dot-segments out of the raw path, so the request is re-routed or rejected before the handler
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/themes/{_themeId}/templates/../evil.html");
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(DECOY_CONTENT, content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("..%2F..%2Fevil")] // encoded slash traversal
|
||||
[InlineData("%2e%2e%2f%2e%2e%2fevil")] // encoded dot-slash traversal
|
||||
[InlineData("..%5Cevil")] // encoded backslash traversal
|
||||
[InlineData("..%2F")] // encoded trailing slash traversal
|
||||
public async Task GetThemeTemplate_WithPathTraversalInThemeId_ShouldReturnCleanNotFoundProblemDetails(string maliciousThemeId)
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/themes/{maliciousThemeId}/templates/home";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// note: some payloads are normalized away by the server before routing, producing an empty-body 404;
|
||||
// when the value reaches the handler, the failure must still be the generic theme-not-found problem
|
||||
if (!string.IsNullOrWhiteSpace(content))
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.NotFound", problemDetails["title"].GetString());
|
||||
Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a <see cref="ThemeEntity"/> with the unique test theme id.
|
||||
/// </summary>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedThemeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
dbContext.Themes.Add(_themeEntityFixture.Create(themeId: _themeId, isDeleted: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a valid theme pack for the unique test theme into the server storage directory.
|
||||
/// </summary>
|
||||
private void EnsureThemePackOnDisk()
|
||||
{
|
||||
string themeRoot = Path.Combine(AppContext.BaseDirectory, "themes", _themeId);
|
||||
Directory.CreateDirectory(Path.Combine(themeRoot, "templates"));
|
||||
Directory.CreateDirectory(Path.Combine(themeRoot, "assets"));
|
||||
string manifest = $$"""
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "{{_themeId}}",
|
||||
"name": "Test Theme",
|
||||
"description": "Test theme description",
|
||||
"author": "Tester",
|
||||
"version": "1.0.0",
|
||||
"templates": {
|
||||
"default": "templates/default.html",
|
||||
"home": "templates/home.html"
|
||||
}
|
||||
}
|
||||
""";
|
||||
File.WriteAllText(Path.Combine(themeRoot, "theme.json"), manifest);
|
||||
File.WriteAllText(Path.Combine(themeRoot, "templates", "default.html"), "<html><body>default-template</body></html>");
|
||||
File.WriteAllText(Path.Combine(themeRoot, "templates", "home.html"), "<html><body>home-template</body></html>");
|
||||
File.WriteAllText(Path.Combine(themeRoot, "assets", "logo.txt"), "logo-content");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a decoy file outside any theme pack, used to prove traversal payloads never escape the pack root.
|
||||
/// </summary>
|
||||
private static void EnsureDecoyFileOnDisk()
|
||||
{
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, DECOY_FILE_NAME), DECOY_CONTENT);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the seeded theme, its pack directory, and the decoy file.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
ThemeEntity? theme = dbContext.Themes.FirstOrDefault(candidate => candidate.ThemeId == _themeId);
|
||||
if (theme is not null)
|
||||
{
|
||||
dbContext.Themes.Remove(theme);
|
||||
dbContext.SaveChanges();
|
||||
}
|
||||
|
||||
string themeRoot = Path.Combine(AppContext.BaseDirectory, "themes", _themeId);
|
||||
if (Directory.Exists(themeRoot))
|
||||
Directory.Delete(themeRoot, recursive: true);
|
||||
|
||||
string decoyPath = Path.Combine(AppContext.BaseDirectory, DECOY_FILE_NAME);
|
||||
if (File.Exists(decoyPath))
|
||||
File.Delete(decoyPath);
|
||||
|
||||
_client.Dispose();
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
#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.Themes.Queries.GetThemes;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <c>/api/v1/themes</c> route.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetThemesEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetThemesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetThemesEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// a unique X-Forwarded-For isolates rate limiting state per test
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThemes_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/themes");
|
||||
|
||||
// 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/themes", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetThemes_WhenAuthenticated_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync("/api/v1/themes");
|
||||
|
||||
// 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);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user