mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 12:11:10 +00:00
Renames project paths from Lumina to Nemera
This commit is contained in:
1 parent
ce6fddb4c9
commit
0f659a4877
6450 files changed
No files matched your search
+202
@@ -0,0 +1,202 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="ChangePasswordEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ChangePasswordEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly ChangePasswordRequestFixture _changePasswordRequestFixture = new();
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
private readonly string _testUsername;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ChangePasswordEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.12");
|
||||
_testUsername = $"testuser_{Guid.NewGuid()}";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_WithoutAuthentication_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
ChangePasswordRequest request = _changePasswordRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
currentPassword: "OldPass123!",
|
||||
newPassword: "NewPass123!",
|
||||
newPasswordConfirm: "NewPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", 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/auth/change-password", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_WithWrongCurrentPassword_ShouldReturnUniformForbiddenResponse()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateAndAuthenticateUser();
|
||||
ChangePasswordRequest request = _changePasswordRequestFixture.Create(
|
||||
username: user.Username,
|
||||
currentPassword: "WrongPass123!",
|
||||
newPassword: "NewPass123!",
|
||||
newPasswordConfirm: "NewPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage firstResponse = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
|
||||
string firstContent = await firstResponse.Content.ReadAsStringAsync();
|
||||
HttpResponseMessage secondResponse = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
|
||||
string secondContent = await secondResponse.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, firstResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, secondResponse.StatusCode);
|
||||
AssertProblemDetail(firstContent, "General.Failure", "InvalidCurrentPassword");
|
||||
AssertProblemDetail(secondContent, "General.Failure", "InvalidCurrentPassword");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Users--")] // Destructive injection.
|
||||
[InlineData("' OR '1'='1")] // Boolean-based injection.
|
||||
public async Task ChangePassword_WithSQLInjectionInUsername_ShouldNotCorruptOrDeleteData(string maliciousUsername)
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateAndAuthenticateUser();
|
||||
string originalPasswordHash = user.Password;
|
||||
ChangePasswordRequest request = _changePasswordRequestFixture.Create(
|
||||
username: maliciousUsername,
|
||||
currentPassword: "TestPass123!",
|
||||
newPassword: "NewPass123!",
|
||||
newPasswordConfirm: "NewPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
|
||||
|
||||
// Assert
|
||||
// The malicious username is queried by GetByUsernameAsync, so it must never be executed against the database;
|
||||
// if a boolean-injection regression returned the only user in the database, the current password would match and
|
||||
// the password would change, so the response must be a failure and the stored password hash must be unchanged.
|
||||
Assert.NotEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity? storedUser = await dbContext.Users.FirstOrDefaultAsync(candidate => candidate.Id == user.Id);
|
||||
Assert.NotNull(storedUser);
|
||||
Assert.Equal(originalPasswordHash, storedUser!.Password);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the given <paramref name="content"/> is a problem detail with the expected title and detail.
|
||||
/// </summary>
|
||||
/// <param name="content">The response content to assert.</param>
|
||||
/// <param name="expectedTitle">The expected title of the problem detail.</param>
|
||||
/// <param name="expectedDetail">The expected detail of the problem detail.</param>
|
||||
private void AssertProblemDetail(string content, string expectedTitle, string expectedDetail)
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(expectedTitle, problemDetails!["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user, authenticates it on the client, and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateAndAuthenticateUser()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// Create test user.
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
// Authenticate user.
|
||||
LoginRequest loginRequest = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TestPass123!",
|
||||
includeTotpCode: false
|
||||
);
|
||||
|
||||
HttpResponseMessage loginResponse = await _client.PostAsJsonAsync("/api/v1/auth/login", loginRequest);
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
|
||||
// Set auth header for subsequent requests.
|
||||
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token);
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
|
||||
if (user is not null)
|
||||
{
|
||||
dbContext.Users.Remove(user);
|
||||
dbContext.SaveChanges();
|
||||
}
|
||||
|
||||
_client.DefaultRequestHeaders.Authorization = null;
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetUsersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUsersEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUsersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUsersEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUsers_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/auth/users");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string responseContent = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseContent, _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/auth/users", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
}
|
||||
+313
@@ -0,0 +1,313 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Authentication;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="LoginEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
private readonly ICryptographyService _cryptographyService;
|
||||
private readonly TotpTokenGenerator _totpTokenGenerator = new();
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly string _testUsername;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LoginEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public LoginEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// Set a fake IP for this test instance.
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.1");
|
||||
_testUsername = $"testuser_{Guid.NewGuid()}";
|
||||
|
||||
using IServiceScope scope = apiFactory.Services.CreateScope();
|
||||
_cryptographyService = scope.ServiceProvider.GetRequiredService<ICryptographyService>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WithValidCredentials_ShouldAuthenticateSuccessfully()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUser();
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TestPass123!"
|
||||
);
|
||||
DateTimeOffset beforeRequest = DateTimeOffset.UtcNow;
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.10");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
|
||||
// Assert
|
||||
JwtSecurityTokenHandler handler = new();
|
||||
JwtSecurityToken token = handler.ReadJwtToken(result!.Token);
|
||||
|
||||
string expValue = token.Claims.First(c => c.Type == "exp").Value; // Get token claims.
|
||||
DateTimeOffset tokenExpiration = DateTimeOffset.FromUnixTimeSeconds(long.Parse(expValue));
|
||||
DateTimeOffset expectedExpiration = beforeRequest.AddMinutes(15);
|
||||
|
||||
// Verify token duration (should be 15 minutes from request time - expiration value is set in tests setup class).
|
||||
TimeSpan allowedVariance = TimeSpan.FromSeconds(30); // Allow for processing time.
|
||||
TimeSpan actualDifference = tokenExpiration - beforeRequest;
|
||||
TimeSpan expectedDifference = TimeSpan.FromMinutes(15);
|
||||
|
||||
Assert.True(Math.Abs((actualDifference - expectedDifference).TotalSeconds) < allowedVariance.TotalSeconds);
|
||||
|
||||
Assert.Equal("HS256", token.Header.Alg);
|
||||
Assert.Contains(token.Claims, c => c.Type == "sub" && c.Value == user.Id.ToString());
|
||||
Assert.Contains(token.Claims, c => c.Type == "unique_name" && c.Value == user.Username);
|
||||
Assert.Contains(token.Claims, c => c.Type == "jti");
|
||||
Assert.Contains(token.Claims, c => c.Type == "iss" && c.Value == "Lumina");
|
||||
Assert.Contains(token.Claims, c => c.Type == "aud" && c.Value == "Lumina");
|
||||
|
||||
Assert.DoesNotContain("password", content);
|
||||
Assert.DoesNotContain("hash", content);
|
||||
Assert.DoesNotContain("salt", content);
|
||||
|
||||
// TODO: implement more strict security checks:
|
||||
// // check security headers
|
||||
// response.Headers.Should().ContainKey("X-Content-Type-Options")
|
||||
// .WhoseValue.Should().Contain("nosniff");
|
||||
// response.Headers.Should().ContainKey("X-Frame-Options")
|
||||
// .WhoseValue.Should().Contain("DENY");
|
||||
// response.Headers.Should().ContainKey("X-XSS-Protection")
|
||||
// .WhoseValue.Should().Contain("1; mode=block");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WithUnknownUsernameAndWrongPassword_ShouldReturnIndistinguishableResponses()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUser();
|
||||
LoginRequest unknownUserRequest = _loginRequestFixture.Create(
|
||||
username: "nonexistent_user",
|
||||
password: "TestPass123!"
|
||||
);
|
||||
LoginRequest wrongPasswordRequest = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "WrongPass123!"
|
||||
);
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.2");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage unknownUserResponse = await _client.PostAsJsonAsync("/api/v1/auth/login", unknownUserRequest);
|
||||
string unknownUserContent = await unknownUserResponse.Content.ReadAsStringAsync();
|
||||
HttpResponseMessage wrongPasswordResponse = await _client.PostAsJsonAsync("/api/v1/auth/login", wrongPasswordRequest);
|
||||
string wrongPasswordContent = await wrongPasswordResponse.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, unknownUserResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, wrongPasswordResponse.StatusCode);
|
||||
AssertProblemDetail(unknownUserContent, "General.Failure", "InvalidUsernameOrPassword");
|
||||
AssertProblemDetail(wrongPasswordContent, "General.Failure", "InvalidUsernameOrPassword");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WhenRateLimitExceeded_ShouldReturnTooManyRequests()
|
||||
{
|
||||
// Arrange
|
||||
// Set a fake IP for this test instance.
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.3");
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: "testuser",
|
||||
password: "TestPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
List<HttpResponseMessage> responses = [];
|
||||
for (int i = 0; i < 11; i++) // Exceed the 10 request limit.
|
||||
responses.Add(await _client.PostAsJsonAsync("/api/v1/auth/login", request));
|
||||
|
||||
// Assert
|
||||
HttpResponseMessage lastResponse = responses.Last();
|
||||
Assert.Equal(HttpStatusCode.TooManyRequests, lastResponse.StatusCode);
|
||||
string content = await lastResponse.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status429TooManyRequests, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc6585#section-4", problemDetails["type"].GetString());
|
||||
Assert.Equal("TooManyRequests", problemDetails["title"].GetString());
|
||||
Assert.Equal("TooManyRequests", problemDetails["detail"].GetString());
|
||||
Assert.Equal("900", problemDetails["retryAfter"].GetString());
|
||||
|
||||
Assert.True(lastResponse.Headers.Contains("X-RateLimit-Limit"));
|
||||
Assert.True(lastResponse.Headers.Contains("X-RateLimit-Reset"));
|
||||
Assert.True(lastResponse.Headers.Contains("X-RateLimit-Remaining"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // Basic SQL injection.
|
||||
[InlineData("admin'--")] // Comment injection.
|
||||
[InlineData("' UNION SELECT * FROM Users--")] // Union injection.
|
||||
[InlineData("'; DROP TABLE Users--")] // Destructive injection.
|
||||
[InlineData("' WAITFOR DELAY '0:0:10'--")] // Time-based injection.
|
||||
public async Task Login_WithSQLInjectionAttempt_ShouldRemainSecure(string maliciousUsername)
|
||||
{
|
||||
// Arrange
|
||||
UserEntity legitimateUser = await CreateTestUser();
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: maliciousUsername,
|
||||
password: "Abcd123$"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content);
|
||||
Assert.DoesNotContain(legitimateUser.Username, content); // Shouldn't expose other usernames.
|
||||
Assert.DoesNotContain(legitimateUser.Password, content); // Shouldn't expose password hashes.
|
||||
|
||||
// The injected statement must never be executed: the Users table and the seeded user must still be there.
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.NotNull(await dbContext.Users.FirstOrDefaultAsync(user => user.Id == legitimateUser.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WithSQLInjectionInValidUser_ShouldRemainSecure()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUser();
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "' OR '1'='1"
|
||||
);
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.11");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WithInjectionInTotpCode_ShouldRemainSecure()
|
||||
{
|
||||
// Arrange
|
||||
UserEntity user = await CreateTestUserWithTotp();
|
||||
LoginRequest request = _loginRequestFixture.Create(
|
||||
username: user.Username,
|
||||
password: "TestPass123!",
|
||||
totpCode: "' OR '1'='1"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the given <paramref name="content"/> is a problem detail with the expected title and detail.
|
||||
/// </summary>
|
||||
/// <param name="content">The response content to assert.</param>
|
||||
/// <param name="expectedTitle">The expected title of the problem detail.</param>
|
||||
/// <param name="expectedDetail">The expected detail of the problem detail.</param>
|
||||
private void AssertProblemDetail(string content, string expectedTitle, string expectedDetail)
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(expectedTitle, problemDetails!["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user without a TOTP secret in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateTestUser()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user with a TOTP secret in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateTestUserWithTotp()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
byte[] totpSecret = _totpTokenGenerator.GenerateSecret();
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret));
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return user;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
|
||||
if (user is not null)
|
||||
{
|
||||
dbContext.Users.Remove(user);
|
||||
dbContext.SaveChanges();
|
||||
}
|
||||
}
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="RecoverPasswordEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RecoverPasswordEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly string _testUsername;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RecoverPasswordEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public RecoverPasswordEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
// Set a fake IP for this test instance.
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.4");
|
||||
_testUsername = $"testuser_{Guid.NewGuid()}";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecoverPassword_WhenRateLimitExceeded_ShouldReturnTooManyRequests()
|
||||
{
|
||||
// Arrange
|
||||
RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(
|
||||
username: "testuser",
|
||||
totpCode: "123456"
|
||||
);
|
||||
|
||||
// Act
|
||||
List<HttpResponseMessage> responses = [];
|
||||
for (int i = 0; i < 11; i++) // Exceed the 10 request limit.
|
||||
responses.Add(await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request));
|
||||
|
||||
// Assert
|
||||
HttpResponseMessage lastResponse = responses.Last();
|
||||
Assert.Equal(HttpStatusCode.TooManyRequests, lastResponse.StatusCode);
|
||||
string content = await lastResponse.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status429TooManyRequests, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc6585#section-4", problemDetails["type"].GetString());
|
||||
Assert.Equal("TooManyRequests", problemDetails["title"].GetString());
|
||||
Assert.Equal("TooManyRequests", problemDetails["detail"].GetString());
|
||||
Assert.Equal("900", problemDetails["retryAfter"].GetString());
|
||||
|
||||
Assert.True(lastResponse.Headers.Contains("X-RateLimit-Limit"));
|
||||
Assert.True(lastResponse.Headers.Contains("X-RateLimit-Reset"));
|
||||
Assert.True(lastResponse.Headers.Contains("X-RateLimit-Remaining"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE Users--")] // Destructive injection.
|
||||
[InlineData("' OR '1'='1")] // Boolean-based injection.
|
||||
public async Task RecoverPassword_WithSQLInjectionInUsername_ShouldNotCorruptOrDeleteData(string maliciousUsername)
|
||||
{
|
||||
// Arrange
|
||||
// Use a dedicated unique IP, so the rate-limit test (which exhausts the 10-permit window on its own IP)
|
||||
// cannot run first and 429 this test; the NotEqual(TooManyRequests) assertion below guards against any collision.
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
client.DefaultRequestHeaders.Clear();
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
|
||||
UserEntity legitimateUser = await CreateTestUser();
|
||||
RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(
|
||||
username: maliciousUsername,
|
||||
totpCode: "123456"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/auth/recover-password", request);
|
||||
|
||||
// Assert
|
||||
// The malicious username queries for a user, so it must never be executed against the database.
|
||||
Assert.NotEqual(HttpStatusCode.TooManyRequests, response.StatusCode);
|
||||
Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.NotNull(await dbContext.Users.FirstOrDefaultAsync(user => user.Id == legitimateUser.Id));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user in the database.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateTestUser()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!"));
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return user;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
|
||||
if (user is not null)
|
||||
{
|
||||
dbContext.Users.Remove(user);
|
||||
dbContext.SaveChanges();
|
||||
}
|
||||
}
|
||||
}
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Requests.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="RegisterEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly RegistrationRequestFixture _registrationRequestFixture = new();
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly string _testUsername;
|
||||
|
||||
public RegisterEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.5");
|
||||
_testUsername = $"testuser_{Guid.NewGuid()}";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_WhenUsernameTaken_ShouldReturnUniformConflictResponse()
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: "TestPass123!",
|
||||
passwordConfirm: "TestPass123!"
|
||||
);
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.6");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage firstResponse = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||
HttpResponseMessage secondResponse = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||
string secondContent = await secondResponse.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Created, firstResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.Conflict, secondResponse.StatusCode);
|
||||
AssertProblemDetail(secondContent, "General.Conflict", "UsernameAlreadyExists");
|
||||
Assert.DoesNotContain("password", secondContent);
|
||||
Assert.DoesNotContain("hash", secondContent);
|
||||
Assert.DoesNotContain("salt", secondContent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_WhenRateLimitExceeded_ShouldReturnTooManyRequests()
|
||||
{
|
||||
// Arrange
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.7");
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: "TestPass123!",
|
||||
passwordConfirm: "TestPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
List<HttpResponseMessage> responses = [];
|
||||
for (int i = 0; i < 11; i++)
|
||||
responses.Add(await _client.PostAsJsonAsync("/api/v1/auth/register", request));
|
||||
|
||||
// Assert
|
||||
HttpResponseMessage lastResponse = responses.Last();
|
||||
Assert.Equal(HttpStatusCode.TooManyRequests, lastResponse.StatusCode);
|
||||
string content = await lastResponse.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status429TooManyRequests, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc6585#section-4", problemDetails["type"].GetString());
|
||||
Assert.Equal("TooManyRequests", problemDetails["title"].GetString());
|
||||
Assert.Equal("TooManyRequests", problemDetails["detail"].GetString());
|
||||
Assert.Equal("900", problemDetails["retryAfter"].GetString());
|
||||
|
||||
Assert.True(lastResponse.Headers.Contains("X-RateLimit-Limit"));
|
||||
Assert.True(lastResponse.Headers.Contains("X-RateLimit-Reset"));
|
||||
Assert.True(lastResponse.Headers.Contains("X-RateLimit-Remaining"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // Basic SQL injection.
|
||||
[InlineData("admin'--")] // Comment injection.
|
||||
[InlineData("' UNION SELECT * FROM Users--")] // Union injection.
|
||||
[InlineData("'; DROP TABLE Users--")] // Destructive injection.
|
||||
[InlineData("' WAITFOR DELAY '0:0:10'--")] // Time-based injection.
|
||||
public async Task Register_WithSQLInjectionAttempt_ShouldRemainSecure(string maliciousUsername)
|
||||
{
|
||||
// Arrange
|
||||
// Note: the register validator rejects these usernames (invalid username format) with 422 before any DB access,
|
||||
// so the malicious username never reaches a query; the 422 assertion below is the security guarantee.
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: maliciousUsername,
|
||||
password: "TestPass123!",
|
||||
passwordConfirm: "TestPass123!"
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.DoesNotContain("Exception", content);
|
||||
Assert.DoesNotContain("password", content);
|
||||
Assert.DoesNotContain("hash", content);
|
||||
Assert.DoesNotContain("salt", content);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("password123")] // Common password.
|
||||
[InlineData("123456789")] // Numeric only.
|
||||
[InlineData("abcdefgh")] // Lowercase only.
|
||||
[InlineData("short")] // Too short.
|
||||
public async Task Register_WithWeakPassword_ShouldBeDenied(string weakPassword)
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: weakPassword,
|
||||
passwordConfirm: weakPassword
|
||||
);
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.8");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.DoesNotContain(weakPassword, content); // Shouldn't leak the actual password.
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("TestPass123!")] // Valid password.
|
||||
[InlineData("Ab1!defghijklmnopqrstuvwxyz")] // Long password.
|
||||
public async Task Register_WithValidPassword_ShouldAcceptPassword(string password)
|
||||
{
|
||||
// Arrange
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: password,
|
||||
passwordConfirm: password
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Register_WithExistingUsername_ShouldNotLeakUserExistence()
|
||||
{
|
||||
// Arrange
|
||||
await CreateTestUser();
|
||||
RegistrationRequest request = _registrationRequestFixture.Create(
|
||||
username: _testUsername,
|
||||
password: "TestPass123!",
|
||||
passwordConfirm: "TestPass123!"
|
||||
);
|
||||
_client.DefaultRequestHeaders.Clear();
|
||||
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.9");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
|
||||
Assert.DoesNotContain("password", content);
|
||||
Assert.DoesNotContain("hash", content);
|
||||
Assert.DoesNotContain("salt", content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the given <paramref name="content"/> is a problem detail with the expected title and detail.
|
||||
/// </summary>
|
||||
/// <param name="content">The response content to assert.</param>
|
||||
/// <param name="expectedTitle">The expected title of the problem detail.</param>
|
||||
/// <param name="expectedDetail">The expected detail of the problem detail.</param>
|
||||
private void AssertProblemDetail(string content, string expectedTitle, string expectedDetail)
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(expectedTitle, problemDetails!["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user in the database and returns it.
|
||||
/// </summary>
|
||||
/// <returns>The created user entity.</returns>
|
||||
private async Task<UserEntity> CreateTestUser()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!"));
|
||||
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return user;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
|
||||
if (user is not null)
|
||||
{
|
||||
dbContext.Users.Remove(user);
|
||||
dbContext.SaveChanges();
|
||||
}
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetAuthorizationEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAuthorizationEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAuthorizationEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetAuthorizationEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAuthorization_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
string url = $"/api/v1/auth/get-authorization?UserId={userId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string responseContent = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseContent, _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/auth/get-authorization", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetUserPermissionsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserPermissionsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserPermissionsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserPermissionsEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserPermissions_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/auth/users/{Guid.NewGuid()}/permissions";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string responseContent = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseContent, _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());
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetUserRoleEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserRoleEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserRoleEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserRoleEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRole_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
string url = $"/api/v1/auth/users/{userId}/role";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string responseContent = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseContent, _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());
|
||||
}
|
||||
}
|
||||
+282
@@ -0,0 +1,282 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authorization;
|
||||
using Lumina.Contracts.Requests.Authorization;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="UpdateUserRoleAndPermissionsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture<LuminaApiFactory>, IAsyncDisposable
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly UpdateUserRoleAndPermissionsRequestFixture _updateUserRoleAndPermissionsRequestFixture = new();
|
||||
private readonly RoleEntityFixture _roleEntityFixture = new();
|
||||
private readonly PermissionEntityFixture _permissionEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
private Guid _adminUserId;
|
||||
private Guid _seededRoleId;
|
||||
private Guid _seededPermissionId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserRoleAndPermissionsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdateUserRoleAndPermissionsEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserRoleAndPermissions_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
string url = $"/api/v1/auth/users/{userId}/role-and-permissions";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync(url, new StringContent("{}", Encoding.UTF8, "application/json"));
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string responseContent = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseContent, _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 UpdateUserRoleAndPermissions_WhenAuthenticatedNonAdmin_ShouldReturnForbiddenResult()
|
||||
{
|
||||
// Arrange
|
||||
using HttpClient client = _apiFactory.CreateClient();
|
||||
(Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
Guid targetUserId = Guid.NewGuid();
|
||||
string url = $"/api/v1/auth/users/{targetUserId}/role-and-permissions";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsync(url, new StringContent("{}", Encoding.UTF8, "application/json"));
|
||||
string responseContent = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(responseContent, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.DoesNotContain("password", responseContent, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", responseContent, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", responseContent, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserRoleAndPermissions_WhenCalledByAdminWithValidData_ShouldUpdateRoleAndPermissions()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
_adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
UserEntity targetUser = await SeedTargetUserAsync();
|
||||
RoleEntity editorRole = await SeedRoleAsync("Editor");
|
||||
PermissionEntity permission = await SeedPermissionAsync(AuthorizationPermission.CanDeleteUsers);
|
||||
UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(
|
||||
userId: targetUser.Id,
|
||||
roleId: editorRole.Id,
|
||||
permissions: [permission.Id]
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/auth/users/{targetUser.Id}/role-and-permissions", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
using JsonDocument authorizationResponse = JsonDocument.Parse(content);
|
||||
Assert.Equal(targetUser.Id, authorizationResponse.RootElement.GetProperty("userId").GetGuid());
|
||||
Assert.Equal("Editor", authorizationResponse.RootElement.GetProperty("role").GetString());
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity? updatedUser = await dbContext.Users
|
||||
.Include(user => user.UserRole).ThenInclude(userRole => userRole!.Role)
|
||||
.Include(user => user.UserPermissions)
|
||||
.FirstOrDefaultAsync(user => user.Id == targetUser.Id);
|
||||
Assert.NotNull(updatedUser);
|
||||
Assert.Equal("Editor", updatedUser!.UserRole!.Role.RoleName);
|
||||
Assert.Contains(updatedUser.UserPermissions, userPermission => userPermission.PermissionId == permission.Id);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE UserRoles; --")] // Destructive injection.
|
||||
[InlineData("' OR '1'='1")] // Boolean-based injection.
|
||||
public async Task UpdateUserRoleAndPermissions_WithInjectionInUserIdRouteSegment_ShouldNotLeakOrExecuteSql(string maliciousUserId)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
_adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(
|
||||
userId: Guid.NewGuid(),
|
||||
roleId: Guid.NewGuid(),
|
||||
permissions: []
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/auth/users/{Uri.EscapeDataString(maliciousUserId)}/role-and-permissions", request);
|
||||
|
||||
// Assert
|
||||
// Note: the {userId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler.
|
||||
// Note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding failure into a
|
||||
// 500 response instead of 400/422 (pre-existing production bug, not fixed here), and that body leaks the binding exception details.
|
||||
// Note: what matters is that the injection never reaches the database, so no SQL engine error (SqliteException) may surface.
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("'; DROP TABLE UserPermissions; --")] // Destructive injection.
|
||||
[InlineData("' OR '1'='1")] // Boolean-based injection.
|
||||
public async Task UpdateUserRoleAndPermissions_WithInjectionInPermissionsBody_ShouldNotLeakOrExecuteSql(string maliciousPermissionId)
|
||||
{
|
||||
// Arrange
|
||||
// Authenticate as an admin and seed the target user, so a well-formed body would reach the handler and be authorized.
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
_adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
|
||||
UserEntity targetUser = await SeedTargetUserAsync();
|
||||
string jsonBody = $"{{\"userId\":\"{targetUser.Id}\",\"roleId\":\"{Guid.NewGuid()}\",\"permissions\":[\"{maliciousPermissionId}\"]}}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsync(
|
||||
$"/api/v1/auth/users/{targetUser.Id}/role-and-permissions",
|
||||
new StringContent(jsonBody, Encoding.UTF8, "application/json"));
|
||||
|
||||
// Assert
|
||||
// Note: the permission Ids are Guid-typed, so the malicious value fails model binding before it reaches the handler.
|
||||
// Note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding failure into a
|
||||
// 500 response instead of 400/422 (pre-existing production bug, not fixed here), and that body leaks the binding exception details.
|
||||
// Note: what matters is that the injection never reaches the database, so no SQL engine error (SqliteException) may surface.
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user whose role and permissions are updated, and traces its username for cleanup.
|
||||
/// </summary>
|
||||
/// <returns>The seeded user.</returns>
|
||||
private async Task<UserEntity> SeedTargetUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
string username = $"targetuser_{Guid.NewGuid()}";
|
||||
UserEntity user = _userEntityFixture.Create(id: Guid.NewGuid(), username: username, password: "HashedPassword");
|
||||
user.TotpSecret = null;
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a role that is assigned to the updated user, and traces it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="roleName">The name of the role to seed.</param>
|
||||
/// <returns>The seeded role.</returns>
|
||||
private async Task<RoleEntity> SeedRoleAsync(string roleName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
_seededRoleId = Guid.NewGuid();
|
||||
RoleEntity role = _roleEntityFixture.Create(id: _seededRoleId, roleName: roleName);
|
||||
dbContext.Roles.Add(role);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return role;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a permission that is assigned to the updated user, and traces it for cleanup.
|
||||
/// </summary>
|
||||
/// <param name="permissionName">The permission to seed.</param>
|
||||
/// <returns>The seeded permission.</returns>
|
||||
private async Task<PermissionEntity> SeedPermissionAsync(AuthorizationPermission permissionName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
_seededPermissionId = Guid.NewGuid();
|
||||
PermissionEntity permission = _permissionEntityFixture.Create(id: _seededPermissionId, permissionName: permissionName);
|
||||
dbContext.Permissions.Add(permission);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return permission;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
await _apiFactory.RemoveTestUserAsync(username).ConfigureAwait(false);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
if (_seededRoleId != Guid.Empty)
|
||||
{
|
||||
RoleEntity? role = await dbContext.Roles.FirstOrDefaultAsync(candidate => candidate.Id == _seededRoleId);
|
||||
if (role is not null)
|
||||
dbContext.Roles.Remove(role);
|
||||
}
|
||||
if (_seededPermissionId != Guid.Empty)
|
||||
{
|
||||
PermissionEntity? permission = await dbContext.Permissions.FirstOrDefaultAsync(candidate => candidate.Id == _seededPermissionId);
|
||||
if (permission is not null)
|
||||
dbContext.Permissions.Remove(permission);
|
||||
}
|
||||
await dbContext.SaveChangesAsync();
|
||||
if (_adminUserId != Guid.Empty)
|
||||
await _apiFactory.RemoveAdminUserAsync(_adminUserId).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.UsersManagement.Settings;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.GetPlaybackState;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Settings.GetPlaybackState;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetPlaybackStateEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The route has no user controlled string input and no configured rate limiting policy, so injection resistance and rate limiting are not
|
||||
/// applicable to it. It also never issues a token, so token and claim correctness is not applicable either.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlaybackStateEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaybackStateEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetPlaybackStateEndpointTests(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 GetPlaybackState_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings/playback-state");
|
||||
|
||||
// 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/users/me/settings/playback-state", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackState_WhenAnotherUserHasStoredState_ShouldReturnOnlyTheAuthenticatedUsersState()
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
await SeedOtherUserWithPlaybackStateAsync(volume: 0.1, isMuted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings/playback-state");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
PlaybackStateResponse? result = JsonSerializer.Deserialize<PlaybackStateResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(1.0, result!.Volume);
|
||||
Assert.False(result.IsMuted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPlaybackState_WhenAuthenticated_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings/playback-state");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated one, with a stored playback state.
|
||||
/// </summary>
|
||||
/// <param name="volume">The volume to store.</param>
|
||||
/// <param name="isMuted">The mute state to store.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task SeedOtherUserWithPlaybackStateAsync(double volume, bool isMuted)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
UserEntity otherUser = _userEntityFixture.Create(username: username, password: "TestPass123!");
|
||||
otherUser.TotpSecret = null;
|
||||
dbContext.Users.Add(otherUser);
|
||||
dbContext.UserSettings.Add(_userSettingsEntityFixture.Create(userId: otherUser.Id, volume: volume, isMuted: isMuted));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the API factory resources and the seeded users.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Settings.GetUserSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetUserSettingsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserSettingsEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/users/me/settings", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserSettings_WhenAuthenticated_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.GetAsync("/api/v1/users/me/settings");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task CreateAndAuthenticateUserAsync(HttpClient client)
|
||||
{
|
||||
client.DefaultRequestHeaders.Clear();
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!"));
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
}
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings;
|
||||
using Lumina.Contracts.Requests.UsersManagement.Settings;
|
||||
using Lumina.Contracts.Responses.UsersManagement.Settings;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.UpdatePlaybackState;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Settings.UpdatePlaybackState;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="UpdatePlaybackStateEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The route accepts only numeric and boolean JSON fields and has no configured rate limiting policy, so rate limiting and timing attack
|
||||
/// resistance are not applicable to it. It never issues a token, so token and claim correctness is not applicable either.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdatePlaybackStateEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly UpdatePlaybackStateRequestFixture _updatePlaybackStateRequestFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdatePlaybackStateEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdatePlaybackStateEndpointTests(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 UpdatePlaybackState_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.35, isMuted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", 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/users/me/settings/playback-state", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(double.MaxValue)] // Far above the maximum.
|
||||
[InlineData(double.MinValue)] // Far below the minimum.
|
||||
public async Task UpdatePlaybackState_WhenVolumeIsAtADoubleExtreme_ShouldReturnValidationErrorWithoutLeakingInternals(double volume)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: volume);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
AssertResponseDoesNotLeakInternalDetails(content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaybackState_WhenCalledByOneUser_ShouldNotChangeTheStateOfAnotherUser()
|
||||
{
|
||||
// Arrange
|
||||
(_, string firstUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(firstUsername);
|
||||
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.25, isMuted: true);
|
||||
HttpResponseMessage updateResponse = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request);
|
||||
HttpClient otherClient = _apiFactory.CreateClient();
|
||||
(_, string secondUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(otherClient);
|
||||
_seededUsernames.Add(secondUsername);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage getResponse = await otherClient.GetAsync("/api/v1/users/me/settings/playback-state");
|
||||
|
||||
// Assert
|
||||
updateResponse.EnsureSuccessStatusCode();
|
||||
getResponse.EnsureSuccessStatusCode();
|
||||
string content = await getResponse.Content.ReadAsStringAsync();
|
||||
PlaybackStateResponse? result = JsonSerializer.Deserialize<PlaybackStateResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(1.0, result!.Volume);
|
||||
Assert.False(result.IsMuted);
|
||||
otherClient.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdatePlaybackState_WhenAuthenticated_ShouldNotLeakSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.35, isMuted: true);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Theory(Skip = "Production bug: a JSON payload whose volume is a string makes the FastEndpoints binder throw a System.Text.Json.JsonException, which escapes because UpdatePlaybackStateEndpoint calls DontCatchExceptions(), so the API responds with 500 instead of 400 or 422. The body is the generic ProblemDetails and leaks no internals. The test stays skipped until the endpoint maps binding failures to a client error.")]
|
||||
[InlineData("'; DROP TABLE UserSettings; --")] // SQL injection.
|
||||
[InlineData("$(rm -rf /)")] // Command injection.
|
||||
[InlineData("../../etc/passwd")] // Path traversal.
|
||||
public async Task UpdatePlaybackState_WhenAStringIsSentInTheVolumeField_ShouldReturnAClientErrorWithoutLeakingInternalDetails(string maliciousValue)
|
||||
{
|
||||
// Arrange
|
||||
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
|
||||
_seededUsernames.Add(username);
|
||||
string payload = $"{{\"volume\":\"{maliciousValue}\",\"isMuted\":true}}";
|
||||
StringContent requestContent = new(payload, Encoding.UTF8, "application/json");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsync("/api/v1/users/me/settings/playback-state", requestContent);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.True(response.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.UnprocessableEntity, $"Actual status: {(int)response.StatusCode}");
|
||||
AssertResponseDoesNotLeakInternalDetails(content);
|
||||
Assert.DoesNotContain("DROP TABLE", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("rm -rf", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("/etc/passwd", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body does not expose exception details, stack frames, or database internals.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to inspect.</param>
|
||||
private static void AssertResponseDoesNotLeakInternalDetails(string content)
|
||||
{
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Microsoft.Data.Sqlite", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Microsoft.EntityFrameworkCore", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the API factory resources and the seeded users.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+369
@@ -0,0 +1,369 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.Authentication;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings;
|
||||
using Lumina.Contracts.Requests.UsersManagement.Settings;
|
||||
using Lumina.Contracts.Responses.Authentication;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Settings.UpdateUserSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="UpdateUserSettingsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class UpdateUserSettingsEndpointTests : IClassFixture<LuminaApiFactory>
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly PasswordHashService _hashService = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly LoginRequestFixture _loginRequestFixture = new();
|
||||
private readonly UpdateUserSettingsRequestFixture _updateUserSettingsRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserSettingsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public UpdateUserSettingsEndpointTests(LuminaApiFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
_client = apiFactory.CreateClient();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
isPaginationEnabled: true,
|
||||
itemsPerPage: 48,
|
||||
shouldIgnoreThePrefixForAlphaPicker: false,
|
||||
isThemeCachingEnabled: true,
|
||||
shouldAggregateMetadataWhenMissing: false
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("/api/v1/users/me/settings", problemDetails["instance"].GetProperty("value").GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenItemsPerPageIsAtIntMaxValue_ShouldNotCrash()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
isPaginationEnabled: true,
|
||||
itemsPerPage: int.MaxValue,
|
||||
shouldIgnoreThePrefixForAlphaPicker: false,
|
||||
isThemeCachingEnabled: true,
|
||||
shouldAggregateMetadataWhenMissing: false
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenItemsPerPageIsAtIntMinValue_ShouldReturnValidationErrorWithoutCrashing()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
isPaginationEnabled: true,
|
||||
itemsPerPage: int.MinValue,
|
||||
shouldIgnoreThePrefixForAlphaPicker: false,
|
||||
isThemeCachingEnabled: true,
|
||||
shouldAggregateMetadataWhenMissing: false
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(int.MaxValue)] // Far above the maximum.
|
||||
[InlineData(int.MinValue)] // Far below the minimum.
|
||||
public async Task UpdateUserSettings_WhenVuMeterSegmentCountIsAtAnIntExtreme_ShouldReturnValidationErrorWithoutCrashing(int vuMeterSegmentCount)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterSegmentCount: vuMeterSegmentCount);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
AssertResponseDoesNotLeakInternalDetails(content);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(int.MaxValue)] // Far above the maximum.
|
||||
[InlineData(int.MinValue)] // Far below the minimum.
|
||||
public async Task UpdateUserSettings_WhenVuMeterSegmentGapIsAtAnIntExtreme_ShouldReturnValidationErrorWithoutCrashing(int vuMeterSegmentGap)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterSegmentGap: vuMeterSegmentGap);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
AssertResponseDoesNotLeakInternalDetails(content);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(double.MaxValue)] // Far above the maximum.
|
||||
[InlineData(double.MinValue)] // Far below the minimum.
|
||||
public async Task UpdateUserSettings_WhenVuMeterMediumThresholdIsAtADoubleExtreme_ShouldReturnValidationErrorWithoutCrashing(double vuMeterMediumThreshold)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
vuMeterMediumThreshold: vuMeterMediumThreshold,
|
||||
vuMeterHighThreshold: 1.0);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
AssertResponseDoesNotLeakInternalDetails(content);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(double.MaxValue)] // Far above the maximum.
|
||||
[InlineData(double.MinValue)] // Far below the minimum.
|
||||
public async Task UpdateUserSettings_WhenVuMeterHighThresholdIsAtADoubleExtreme_ShouldReturnValidationErrorWithoutCrashing(double vuMeterHighThreshold)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
vuMeterMediumThreshold: 0.0,
|
||||
vuMeterHighThreshold: vuMeterHighThreshold);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
AssertResponseDoesNotLeakInternalDetails(content);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(int.MaxValue)] // Far above the maximum.
|
||||
[InlineData(int.MinValue)] // Far below the minimum.
|
||||
public async Task UpdateUserSettings_WhenVuMeterPeakHoldDurationIsAtAnIntExtreme_ShouldReturnValidationErrorWithoutCrashing(int vuMeterPeakHoldDurationInMilliseconds)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(
|
||||
vuMeterPeakHoldDurationInMilliseconds: vuMeterPeakHoldDurationInMilliseconds);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
AssertResponseDoesNotLeakInternalDetails(content);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(double.MaxValue)] // Far above the maximum.
|
||||
[InlineData(double.MinValue)] // Far below the minimum.
|
||||
public async Task UpdateUserSettings_WhenVuMeterReleasePerSecondIsAtADoubleExtreme_ShouldReturnValidationErrorWithoutCrashing(double vuMeterReleasePerSecond)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterReleasePerSecond: vuMeterReleasePerSecond);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
AssertResponseDoesNotLeakInternalDetails(content);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(double.MaxValue)] // Far above the maximum.
|
||||
[InlineData(double.MinValue)] // Far below the minimum.
|
||||
public async Task UpdateUserSettings_WhenVuMeterPeakReleasePerSecondIsAtADoubleExtreme_ShouldReturnValidationErrorWithoutCrashing(double vuMeterPeakReleasePerSecond)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterPeakReleasePerSecond: vuMeterPeakReleasePerSecond);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
AssertResponseDoesNotLeakInternalDetails(content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenVuMeterOrientationIsAnUndefinedValue_ShouldReturnValidationErrorWithoutCrashing()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(vuMeterOrientation: (VuMeterOrientation)999);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/users/me/settings", request);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
AssertResponseDoesNotLeakInternalDetails(content);
|
||||
}
|
||||
|
||||
[Theory(Skip = "Production bug: a JSON payload whose VuMeterOrientation is not a valid enumeration value makes the FastEndpoints binder throw a System.Text.Json.JsonException, which escapes because UpdateUserSettingsEndpoint calls DontCatchExceptions(), so the API responds with 500 instead of 400 or 422. The body is the generic ProblemDetails and leaks no internals. The test stays skipped until the endpoint maps binding failures to a client error.")]
|
||||
[InlineData("'; DROP TABLE UserSettings; --")] // SQL injection.
|
||||
[InlineData("$(rm -rf /)")] // Command injection.
|
||||
[InlineData("{{7*7}}")] // Template injection.
|
||||
public async Task UpdateUserSettings_WhenVuMeterOrientationIsAMaliciousString_ShouldReturnClientErrorWithoutLeakingInternals(string maliciousOrientation)
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
UpdateUserSettingsRequest validRequest = _updateUserSettingsRequestFixture.Create();
|
||||
JsonObject payload = JsonSerializer.SerializeToNode(
|
||||
validRequest,
|
||||
new JsonSerializerOptions(JsonSerializerDefaults.Web))!.AsObject();
|
||||
payload["vuMeterOrientation"] = maliciousOrientation;
|
||||
StringContent requestContent = new(payload.ToJsonString(), Encoding.UTF8, "application/json");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsync("/api/v1/users/me/settings", requestContent);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
Assert.True(
|
||||
response.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.UnprocessableEntity,
|
||||
$"Expected a 400 or 422 response, but got {(int)response.StatusCode}.");
|
||||
AssertResponseDoesNotLeakInternalDetails(content);
|
||||
Assert.DoesNotContain("DROP TABLE", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("rm -rf", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateUserSettings_WhenTheRawJsonPayloadIsValid_ShouldUpdateSettings()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient client = _apiFactory.CreateClient();
|
||||
await CreateAndAuthenticateUserAsync(client);
|
||||
UpdateUserSettingsRequest validRequest = _updateUserSettingsRequestFixture.Create();
|
||||
JsonObject payload = JsonSerializer.SerializeToNode(
|
||||
validRequest,
|
||||
new JsonSerializerOptions(JsonSerializerDefaults.Web))!.AsObject();
|
||||
StringContent requestContent = new(payload.ToJsonString(), Encoding.UTF8, "application/json");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.PutAsync("/api/v1/users/me/settings", requestContent);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body does not expose exception details, stack frames, or database internals.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to inspect.</param>
|
||||
private static void AssertResponseDoesNotLeakInternalDetails(string content)
|
||||
{
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Microsoft.Data.Sqlite", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Microsoft.EntityFrameworkCore", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task CreateAndAuthenticateUserAsync(HttpClient client)
|
||||
{
|
||||
client.DefaultRequestHeaders.Clear();
|
||||
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"testuser_{Guid.NewGuid()}";
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!"));
|
||||
user.TotpSecret = null;
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!"));
|
||||
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||
LoginResponse? loginResult = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user