diff --git a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs index 99629352..fba2d476 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserEntity.cs @@ -42,12 +42,12 @@ public class UserEntity : IStorageEntity /// /// Gets or sets the optional token used for account verification or password reset. /// - public string? VerificationToken { get; set; } + public string? VerificationToken { get; set; } // TODO: to be deleted, not used /// /// Gets or sets the optional date and time when the verification token was created. /// - public DateTime? VerificationTokenCreated { get; set; } + public DateTime? VerificationTokenCreated { get; set; } // TODO: to be deleted, not used /// /// Gets or sets the date and time when the temporary password used in password recovery was created. diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpoint.cs index 22eaa48a..c7b79cf6 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpoint.cs @@ -50,6 +50,6 @@ public class SetupApplicationEndpoint : BaseEndpoint ExecuteAsync(RegistrationRequest request, CancellationToken cancellationToken) { ErrorOr result = await _sender.Send(request.ToSetupCommand(), cancellationToken).ConfigureAwait(false); - return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{Api.Common.Routes.UsersManagement.ApiRoutes.Users.GET_USER_BY_ID}/{result.Value.Id}", result.Value), Problem); + return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{Api.Common.Routes.UsersManagement.ApiRoutes.Users.GET_USER_BY_ID.Replace("{id}", success.Id.ToString())}", result.Value), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs index 0f2c5498..fd72bd70 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpoint.cs @@ -50,6 +50,6 @@ public class RegisterEndpoint : BaseEndpoint public override async Task ExecuteAsync(RegistrationRequest request, CancellationToken cancellationToken) { ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); - return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Users.GET_USER_BY_ID}/{result.Value.Id}", result.Value), Problem); + return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Users.GET_USER_BY_ID.Replace("{id}", success.Id.ToString())}", result.Value), Problem); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Fixtures/JwtFixture.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Fixtures/JwtFixture.cs new file mode 100644 index 00000000..84a5c625 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Fixtures/JwtFixture.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.IdentityModel.Tokens; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IdentityModel.Tokens.Jwt; +using System.Linq; +using System.Security.Claims; +using System.Text; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Common.Fixtures; + +/// +/// Provides JWT token generation functionality for testing purposes. +/// +[ExcludeFromCodeCoverage] +public class JwtFixture +{ + private static readonly string s_secretKey = "test-key-thats-at-least-32-chars-long-for-jwt"; + + /// + /// Generates a JWT token for testing with the specified username and optional roles. + /// + /// The username to include in the token claims. + /// Optional array of roles to include in the token claims. + /// A JWT token string that can be used for authentication in tests. + public static string GenerateJwtToken(string username, string[]? roles = null) + { + byte[] key = Encoding.ASCII.GetBytes(s_secretKey); + List claims = + [ + new(ClaimTypes.Name, username), + new(ClaimTypes.NameIdentifier, username) + ]; + + if (roles?.Length > 0) + claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role))); + + JwtSecurityToken token = new( + issuer: "test-issuer", + audience: "test-audience", + claims: claims, + expires: DateTime.UtcNow.AddHours(1), + signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) + ); + return new JwtSecurityTokenHandler().WriteToken(token); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs index 5c02727c..e0890627 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs @@ -1,15 +1,18 @@ #region ========================================================================= USING ===================================================================================== using Lumina.DataAccess.Core.UoW; +using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.Tokens; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Text; #endregion namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; @@ -21,6 +24,7 @@ namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; public class LuminaApiFactory : WebApplicationFactory, IDisposable { private readonly SqliteConnection _connection; + private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; /// /// Initializes a new instance of the class. @@ -50,7 +54,7 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable config.AddInMemoryCollection(initialData: new Dictionary { ["JwtSettings:SecretKey"] = "test-key-thats-at-least-32-chars-long-for-jwt", - ["EncryptionSettings:SecretKey"] = "dGVzdC1rZXktdGhhdHMtYXQtbGVhc3QtMzItY2hhcnMtbG9uZy1mb3ItZW5jcnlwdGlvbg==" // base64 encoded test key + ["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY // base64 encoded test key }); }); builder.ConfigureServices(services => @@ -61,6 +65,20 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable services.Remove(descriptor); // add SQLite DbContext configuration services.AddDbContext(options => options.UseSqlite(_connection)); + // configure JWT authentication for testing + services.PostConfigure(JwtBearerDefaults.AuthenticationScheme, options => + { + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuer = true, + ValidateAudience = true, + ValidateLifetime = true, + ValidateIssuerSigningKey = true, + ValidIssuer = "test-issuer", + ValidAudience = "test-audience", + IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("test-key-thats-at-least-32-chars-long-for-jwt")) + }; + }); // build service provider and ensure database is created ServiceProvider servicePreovider = services.BuildServiceProvider(); using (IServiceScope scope = servicePreovider.CreateScope()) @@ -70,7 +88,7 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable dbContext.Database.Migrate(); } }); - } + } /// /// Disposes the connection to the database. diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs new file mode 100644 index 00000000..f2220547 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs @@ -0,0 +1,132 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Infrastructure.Core.Security; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Maintenance.ApplicationSetup; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CheckInitializationEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testUsername; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public CheckInitializationEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + } + + [Fact] + public async Task ExecuteAsync_WhenNoUsersExist_ShouldReturnNotInitialized() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/initialization"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + InitializationResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.IsInitialized.Should().BeFalse(); + } + + [Fact] + public async Task ExecuteAsync_WhenUsersExist_ShouldReturnInitialized() + { + // Arrange + await CreateTestUser(); + + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/initialization"); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + InitializationResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.IsInitialized.Should().BeTrue(); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException() + { + // Arrange + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); + await _client.GetAsync("/api/v1/initialization", cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } + + private async Task CreateTestUser() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = new HashService().HashString("TestPass123!"), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs new file mode 100644 index 00000000..180e5594 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs @@ -0,0 +1,187 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.DataAccess.Core.UoW; +using Lumina.Infrastructure.Core.Security; +using Lumina.Presentation.Api.IntegrationTests.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.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.IntegrationTests.Core.Endpoints.Maintenance.ApplicationSetup; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetupApplicationEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testUsername; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public SetupApplicationEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidRequestAnd2FA_ShouldSetupApplicationSuccessfully() + { + // Arrange + RegistrationRequest request = new( + Username: _testUsername, + Password: "TestPass123!", + PasswordConfirm: "TestPass123!", + Use2fa: true + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Created); + string content = await response.Content.ReadAsStringAsync(); + RegistrationResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.Username.Should().Be(_testUsername); + result.Id.Should().NotBe(Guid.Empty); + result.TotpSecret.Should().NotBeNullOrEmpty(); + result.TotpSecret.Should().StartWith("data:image/png;base64,"); + + response.Headers.Location.Should().NotBeNull(); + response.Headers.Location!.ToString().Should().Be($"http://localhost/api/v1/users/{result.Id}"); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidRequestWithout2FA_ShouldSetupApplicationSuccessfully() + { + // Arrange + RegistrationRequest request = new( + Username: _testUsername, + Password: "TestPass123!", + PasswordConfirm: "TestPass123!", + Use2fa: false + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Created); + string content = await response.Content.ReadAsStringAsync(); + RegistrationResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.Username.Should().Be(_testUsername); + result.Id.Should().NotBe(Guid.Empty); + result.TotpSecret.Should().BeNull(); + + response.Headers.Location.Should().NotBeNull(); + response.Headers.Location!.ToString().Should().Be($"http://localhost/api/v1/users/{result.Id}"); + } + + [Fact] + public async Task ExecuteAsync_WhenAdminAccountAlreadyExists_ShouldReturnConflict() + { + // Arrange + await CreateTestUser(); + RegistrationRequest request = new( + Username: "another_admin", + Password: "TestPass123!", + PasswordConfirm: "TestPass123!", + Use2fa: false + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4"); + problemDetails["title"].GetString().Should().Be("General.Unauthorized"); + problemDetails["detail"].GetString().Should().Be("AdminAccountAlreadyCreated"); + problemDetails["instance"].GetString().Should().Be("/api/v1/initialization"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task ExecuteAsync_WhenRequestIsNull_ShouldReturnValidationError() + { + // Arrange + RegistrationRequest? request = null; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + Dictionary? errors = problemDetails!["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation") + .WhoseValue.Should().Contain(["UsernameCannotBeEmpty", "PasswordCannotBeEmpty", "PasswordConfirmCannotBeEmpty"]); + } + + private async Task CreateTestUser() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = new HashService().HashString("TestPass123!"), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs new file mode 100644 index 00000000..e6cb419c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs @@ -0,0 +1,255 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.DataAccess.Core.UoW; +using Lumina.Infrastructure.Core.Security; +using Lumina.Presentation.Api.IntegrationTests.Common.Fixtures; +using Lumina.Presentation.Api.IntegrationTests.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.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authentication; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordEndpointTests : IClassFixture, IDisposable +{ + private readonly HashService _hashService; + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testUsername; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public ChangePasswordEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _hashService = new HashService(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + + // Set authorization header with unique username + string token = JwtFixture.GenerateJwtToken(_testUsername, ["User"]); + _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldChangePasswordSuccessfully() + { + // Arrange + UserEntity user = await CreateTestUser(); + ChangePasswordRequest request = new( + Username: user.Username, + CurrentPassword: "OldPass123!", + NewPassword: "NewPass123!", + NewPasswordConfirm: "NewPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + ChangePasswordResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.IsPasswordChanged.Should().BeTrue(); + } + + [Fact] + public async Task ExecuteAsync_WhenPasswordsDoNotMatch_ShouldReturnValidationError() + { + // Arrange + UserEntity user = await CreateTestUser(); + ChangePasswordRequest request = new( + Username: user.Username, + CurrentPassword: "OldPass123!", + NewPassword: "NewPass123!", + NewPasswordConfirm: "DifferentPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/change-password"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain("PasswordsNotMatch"); + } + + [Fact] + public async Task ExecuteAsync_WhenUserDoesNotExist_ShouldReturnNotFound() + { + // Arrange + ChangePasswordRequest request = new( + Username: "nonexistentuser", + CurrentPassword: "OldPass123!", + NewPassword: "NewPass123!", + NewPasswordConfirm: "NewPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.NotFound); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status404NotFound); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5"); + problemDetails["title"].GetString().Should().Be("General.NotFound"); + problemDetails["detail"].GetString().Should().Be("UsernameDoesNotExist"); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/change-password"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task ExecuteAsync_WhenCurrentPasswordIsIncorrect_ShouldReturnForbidden() + { + // Arrange + UserEntity user = await CreateTestUser(); + ChangePasswordRequest request = new( + Username: user.Username, + CurrentPassword: "WrongPass123!", + NewPassword: "NewPass123!", + NewPasswordConfirm: "NewPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4"); + problemDetails["title"].GetString().Should().Be("General.Failure"); + problemDetails["detail"].GetString().Should().Be("InvalidCurrentPassword"); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/change-password"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task ExecuteAsync_WhenRequestIsNull_ShouldReturnValidationError() + { + // Arrange + ChangePasswordRequest? request = null; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/change-password"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["UsernameCannotBeEmpty", "CurrentPasswordCannotBeEmpty", "NewPasswordCannotBeEmpty", "NewPasswordConfirmCannotBeEmpty"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException() + { + // Arrange + UserEntity user = await CreateTestUser(); + ChangePasswordRequest request = new( + Username: user.Username, + CurrentPassword: "OldPass123!", + NewPassword: "NewPass123!", + NewPasswordConfirm: "NewPass123!" + ); + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); + await _client.PostAsJsonAsync("/api/v1/auth/change-password", request, cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } + + private async Task CreateTestUser() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("OldPass123!"), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointRateLimitingTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointRateLimitingTests.cs new file mode 100644 index 00000000..9191a0c1 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointRateLimitingTests.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Requests.Authentication; +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +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.IntegrationTests.Core.Endpoints.UsersManagement.Authentication; + +/// +/// Contains integration tests for the class. +/// +/// +/// This test class needs to be separate from because rate limiting is set per application run, not HTTP client instantiation. +/// +[ExcludeFromCodeCoverage] +public class LoginEndpointRateLimitingTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testUsername; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public LoginEndpointRateLimitingTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + } + + [Fact] + public async Task ExecuteAsync_WhenRateLimitExceeded_ShouldReturnTooManyRequests() + { + // Arrange + LoginRequest request = new( + Username: "testuser", + Password: "TestPass123!" + ); + + // Act + List 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(); + lastResponse.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + string content = await lastResponse.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["title"].GetString().Should().Be("TooManyRequests"); + problemDetails["retryAfter"].GetString().Should().Be("15"); + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs new file mode 100644 index 00000000..7f468272 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs @@ -0,0 +1,319 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.Infrastructure.Security; +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.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using OtpNet; +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.IntegrationTests.Core.Endpoints.UsersManagement.Authentication; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LoginEndpointTests : IClassFixture, IDisposable +{ + private readonly HashService _hashService; + private readonly ICryptographyService _cryptographyService; + private readonly TotpTokenGenerator _totpTokenGenerator; + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testUsername; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public LoginEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _hashService = new HashService(); + _totpTokenGenerator = new TotpTokenGenerator(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + + using IServiceScope scope = apiFactory.Services.CreateScope(); + _cryptographyService = scope.ServiceProvider.GetRequiredService(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidCredentials_ShouldLoginSuccessfully() + { + // Arrange + UserEntity user = await CreateTestUser(); + LoginRequest request = new( + Username: user.Username, + Password: "TestPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + LoginResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.Username.Should().Be(user.Username); + result.UsesTotp.Should().BeFalse(); + result.Token.Should().NotBeNullOrEmpty(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidCredentialsAndTotp_ShouldLoginSuccessfully() + { + // Arrange + UserEntity user = await CreateTestUserWithTotp(); + byte[] totpSecret = Convert.FromBase64String(_cryptographyService.Decrypt(user.TotpSecret!)); + Totp totp = new(totpSecret); + string validTotpCode = totp.ComputeTotp(DateTime.UtcNow); + + LoginRequest request = new( + Username: user.Username, + Password: "TestPass123!", + TotpCode: validTotpCode + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + LoginResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.Username.Should().Be(user.Username); + result.UsesTotp.Should().BeTrue(); + result.Token.Should().NotBeNullOrEmpty(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithTempPassword_ShouldLoginSuccessfully() + { + // Arrange + UserEntity user = await CreateTestUserWithTempPassword(); + LoginRequest request = new( + Username: user.Username, + Password: "TempPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + LoginResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.Username.Should().Be(user.Username); + result.Token.Should().NotBeNullOrEmpty(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithExpiredTempPassword_ShouldReturnUnauthorized() + { + // Arrange + UserEntity user = await CreateTestUserWithExpiredTempPassword(); + LoginRequest request = new( + Username: user.Username, + Password: "TempPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4"); + problemDetails["title"].GetString().Should().Be("General.Failure"); + problemDetails["detail"].GetString().Should().Be("TempPasswordExpired"); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/login"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithInvalidCredentials_ShouldReturnUnauthorized() + { + // Arrange + UserEntity user = await CreateTestUser(); + LoginRequest request = new( + Username: user.Username, + Password: "WrongPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status403Forbidden); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.4"); + problemDetails["title"].GetString().Should().Be("General.Failure"); + problemDetails["detail"].GetString().Should().Be("InvalidUsernameOrPassword"); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/login"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithInvalidTotpCode_ShouldReturnUnauthorized() + { + // Arrange + UserEntity user = await CreateTestUserWithTotp(); + LoginRequest request = new( + Username: user.Username, + Password: "TestPass123!", + TotpCode: "000000" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/login"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["InvalidTotpCode"]); + } + + private async Task CreateTestUser() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + private async Task CreateTestUserWithTotp() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + byte[] totpSecret = _totpTokenGenerator.GenerateSecret(); + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + private async Task CreateTestUserWithTempPassword() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")), + TempPasswordCreated = DateTime.UtcNow, + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + private async Task CreateTestUserWithExpiredTempPassword() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("TestPass123!"), + TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")), + TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16), // expired (> 15 minutes old) + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointRateLimitingTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointRateLimitingTests.cs new file mode 100644 index 00000000..6ac4db70 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointRateLimitingTests.cs @@ -0,0 +1,92 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Requests.Authentication; +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.IntegrationTests.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.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.IntegrationTests.Core.Endpoints.UsersManagement.Authentication; + +/// +/// Contains integration tests for the class. +/// +/// +/// This test class needs to be separate from because rate limiting is set per application run, not HTTP client instantiation. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordEndpointRateLimitingTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testUsername; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public RecoverPasswordEndpointRateLimitingTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + } + + [Fact] + public async Task ExecuteAsync_WhenRateLimitExceeded_ShouldReturnTooManyRequests() + { + // Arrange + RecoverPasswordRequest request = new( + Username: "testuser", + TotpCode: "123456" + ); + + // Act + List 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(); + lastResponse.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + string content = await lastResponse.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status429TooManyRequests); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc7231#section-6.5.29"); + problemDetails["title"].GetString().Should().Be("TooManyRequests"); + problemDetails["detail"].GetString().Should().Be("Too many attempts. Please try again later."); + problemDetails["retryAfter"].GetString().Should().Be("15"); + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs new file mode 100644 index 00000000..1b8cc3b7 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs @@ -0,0 +1,339 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.Infrastructure.Security; +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.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OtpNet; +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; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authentication; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordEndpointTests : IClassFixture, IDisposable +{ + private readonly HashService _hashService; + private readonly ICryptographyService _cryptographyService; + private readonly TotpTokenGenerator _totpTokenGenerator; + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testUsername; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public RecoverPasswordEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _hashService = new HashService(); + _totpTokenGenerator = new TotpTokenGenerator(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + + // get the encryption service with the test key from factory + using IServiceScope scope = apiFactory.Services.CreateScope(); + _cryptographyService = scope.ServiceProvider.GetRequiredService(); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldResetPassword() + { + // Arrange + UserEntity user = await CreateUserWithTotp(); + + // decrypt the TOTP secret and generate a valid code + byte[] totpSecret = Convert.FromBase64String(_cryptographyService.Decrypt(user.TotpSecret!)); + Totp totp = new(totpSecret); + string validTotpCode = totp.ComputeTotp(DateTime.UtcNow); + + RecoverPasswordRequest request = new( + Username: user.Username, + TotpCode: validTotpCode + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request); + + // Assert + response.EnsureSuccessStatusCode(); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + string content = await response.Content.ReadAsStringAsync(); + RecoverPasswordResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.IsPasswordReset.Should().BeTrue(); + + // Create a new context to get fresh data + using IServiceScope verificationScope = _apiFactory.Services.CreateScope(); + LuminaDbContext verificationContext = verificationScope.ServiceProvider.GetRequiredService(); + + // Ensure we get fresh data from the database + verificationContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; + UserEntity? updatedUser = await verificationContext.Users + .AsNoTracking() + .FirstOrDefaultAsync(u => u.Username == user.Username); + + updatedUser.Should().NotBeNull(); + updatedUser!.TempPassword.Should().NotBeNull(); + updatedUser.TempPasswordCreated.Should().BeCloseTo(DateTime.UtcNow, TimeSpan.FromSeconds(5)); + } + + [Fact] + public async Task ExecuteAsync_WhenUserDoesNotExist_ShouldReturnNotFound() + { + // Arrange + RecoverPasswordRequest request = new( + Username: "nonexistentuser", + TotpCode: "123456" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.NotFound); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status404NotFound); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc9110#section-15.5.5"); + problemDetails["title"].GetString().Should().Be("General.NotFound"); + problemDetails["detail"].GetString().Should().Be("UsernameDoesNotExist"); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/recover-password"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task ExecuteAsync_WhenInvalidTotpCode_ShouldReturnForbidden() + { + // Arrange + UserEntity user = await CreateUserWithTotp(); + RecoverPasswordRequest request = new( + Username: user.Username, + TotpCode: "000000" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/recover-password"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["InvalidTotpCode"]); + } + + [Fact] + public async Task ExecuteAsync_WhenRequestIsNull_ShouldReturnValidationError() + { + // Arrange + RecoverPasswordRequest? request = null; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/recover-password"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["UsernameCannotBeEmpty", "TotpCannotBeEmpty"]); + } + + [Fact] + public async Task ExecuteAsync_WhenUserDoesNotUseTotpAndTriesToRecover_ShouldReturnForbidden() + { + // Arrange + UserEntity user = await CreateUserWithoutTotp(); + + RecoverPasswordRequest request = new( + Username: user.Username, + TotpCode: "123456" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/recover-password"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["InvalidTotpCode"]); + } + + [Fact] + public async Task ExecuteAsync_WhenUserDoesNotUseTotpAndTriesToRecoverWithoutCode_ShouldReturnForbidden() + { + // Arrange + // Setup user without TOTP + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity userWithoutTotp = new() + { + Username = "userwithoutotp2", + Password = _hashService.HashString("OldPass123!"), + TotpSecret = null, // No TOTP configured + Libraries = [], + Created = DateTime.UtcNow + }; + dbContext.Users.Add(userWithoutTotp); + await dbContext.SaveChangesAsync(); + } + + RecoverPasswordRequest request = new( + Username: "userwithoutotp2", + TotpCode: null + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status422UnprocessableEntity); + problemDetails["type"].GetString().Should().Be("https://tools.ietf.org/html/rfc4918#section-11.2"); + problemDetails["title"].GetString().Should().Be("Validation Error"); + problemDetails["detail"].GetString().Should().Be("One or more validation errors occurred."); + problemDetails["instance"].GetString().Should().Be("/api/v1/auth/recover-password"); + problemDetails["traceId"].GetString().Should().NotBeNullOrWhiteSpace(); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["TotpCannotBeEmpty"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException() + { + // Arrange + RecoverPasswordRequest request = new( + Username: "testuser", + TotpCode: "123456" + ); + using CancellationTokenSource cts = new(); + + // Act + Func act = async () => + { + cts.Cancel(); + await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request, cts.Token); + }; + + // Assert + await act.Should().ThrowAsync(); + } + + private async Task CreateUserWithTotp() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + byte[] totpSecret = _totpTokenGenerator.GenerateSecret(); + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("OldPass123!"), + TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + private async Task CreateUserWithoutTotp() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = _hashService.HashString("OldPass123!"), + TotpSecret = null, + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs new file mode 100644 index 00000000..83eeb4b2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs @@ -0,0 +1,205 @@ +#region ========================================================================= USING ===================================================================================== +using FluentAssertions; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Contracts.Responses.Authentication; +using Lumina.DataAccess.Core.UoW; +using Lumina.Infrastructure.Core.Security; +using Lumina.Presentation.Api.IntegrationTests.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.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.IntegrationTests.Core.Endpoints.UsersManagement.Authentication; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly string _testUsername; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public RegisterEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _testUsername = $"testuser_{Guid.NewGuid()}"; + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidRequest_ShouldRegisterUserSuccessfully() + { + // Arrange + RegistrationRequest request = new( + Username: _testUsername, + Password: "TestPass123!", + PasswordConfirm: "TestPass123!", + Use2fa: false + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Created); + string content = await response.Content.ReadAsStringAsync(); + RegistrationResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.Username.Should().Be(_testUsername); + result.Id.Should().NotBe(Guid.Empty); + result.TotpSecret.Should().BeNull(); + + response.Headers.Location.Should().NotBeNull(); + response.Headers.Location!.ToString().Should().Be($"http://localhost/api/v1/users/{result.Id}"); + } + + [Fact] + public async Task ExecuteAsync_WhenCalledWithValidRequestAnd2FA_ShouldRegisterUserWithTotp() + { + // Arrange + RegistrationRequest request = new( + Username: _testUsername, + Password: "TestPass123!", + PasswordConfirm: "TestPass123!", + Use2fa: true + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Created); + string content = await response.Content.ReadAsStringAsync(); + RegistrationResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + result.Should().NotBeNull(); + result!.Username.Should().Be(_testUsername); + result.Id.Should().NotBe(Guid.Empty); + result.TotpSecret.Should().NotBeNullOrEmpty(); + result.TotpSecret.Should().StartWith("data:image/png;base64,"); + } + + [Fact] + public async Task ExecuteAsync_WhenUsernameAlreadyExists_ShouldReturnConflict() + { + // Arrange + await CreateTestUser(); + RegistrationRequest request = new( + Username: _testUsername, + Password: "TestPass123!", + PasswordConfirm: "TestPass123!", + Use2fa: false + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.Conflict); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + problemDetails!["status"].GetInt32().Should().Be(StatusCodes.Status409Conflict); + problemDetails["title"].GetString().Should().Be("General.Conflict"); + problemDetails["detail"].GetString().Should().Be("UsernameAlreadyExists"); + } + + [Fact] + public async Task ExecuteAsync_WhenPasswordsDoNotMatch_ShouldReturnValidationError() + { + // Arrange + RegistrationRequest request = new( + Username: _testUsername, + Password: "TestPass123!", + PasswordConfirm: "DifferentPass123!", + Use2fa: false + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + Dictionary? errors = problemDetails!["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain("PasswordsNotMatch"); + } + + [Fact] + public async Task ExecuteAsync_WhenRequestIsNull_ShouldReturnValidationError() + { + // Arrange + RegistrationRequest? request = null; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + + // Assert + response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + problemDetails.Should().NotBeNull(); + Dictionary? errors = problemDetails!["errors"].Deserialize>(_jsonOptions); + errors.Should().ContainKey("General.Validation") + .WhoseValue.Should().Contain(["UsernameCannotBeEmpty", "PasswordCannotBeEmpty", "PasswordConfirmCannotBeEmpty"]); + } + + private async Task CreateTestUser() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = new() + { + Username = _testUsername, + Password = new HashService().HashString("TestPass123!"), + Libraries = [], + Created = DateTime.UtcNow + }; + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } +}