Adds authentication integration tests

This commit is contained in:
BinaryAlley committed 2024-11-12 21:57:19 +02:00
1 parent 4f91f29b62
commit 6d7d2f3c32
13 files changed
+1690 -6

No files matched your search

@@ -42,12 +42,12 @@ public class UserEntity : IStorageEntity
/// <summary>
/// Gets or sets the optional token used for account verification or password reset.
/// </summary>
public string? VerificationToken { get; set; }
public string? VerificationToken { get; set; } // TODO: to be deleted, not used
/// <summary>
/// Gets or sets the optional date and time when the verification token was created.
/// </summary>
public DateTime? VerificationTokenCreated { get; set; }
public DateTime? VerificationTokenCreated { get; set; } // TODO: to be deleted, not used
/// <summary>
/// Gets or sets the date and time when the temporary password used in password recovery was created.
@@ -50,6 +50,6 @@ public class SetupApplicationEndpoint : BaseEndpoint<RegistrationRequest, IResul
public override async Task<IResult> ExecuteAsync(RegistrationRequest request, CancellationToken cancellationToken)
{
ErrorOr<RegistrationResponse> 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);
}
}
@@ -50,6 +50,6 @@ public class RegisterEndpoint : BaseEndpoint<RegistrationRequest, IResult>
public override async Task<IResult> ExecuteAsync(RegistrationRequest request, CancellationToken cancellationToken)
{
ErrorOr<RegistrationResponse> 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);
}
}
@@ -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;
/// <summary>
/// Provides JWT token generation functionality for testing purposes.
/// </summary>
[ExcludeFromCodeCoverage]
public class JwtFixture
{
private static readonly string s_secretKey = "test-key-thats-at-least-32-chars-long-for-jwt";
/// <summary>
/// Generates a JWT token for testing with the specified username and optional roles.
/// </summary>
/// <param name="username">The username to include in the token claims.</param>
/// <param name="roles">Optional array of roles to include in the token claims.</param>
/// <returns>A JWT token string that can be used for authentication in tests.</returns>
public static string GenerateJwtToken(string username, string[]? roles = null)
{
byte[] key = Encoding.ASCII.GetBytes(s_secretKey);
List<Claim> 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);
}
}
@@ -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<Program>, IDisposable
{
private readonly SqliteConnection _connection;
private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=";
/// <summary>
/// Initializes a new instance of the <see cref="LuminaApiFactory"/> class.
@@ -50,7 +54,7 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
config.AddInMemoryCollection(initialData: new Dictionary<string, string?>
{
["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<Program>, IDisposable
services.Remove(descriptor);
// add SQLite DbContext configuration
services.AddDbContext<LuminaDbContext>(options => options.UseSqlite(_connection));
// configure JWT authentication for testing
services.PostConfigure<JwtBearerOptions>(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<Program>, IDisposable
dbContext.Database.Migrate();
}
});
}
}
/// <summary>
/// Disposes the connection to the database.
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="CheckInitializationEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CheckInitializationEndpointTests : IClassFixture<LuminaApiFactory>, 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;
/// <summary>
/// Initializes a new instance of the <see cref="CheckInitializationEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<InitializationResponse>(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<InitializationResponse>(content, _jsonOptions);
result.Should().NotBeNull();
result!.IsInitialized.Should().BeTrue();
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldThrowTaskCanceledException()
{
// Arrange
using CancellationTokenSource cts = new();
// Act
Func<Task> act = async () =>
{
cts.Cancel();
await _client.GetAsync("/api/v1/initialization", cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
private async Task<UserEntity> CreateTestUser()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="SetupApplicationEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetupApplicationEndpointTests : IClassFixture<LuminaApiFactory>, 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;
/// <summary>
/// Initializes a new instance of the <see cref="SetupApplicationEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<RegistrationResponse>(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<RegistrationResponse>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
Dictionary<string, string[]>? errors = problemDetails!["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation")
.WhoseValue.Should().Contain(["UsernameCannotBeEmpty", "PasswordCannotBeEmpty", "PasswordConfirmCannotBeEmpty"]);
}
private async Task<UserEntity> CreateTestUser()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="ChangePasswordEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ChangePasswordEndpointTests : IClassFixture<LuminaApiFactory>, 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;
/// <summary>
/// Initializes a new instance of the <see cref="ChangePasswordEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<ChangePasswordResponse>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_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<Task> act = async () =>
{
cts.Cancel();
await _client.PostAsJsonAsync("/api/v1/auth/change-password", request, cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
private async Task<UserEntity> CreateTestUser()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="LoginEndpoint"/> class.
/// </summary>
/// <remarks>
/// This test class needs to be separate from <see cref="LoginEndpointTests"/> because rate limiting is set per application run, not HTTP client instantiation.
/// </remarks>
[ExcludeFromCodeCoverage]
public class LoginEndpointRateLimitingTests : IClassFixture<LuminaApiFactory>, 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;
/// <summary>
/// Initializes a new instance of the <see cref="LoginEndpointRateLimitingTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<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();
lastResponse.StatusCode.Should().Be(HttpStatusCode.TooManyRequests);
string content = await lastResponse.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="LoginEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LoginEndpointTests : IClassFixture<LuminaApiFactory>, 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;
/// <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();
_hashService = new HashService();
_totpTokenGenerator = new TotpTokenGenerator();
_testUsername = $"testuser_{Guid.NewGuid()}";
using IServiceScope scope = apiFactory.Services.CreateScope();
_cryptographyService = scope.ServiceProvider.GetRequiredService<ICryptographyService>();
}
[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<LoginResponse>(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<LoginResponse>(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<LoginResponse>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation").WhoseValue.Should().Contain(["InvalidTotpCode"]);
}
private async Task<UserEntity> CreateTestUser()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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<UserEntity> CreateTestUserWithTotp()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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<UserEntity> CreateTestUserWithTempPassword()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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<UserEntity> CreateTestUserWithExpiredTempPassword()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="RecoverPasswordEndpoint"/> class.
/// </summary>
/// <remarks>
/// This test class needs to be separate from <see cref="RecoverPasswordEndpointTests"/> because rate limiting is set per application run, not HTTP client instantiation.
/// </remarks>
[ExcludeFromCodeCoverage]
public class RecoverPasswordEndpointRateLimitingTests : IClassFixture<LuminaApiFactory>, 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;
/// <summary>
/// Initializes a new instance of the <see cref="RecoverPasswordEndpointRateLimitingTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<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();
lastResponse.StatusCode.Should().Be(HttpStatusCode.TooManyRequests);
string content = await lastResponse.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="RecoverPasswordEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RecoverPasswordEndpointTests : IClassFixture<LuminaApiFactory>, 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;
/// <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();
_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<ICryptographyService>();
}
[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<RecoverPasswordResponse>(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<LuminaDbContext>();
// 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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_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<LuminaDbContext>();
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_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<Task> act = async () =>
{
cts.Cancel();
await _client.PostAsJsonAsync("/api/v1/auth/recover-password", request, cts.Token);
};
// Assert
await act.Should().ThrowAsync<TaskCanceledException>();
}
private async Task<UserEntity> CreateUserWithTotp()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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<UserEntity> CreateUserWithoutTotp()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="RegisterEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RegisterEndpointTests : IClassFixture<LuminaApiFactory>, 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;
/// <summary>
/// Initializes a new instance of the <see cref="RegisterEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<RegistrationResponse>(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<RegistrationResponse>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
Dictionary<string, string[]>? errors = problemDetails!["errors"].Deserialize<Dictionary<string, string[]>>(_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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
problemDetails.Should().NotBeNull();
Dictionary<string, string[]>? errors = problemDetails!["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
errors.Should().ContainKey("General.Validation")
.WhoseValue.Should().Contain(["UsernameCannotBeEmpty", "PasswordCannotBeEmpty", "PasswordConfirmCannotBeEmpty"]);
}
private async Task<UserEntity> CreateTestUser()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
}
}