mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 16:11:10 +00:00
Merge pull request #65 from BinaryAlley/feature/add-security-test-project
Adds security tests project
This commit is contained in:
7 files changed
+911
-102
No files matched your search
-88
@@ -1,88 +0,0 @@
|
|||||||
#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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+99
@@ -0,0 +1,99 @@
|
|||||||
|
#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.Diagnostics.CodeAnalysis;
|
||||||
|
using System.Text;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Factory for creating a web application for security tests.
|
||||||
|
/// </summary>
|
||||||
|
[ExcludeFromCodeCoverage]
|
||||||
|
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.
|
||||||
|
/// </summary>
|
||||||
|
public LuminaApiFactory()
|
||||||
|
{
|
||||||
|
_connection = new SqliteConnection("DataSource=:memory:");
|
||||||
|
_connection.Open();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Configures the web host for the security tests.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="builder">The web host builder to configure.</param>
|
||||||
|
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||||
|
{
|
||||||
|
builder.ConfigureAppConfiguration((context, config) =>
|
||||||
|
{
|
||||||
|
// clear all existing configuration sources
|
||||||
|
config.Sources.Clear();
|
||||||
|
|
||||||
|
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
|
||||||
|
config.AddJsonFile($"appsettings.test.json", optional: true, reloadOnChange: true);
|
||||||
|
config.AddJsonFile("appsettings.shared.json", optional: true, reloadOnChange: true);
|
||||||
|
config.AddJsonFile($"appsettings.shared.test.json", optional: true, reloadOnChange: true);
|
||||||
|
// First add the test values directly
|
||||||
|
config.AddInMemoryCollection(initialData: new Dictionary<string, string?>
|
||||||
|
{
|
||||||
|
["JwtSettings:SecretKey"] = "test-key-thats-at-least-32-chars-long-for-jwt",
|
||||||
|
["JwtSettings:ExpiryMinutes"] = "15", // control the expiry time during tests
|
||||||
|
["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY // base64 encoded test key
|
||||||
|
});
|
||||||
|
});
|
||||||
|
builder.ConfigureServices(services =>
|
||||||
|
{
|
||||||
|
// remove existing DbContext configuration
|
||||||
|
ServiceDescriptor? descriptor = services.SingleOrDefault(serviceDescriptor => serviceDescriptor.ServiceType == typeof(DbContextOptions<LuminaDbContext>));
|
||||||
|
if (descriptor is not null)
|
||||||
|
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())
|
||||||
|
{
|
||||||
|
IServiceProvider scopedServices = scope.ServiceProvider;
|
||||||
|
LuminaDbContext dbContext = scopedServices.GetRequiredService<LuminaDbContext>();
|
||||||
|
dbContext.Database.Migrate();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Disposes the connection to the database.
|
||||||
|
/// </summary>
|
||||||
|
public new void Dispose()
|
||||||
|
{
|
||||||
|
_connection.Close();
|
||||||
|
base.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
+157
@@ -0,0 +1,157 @@
|
|||||||
|
#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.SecurityTests.Common.Setup;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using System.IdentityModel.Tokens.Jwt;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Contains security tests for the <c>/auth/change-password</c> route.
|
||||||
|
/// </summary>
|
||||||
|
[ExcludeFromCodeCoverage]
|
||||||
|
public class AuthChangePasswordTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||||
|
{
|
||||||
|
private readonly LuminaApiFactory _apiFactory;
|
||||||
|
private readonly HttpClient _client;
|
||||||
|
private readonly HashService _hashService;
|
||||||
|
private readonly string _testUsername;
|
||||||
|
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||||
|
{
|
||||||
|
PropertyNameCaseInsensitive = true
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="AuthLoginTests"/> class.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||||
|
public AuthChangePasswordTests(LuminaApiFactory apiFactory)
|
||||||
|
{
|
||||||
|
_apiFactory = apiFactory;
|
||||||
|
_client = apiFactory.CreateClient();
|
||||||
|
_client.DefaultRequestHeaders.Clear();
|
||||||
|
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.12");
|
||||||
|
_hashService = new HashService();
|
||||||
|
_testUsername = $"testuser_{Guid.NewGuid()}";
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ChangePassword_WithoutAuthentication_ShouldReturn401()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
ChangePasswordRequest request = new(
|
||||||
|
Username: _testUsername,
|
||||||
|
CurrentPassword: "OldPass123!",
|
||||||
|
NewPassword: "NewPass123!",
|
||||||
|
NewPasswordConfirm: "NewPass123!"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ChangePassword_WithValidRequest_ShouldNotLeakTimingInformation()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
UserEntity user = await CreateAndAuthenticateUser();
|
||||||
|
Stopwatch stopwatch = new();
|
||||||
|
List<long> timings = [];
|
||||||
|
|
||||||
|
// Act
|
||||||
|
for (int i = 0; i < 10; i++)
|
||||||
|
{
|
||||||
|
await Task.Delay(100);
|
||||||
|
stopwatch.Restart();
|
||||||
|
await _client.PostAsJsonAsync("/api/v1/auth/change-password", new ChangePasswordRequest(
|
||||||
|
Username: user.Username,
|
||||||
|
CurrentPassword: "WrongPass123!",
|
||||||
|
NewPassword: "NewPass123!",
|
||||||
|
NewPasswordConfirm: "NewPass123!"
|
||||||
|
));
|
||||||
|
stopwatch.Stop();
|
||||||
|
timings.Add(stopwatch.ElapsedMilliseconds);
|
||||||
|
}
|
||||||
|
|
||||||
|
timings.Sort();
|
||||||
|
timings = timings.Skip(1).SkipLast(1).ToList(); // remove outliers
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
double stdDev = CalculateStandardDeviation(timings);
|
||||||
|
stdDev.Should().BeLessThan(200);
|
||||||
|
}
|
||||||
|
|
||||||
|
private double CalculateStandardDeviation(List<long> values)
|
||||||
|
{
|
||||||
|
double average = values.Average();
|
||||||
|
double sumOfSquaresOfDifferences = values.Select(value => (value - average) * (value - average)).Sum();
|
||||||
|
return Math.Sqrt(sumOfSquaresOfDifferences / values.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<UserEntity> CreateAndAuthenticateUser()
|
||||||
|
{
|
||||||
|
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||||
|
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||||
|
|
||||||
|
// create test user
|
||||||
|
UserEntity user = new()
|
||||||
|
{
|
||||||
|
Username = _testUsername,
|
||||||
|
Password = _hashService.HashString("TestPass123!"),
|
||||||
|
Libraries = [],
|
||||||
|
Created = DateTime.UtcNow
|
||||||
|
};
|
||||||
|
|
||||||
|
dbContext.Users.Add(user);
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
// authenticate user
|
||||||
|
LoginRequest loginRequest = new(
|
||||||
|
Username: user.Username,
|
||||||
|
Password: "TestPass123!"
|
||||||
|
);
|
||||||
|
|
||||||
|
HttpResponseMessage loginResponse = await _client.PostAsJsonAsync("/api/v1/auth/login", loginRequest);
|
||||||
|
string content = await loginResponse.Content.ReadAsStringAsync();
|
||||||
|
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||||
|
|
||||||
|
// set auth header for subsequent requests
|
||||||
|
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token);
|
||||||
|
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||||
|
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||||
|
|
||||||
|
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == _testUsername);
|
||||||
|
if (user is not null)
|
||||||
|
{
|
||||||
|
dbContext.Users.Remove(user);
|
||||||
|
dbContext.SaveChanges();
|
||||||
|
}
|
||||||
|
|
||||||
|
_client.DefaultRequestHeaders.Authorization = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
+350
@@ -0,0 +1,350 @@
|
|||||||
|
#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.SecurityTests.Common.Setup;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using System.IdentityModel.Tokens.Jwt;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Contains security tests for the <c>/auth/login</c> route.
|
||||||
|
/// </summary>
|
||||||
|
[ExcludeFromCodeCoverage]
|
||||||
|
public class AuthLoginTests : 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="AuthLoginTests"/> class.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||||
|
public AuthLoginTests(LuminaApiFactory apiFactory)
|
||||||
|
{
|
||||||
|
_apiFactory = apiFactory;
|
||||||
|
_client = apiFactory.CreateClient();
|
||||||
|
// set a fake IP for this test instance
|
||||||
|
_client.DefaultRequestHeaders.Clear();
|
||||||
|
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.1");
|
||||||
|
_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 Login_WithValidCredentials_ShouldAuthenticateSuccessfully()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
UserEntity user = await CreateTestUser();
|
||||||
|
LoginRequest request = new(
|
||||||
|
Username: user.Username,
|
||||||
|
Password: "TestPass123!"
|
||||||
|
);
|
||||||
|
DateTimeOffset beforeRequest = DateTimeOffset.UtcNow;
|
||||||
|
_client.DefaultRequestHeaders.Clear();
|
||||||
|
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.10");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
|
||||||
|
string content = await response.Content.ReadAsStringAsync();
|
||||||
|
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
JwtSecurityTokenHandler handler = new();
|
||||||
|
JwtSecurityToken token = handler.ReadJwtToken(result!.Token);
|
||||||
|
|
||||||
|
string expValue = token.Claims.First(c => c.Type == "exp").Value; // get token claims
|
||||||
|
DateTimeOffset tokenExpiration = DateTimeOffset.FromUnixTimeSeconds(long.Parse(expValue));
|
||||||
|
DateTimeOffset expectedExpiration = beforeRequest.AddMinutes(15);
|
||||||
|
|
||||||
|
// verify token duration (should be 15 minutes from request time - expiration value is set in tests setup class)
|
||||||
|
TimeSpan allowedVariance = TimeSpan.FromSeconds(30); // allow for processing time
|
||||||
|
TimeSpan actualDifference = tokenExpiration - beforeRequest;
|
||||||
|
TimeSpan expectedDifference = TimeSpan.FromMinutes(15);
|
||||||
|
|
||||||
|
actualDifference.Should().BeCloseTo(expectedDifference, precision: allowedVariance);
|
||||||
|
|
||||||
|
token.Header.Alg.Should().Be("HS256");
|
||||||
|
token.Claims.Should().Contain(c => c.Type == "sub" && c.Value == user.Id.ToString());
|
||||||
|
token.Claims.Should().Contain(c => c.Type == "unique_name" && c.Value == user.Username);
|
||||||
|
token.Claims.Should().Contain(c => c.Type == "jti");
|
||||||
|
token.Claims.Should().Contain(c => c.Type == "iss" && c.Value == "Lumina");
|
||||||
|
token.Claims.Should().Contain(c => c.Type == "aud" && c.Value == "Lumina");
|
||||||
|
|
||||||
|
content.Should().NotContain("password");
|
||||||
|
content.Should().NotContain("hash");
|
||||||
|
content.Should().NotContain("salt");
|
||||||
|
|
||||||
|
// TODO: implement more strict security checks:
|
||||||
|
// // check security headers
|
||||||
|
// response.Headers.Should().ContainKey("X-Content-Type-Options")
|
||||||
|
// .WhoseValue.Should().Contain("nosniff");
|
||||||
|
// response.Headers.Should().ContainKey("X-Frame-Options")
|
||||||
|
// .WhoseValue.Should().Contain("DENY");
|
||||||
|
// response.Headers.Should().ContainKey("X-XSS-Protection")
|
||||||
|
// .WhoseValue.Should().Contain("1; mode=block");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Login_WithValidCredentials_ShouldNotLeakTimingInformation()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
UserEntity user = await CreateTestUser();
|
||||||
|
Stopwatch stopwatch = new();
|
||||||
|
List<long> timings = [];
|
||||||
|
// since this test is rigged to trigger the rate limiting, assign a different IP to it
|
||||||
|
_client.DefaultRequestHeaders.Clear();
|
||||||
|
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.2");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
for (int i = 0; i < 10; i++)
|
||||||
|
{
|
||||||
|
await Task.Delay(100); // add small delay between requests
|
||||||
|
stopwatch.Restart();
|
||||||
|
await _client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(
|
||||||
|
Username: user.Username,
|
||||||
|
Password: "TestPass123!"
|
||||||
|
));
|
||||||
|
stopwatch.Stop();
|
||||||
|
timings.Add(stopwatch.ElapsedMilliseconds);
|
||||||
|
}
|
||||||
|
// remove the highest and lowest values to account for outliers
|
||||||
|
timings.Sort();
|
||||||
|
timings = timings.Skip(1).SkipLast(1).ToList();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
// check for timing consistency to prevent timing attacks
|
||||||
|
double stdDev = CalculateStandardDeviation(timings);
|
||||||
|
stdDev.Should().BeLessThan(200);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ExecuteAsync_WhenRateLimitExceeded_ShouldReturnTooManyRequests()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
// set a fake IP for this test instance
|
||||||
|
_client.DefaultRequestHeaders.Clear();
|
||||||
|
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.3");
|
||||||
|
LoginRequest request = 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!["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");
|
||||||
|
|
||||||
|
lastResponse.Headers.Should().ContainKey("X-RateLimit-Limit");
|
||||||
|
lastResponse.Headers.Should().ContainKey("X-RateLimit-Reset");
|
||||||
|
lastResponse.Headers.Should().ContainKey("X-RateLimit-Remaining");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||||
|
[InlineData("admin'--")] // comment injection
|
||||||
|
[InlineData("' UNION SELECT * FROM Users--")] // union injection
|
||||||
|
[InlineData("'; DROP TABLE Users--")] // destructive injection
|
||||||
|
[InlineData("' WAITFOR DELAY '0:0:10'--")] // time-based injection
|
||||||
|
public async Task Login_WithSQLInjectionAttempt_ShouldRemainSecure(string maliciousUsername)
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
UserEntity legitimateUser = await CreateTestUser();
|
||||||
|
LoginRequest request = new(
|
||||||
|
Username: maliciousUsername,
|
||||||
|
Password: "Abcd123$"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
|
||||||
|
string content = await response.Content.ReadAsStringAsync();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||||
|
content.Should().NotContain("SQL");
|
||||||
|
content.Should().NotContain("Exception");
|
||||||
|
content.Should().NotContain(legitimateUser.Username); // shouldn't expose other usernames
|
||||||
|
content.Should().NotContain(legitimateUser.Password); // shouldn't expose password hashes
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Login_WithSQLInjectionInValidUser_ShouldRemainSecure()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
UserEntity user = await CreateTestUser();
|
||||||
|
LoginRequest request = new(
|
||||||
|
Username: user.Username,
|
||||||
|
Password: "' OR '1'='1"
|
||||||
|
);
|
||||||
|
_client.DefaultRequestHeaders.Clear();
|
||||||
|
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.11");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
|
||||||
|
string content = await response.Content.ReadAsStringAsync();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||||
|
content.Should().NotContain("SQL");
|
||||||
|
content.Should().NotContain("Exception");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Login_WithInjectionInTotpCode_ShouldRemainSecure()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
UserEntity user = await CreateTestUserWithTotp();
|
||||||
|
LoginRequest request = new(
|
||||||
|
Username: user.Username,
|
||||||
|
Password: "TestPass123!",
|
||||||
|
TotpCode: "' OR '1'='1"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/login", request);
|
||||||
|
string content = await response.Content.ReadAsStringAsync();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
|
||||||
|
content.Should().NotContain("SQL");
|
||||||
|
content.Should().NotContain("Exception");
|
||||||
|
}
|
||||||
|
|
||||||
|
private double CalculateStandardDeviation(List<long> values)
|
||||||
|
{
|
||||||
|
double average = values.Average();
|
||||||
|
double sumOfSquaresOfDifferences = values.Select(value => (value - average) * (value - average)).Sum();
|
||||||
|
return Math.Sqrt(sumOfSquaresOfDifferences / values.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+13
-14
@@ -3,31 +3,23 @@ using FluentAssertions;
|
|||||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||||
using Lumina.Contracts.Requests.Authentication;
|
using Lumina.Contracts.Requests.Authentication;
|
||||||
using Lumina.DataAccess.Core.UoW;
|
using Lumina.DataAccess.Core.UoW;
|
||||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
using System.Linq;
|
|
||||||
using System.Net;
|
using System.Net;
|
||||||
using System.Net.Http;
|
|
||||||
using System.Net.Http.Json;
|
using System.Net.Http.Json;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
using System.Threading.Tasks;
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Authentication;
|
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Contains integration tests for the <see cref="RecoverPasswordEndpoint"/> class.
|
/// Contains security tests for the <c>/auth/recover-password</c> route.
|
||||||
/// </summary>
|
/// </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]
|
[ExcludeFromCodeCoverage]
|
||||||
public class RecoverPasswordEndpointRateLimitingTests : IClassFixture<LuminaApiFactory>, IDisposable
|
public class AuthRecoverPasswordTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||||
{
|
{
|
||||||
private readonly LuminaApiFactory _apiFactory;
|
private readonly LuminaApiFactory _apiFactory;
|
||||||
private readonly HttpClient _client;
|
private readonly HttpClient _client;
|
||||||
@@ -39,13 +31,16 @@ public class RecoverPasswordEndpointRateLimitingTests : IClassFixture<LuminaApiF
|
|||||||
private readonly string _testUsername;
|
private readonly string _testUsername;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Initializes a new instance of the <see cref="RecoverPasswordEndpointRateLimitingTests"/> class.
|
/// Initializes a new instance of the <see cref="AuthRecoverPasswordTests"/> class.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||||
public RecoverPasswordEndpointRateLimitingTests(LuminaApiFactory apiFactory)
|
public AuthRecoverPasswordTests(LuminaApiFactory apiFactory)
|
||||||
{
|
{
|
||||||
_apiFactory = apiFactory;
|
_apiFactory = apiFactory;
|
||||||
_client = apiFactory.CreateClient();
|
_client = apiFactory.CreateClient();
|
||||||
|
// set a fake IP for this test instance
|
||||||
|
_client.DefaultRequestHeaders.Clear();
|
||||||
|
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.4");
|
||||||
_testUsername = $"testuser_{Guid.NewGuid()}";
|
_testUsername = $"testuser_{Guid.NewGuid()}";
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,6 +70,10 @@ public class RecoverPasswordEndpointRateLimitingTests : IClassFixture<LuminaApiF
|
|||||||
problemDetails["title"].GetString().Should().Be("TooManyRequests");
|
problemDetails["title"].GetString().Should().Be("TooManyRequests");
|
||||||
problemDetails["detail"].GetString().Should().Be("Too many attempts. Please try again later.");
|
problemDetails["detail"].GetString().Should().Be("Too many attempts. Please try again later.");
|
||||||
problemDetails["retryAfter"].GetString().Should().Be("15");
|
problemDetails["retryAfter"].GetString().Should().Be("15");
|
||||||
|
|
||||||
|
lastResponse.Headers.Should().ContainKey("X-RateLimit-Limit");
|
||||||
|
lastResponse.Headers.Should().ContainKey("X-RateLimit-Reset");
|
||||||
|
lastResponse.Headers.Should().ContainKey("X-RateLimit-Remaining");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
+246
@@ -0,0 +1,246 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using FluentAssertions;
|
||||||
|
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||||
|
using Lumina.Contracts.Requests.Authentication;
|
||||||
|
using Lumina.DataAccess.Core.UoW;
|
||||||
|
using Lumina.Infrastructure.Core.Security;
|
||||||
|
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authentication;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Contains security tests for the <c>/auth/register</c> route.
|
||||||
|
/// </summary>
|
||||||
|
[ExcludeFromCodeCoverage]
|
||||||
|
public class AuthRegisterTests : 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;
|
||||||
|
|
||||||
|
public AuthRegisterTests(LuminaApiFactory apiFactory)
|
||||||
|
{
|
||||||
|
_apiFactory = apiFactory;
|
||||||
|
_client = apiFactory.CreateClient();
|
||||||
|
_client.DefaultRequestHeaders.Clear();
|
||||||
|
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.5");
|
||||||
|
_hashService = new HashService();
|
||||||
|
_testUsername = $"testuser_{Guid.NewGuid()}";
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Register_WithValidData_ShouldNotLeakTimingInformation()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
Stopwatch stopwatch = new();
|
||||||
|
List<long> timings = [];
|
||||||
|
_client.DefaultRequestHeaders.Clear();
|
||||||
|
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.6");
|
||||||
|
RegistrationRequest request = new(
|
||||||
|
Username: _testUsername,
|
||||||
|
Password: "TestPass123!",
|
||||||
|
PasswordConfirm: "TestPass123!"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
for (int i = 0; i < 10; i++)
|
||||||
|
{
|
||||||
|
await Task.Delay(100);
|
||||||
|
stopwatch.Restart();
|
||||||
|
await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||||
|
stopwatch.Stop();
|
||||||
|
timings.Add(stopwatch.ElapsedMilliseconds);
|
||||||
|
}
|
||||||
|
timings.Sort();
|
||||||
|
timings = timings.Skip(1).SkipLast(1).ToList();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
double stdDev = CalculateStandardDeviation(timings);
|
||||||
|
stdDev.Should().BeLessThan(200);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Register_WhenRateLimitExceeded_ShouldReturnTooManyRequests()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
_client.DefaultRequestHeaders.Clear();
|
||||||
|
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.7");
|
||||||
|
RegistrationRequest request = new(
|
||||||
|
Username: _testUsername,
|
||||||
|
Password: "TestPass123!",
|
||||||
|
PasswordConfirm: "TestPass123!"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
List<HttpResponseMessage> responses = [];
|
||||||
|
for (int i = 0; i < 11; i++)
|
||||||
|
responses.Add(await _client.PostAsJsonAsync("/api/v1/auth/register", request));
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
HttpResponseMessage lastResponse = responses.Last();
|
||||||
|
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");
|
||||||
|
|
||||||
|
lastResponse.Headers.Should().ContainKey("X-RateLimit-Limit");
|
||||||
|
lastResponse.Headers.Should().ContainKey("X-RateLimit-Reset");
|
||||||
|
lastResponse.Headers.Should().ContainKey("X-RateLimit-Remaining");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("' OR '1'='1")] // basic SQL injection
|
||||||
|
[InlineData("admin'--")] // comment injection
|
||||||
|
[InlineData("' UNION SELECT * FROM Users--")] // union injection
|
||||||
|
[InlineData("'; DROP TABLE Users--")] // destructive injection
|
||||||
|
[InlineData("' WAITFOR DELAY '0:0:10'--")] // time-based injection
|
||||||
|
public async Task Register_WithSQLInjectionAttempt_ShouldRemainSecure(string maliciousUsername)
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
RegistrationRequest request = new(
|
||||||
|
Username: maliciousUsername,
|
||||||
|
Password: "TestPass123!",
|
||||||
|
PasswordConfirm: "TestPass123!"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||||
|
string content = await response.Content.ReadAsStringAsync();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
|
||||||
|
content.Should().NotContain("SQL");
|
||||||
|
content.Should().NotContain("Exception");
|
||||||
|
content.Should().NotContain("password");
|
||||||
|
content.Should().NotContain("hash");
|
||||||
|
content.Should().NotContain("salt");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("password123")] // common password
|
||||||
|
[InlineData("123456789")] // numeric only
|
||||||
|
[InlineData("abcdefgh")] // lowercase only
|
||||||
|
[InlineData("short")] // too short
|
||||||
|
public async Task Register_WithWeakPassword_ShouldBeDenied(string weakPassword)
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
RegistrationRequest request = new(
|
||||||
|
Username: _testUsername,
|
||||||
|
Password: weakPassword,
|
||||||
|
PasswordConfirm: weakPassword
|
||||||
|
);
|
||||||
|
_client.DefaultRequestHeaders.Clear();
|
||||||
|
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.8");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||||
|
string content = await response.Content.ReadAsStringAsync();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
response.StatusCode.Should().Be(HttpStatusCode.UnprocessableContent);
|
||||||
|
content.Should().NotContain(weakPassword); // shouldn't leak the actual password
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("TestPass123!")] // valid password
|
||||||
|
[InlineData("Ab1!defghijklmnopqrstuvwxyz")] // long password
|
||||||
|
public async Task Register_WithValidPassword_ShouldAcceptPassword(string password)
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
RegistrationRequest request = new(
|
||||||
|
Username: _testUsername,
|
||||||
|
Password: password,
|
||||||
|
PasswordConfirm: password
|
||||||
|
);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
response.StatusCode.Should().Be(HttpStatusCode.Created);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Register_WithExistingUsername_ShouldNotLeakUserExistence()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
await CreateTestUser();
|
||||||
|
RegistrationRequest request = new(
|
||||||
|
Username: _testUsername,
|
||||||
|
Password: "TestPass123!",
|
||||||
|
PasswordConfirm: "TestPass123!"
|
||||||
|
);
|
||||||
|
_client.DefaultRequestHeaders.Clear();
|
||||||
|
_client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.9");
|
||||||
|
|
||||||
|
// Act
|
||||||
|
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/register", request);
|
||||||
|
string content = await response.Content.ReadAsStringAsync();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
response.StatusCode.Should().Be(HttpStatusCode.Conflict);
|
||||||
|
content.Should().NotContain(_testUsername);
|
||||||
|
content.Should().NotContain("password");
|
||||||
|
content.Should().NotContain("hash");
|
||||||
|
content.Should().NotContain("salt");
|
||||||
|
}
|
||||||
|
|
||||||
|
private double CalculateStandardDeviation(List<long> values)
|
||||||
|
{
|
||||||
|
double average = values.Average();
|
||||||
|
double sumOfSquaresOfDifferences = values.Select(value => (value - average) * (value - average)).Sum();
|
||||||
|
return Math.Sqrt(sumOfSquaresOfDifferences / values.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
<IsTestProject>true</IsTestProject>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
|
||||||
|
<_Parameter1>DisableTestParallelization = true</_Parameter1>
|
||||||
|
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
|
||||||
|
</AssemblyAttribute>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="AutoFixture.AutoNSubstitute" Version="4.18.1" />
|
||||||
|
<PackageReference Include="AutoFixture.Xunit2" Version="4.18.1" />
|
||||||
|
<PackageReference Include="Bogus" Version="35.6.0" />
|
||||||
|
<PackageReference Include="coverlet.collector" Version="6.0.2">
|
||||||
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
</PackageReference>
|
||||||
|
<PackageReference Include="FluentAssertions" Version="6.12.1" />
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.10" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.1" />
|
||||||
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
|
||||||
|
<PackageReference Include="NSubstitute" Version="5.1.0" />
|
||||||
|
<PackageReference Include="xunit" Version="2.9.2" />
|
||||||
|
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
|
||||||
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
</PackageReference>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Using Include="Xunit" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\..\..\src\Lumina.Presentation.Api\Lumina.Presentation.Api.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
Reference in new issue
Block a user