diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs new file mode 100644 index 00000000..48fdcb60 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the DELETE /api/v1/themes/{themeId} route. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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? problemDetails = JsonSerializer.Deserialize>(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? problemDetails = JsonSerializer.Deserialize>(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? problemDetails = JsonSerializer.Deserialize>(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()); + } + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs new file mode 100644 index 00000000..b93999b5 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the POST /api/v1/themes route. +/// +[ExcludeFromCodeCoverage] +public class InstallThemeEndpointTests : IClassFixture, 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 + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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? problemDetails = JsonSerializer.Deserialize>(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? problemDetails = JsonSerializer.Deserialize>(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? problemDetails = JsonSerializer.Deserialize>(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? problemDetails = JsonSerializer.Deserialize>(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? problemDetails = JsonSerializer.Deserialize>(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 + { + ["theme.json"] = VALID_MANIFEST_JSON, + ["templates/default.html"] = "default", + [@"..\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? problemDetails = JsonSerializer.Deserialize>(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 + { + ["theme.json"] = MALICIOUS_MANIFEST, + ["templates/default.html"] = "default" + }); + + // 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? problemDetails = JsonSerializer.Deserialize>(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? problemDetails = JsonSerializer.Deserialize>(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); + } + + /// + /// Builds a multipart form containing a single file part. + /// + /// The file content bytes. + /// The name of the uploaded file. + /// The content type of the uploaded file. + /// The multipart form content. + 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; + } + + /// + /// Builds an in-memory ZIP archive from the given entry paths and contents. + /// + /// The entry paths mapped to their contents. + /// The ZIP archive bytes. + private static byte[] CreateZipWithEntries(IReadOnlyDictionary 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(); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs new file mode 100644 index 00000000..9f550895 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the PUT /api/v1/themes/current route. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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? problemDetails = JsonSerializer.Deserialize>(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? problemDetails = JsonSerializer.Deserialize>(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? problemDetails = JsonSerializer.Deserialize>(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); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs new file mode 100644 index 00000000..2eee95fb --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the /api/v1/themes/current route. +/// +[ExcludeFromCodeCoverage] +public class GetCurrentThemeEndpointTests : IClassFixture, IDisposable +{ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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? problemDetails = JsonSerializer.Deserialize>(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()); + } + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs new file mode 100644 index 00000000..4228c897 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the /api/v1/themes/{themeId}/archive route. +/// +[ExcludeFromCodeCoverage] +public class GetThemeArchiveEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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? problemDetails = JsonSerializer.Deserialize>(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? problemDetails = JsonSerializer.Deserialize>(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()); + } + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs new file mode 100644 index 00000000..0a3eadf2 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the /api/v1/themes/{themeId}/assets/{*assetPath} route. +/// +[ExcludeFromCodeCoverage] +public class GetThemeAssetEndpointTests : IClassFixture, 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 + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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? problemDetails = JsonSerializer.Deserialize>(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? problemDetails = JsonSerializer.Deserialize>(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()); + } + } + + /// + /// Seeds a with the unique test theme id. + /// + /// A task representing the asynchronous operation. + private async Task SeedThemeAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Themes.Add(_themeEntityFixture.Create(themeId: _themeId, isDeleted: false)); + await dbContext.SaveChangesAsync(); + } + + /// + /// Writes a valid theme pack for the unique test theme into the server storage directory. + /// + 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"), "default-template"); + File.WriteAllText(Path.Combine(themeRoot, "templates", "home.html"), "home-template"); + File.WriteAllText(Path.Combine(themeRoot, "assets", "logo.txt"), "logo-content"); + } + + /// + /// Writes a decoy file outside any theme pack, used to prove traversal payloads never escape the pack root. + /// + private static void EnsureDecoyFileOnDisk() + { + File.WriteAllText(Path.Combine(AppContext.BaseDirectory, DECOY_FILE_NAME), DECOY_CONTENT); + } + + /// + /// Removes the seeded theme, its pack directory, and the decoy file. + /// + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs new file mode 100644 index 00000000..93c44b12 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the /api/v1/themes/settings route. +/// +[ExcludeFromCodeCoverage] +public class GetThemeSettingsEndpointTests : IClassFixture, IDisposable +{ + private readonly HttpClient _client; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs new file mode 100644 index 00000000..cafced8f --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the /api/v1/themes/{themeId}/templates/{*pageKey} route. +/// +[ExcludeFromCodeCoverage] +public class GetThemeTemplateEndpointTests : IClassFixture, 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 + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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? problemDetails = JsonSerializer.Deserialize>(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? problemDetails = JsonSerializer.Deserialize>(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()); + } + } + + /// + /// Seeds a with the unique test theme id. + /// + /// A task representing the asynchronous operation. + private async Task SeedThemeAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Themes.Add(_themeEntityFixture.Create(themeId: _themeId, isDeleted: false)); + await dbContext.SaveChangesAsync(); + } + + /// + /// Writes a valid theme pack for the unique test theme into the server storage directory. + /// + 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"), "default-template"); + File.WriteAllText(Path.Combine(themeRoot, "templates", "home.html"), "home-template"); + File.WriteAllText(Path.Combine(themeRoot, "assets", "logo.txt"), "logo-content"); + } + + /// + /// Writes a decoy file outside any theme pack, used to prove traversal payloads never escape the pack root. + /// + private static void EnsureDecoyFileOnDisk() + { + File.WriteAllText(Path.Combine(AppContext.BaseDirectory, DECOY_FILE_NAME), DECOY_CONTENT); + } + + /// + /// Removes the seeded theme, its pack directory, and the decoy file. + /// + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs new file mode 100644 index 00000000..77dfddc4 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the /api/v1/themes route. +/// +[ExcludeFromCodeCoverage] +public class GetThemesEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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? problemDetails = JsonSerializer.Deserialize>(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); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +}