mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 01:11:10 +00:00
Updates to .NET 9.0
This commit is contained in:
commit
acbdb0a5f8
853 files changed
+34993
-10123
No files matched your search
+2
-3
@@ -10,7 +10,6 @@ using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CommonSettingsModelValidator"/> class.
|
||||
/// </summary>
|
||||
@@ -59,6 +58,6 @@ public class CommonSettingsModelValidatorTests
|
||||
// Assert
|
||||
result.IsValid.Should().BeFalse();
|
||||
result.Errors.Should().ContainSingle()
|
||||
.Which.ErrorMessage.Should().Be(Errors.Configuration.ApplicationThemeCannotBeEmpty.Code);
|
||||
.Which.ErrorMessage.Should().Be(Errors.Configuration.ApplicationThemeCannotBeEmpty.Description);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -58,6 +58,6 @@ public class DatabaseSettingsModelValidatorTests
|
||||
// Assert
|
||||
result.IsValid.Should().BeFalse();
|
||||
result.Errors.Should().ContainSingle()
|
||||
.Which.ErrorMessage.Should().Be(Errors.Configuration.DatabaseConnectionStringCannotBeEmpty.Code);
|
||||
.Which.ErrorMessage.Should().Be(Errors.Configuration.DatabaseConnectionStringCannotBeEmpty.Description);
|
||||
}
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using FluentAssertions;
|
||||
using Lumina.Infrastructure.Common.Errors;
|
||||
using Lumina.Infrastructure.Common.Models.Configuration;
|
||||
using Lumina.Infrastructure.Common.Validators;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="EncryptionSettingsModelValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class EncryptionSettingsModelValidatorTests
|
||||
{
|
||||
private readonly EncryptionSettingsModelValidator _validator;
|
||||
private readonly IFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EncryptionSettingsModelValidatorTests"/> class.
|
||||
/// </summary>
|
||||
public EncryptionSettingsModelValidatorTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
_validator = new();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EncryptionSettingsModelValidator_WhenValidBase64SecretKeyProvided_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
EncryptionSettingsModel model = _fixture.Build<EncryptionSettingsModel>()
|
||||
.With(x => x.SecretKey, "dGhpcyBpcyBhIHZhbGlkIGJhc2U2NCBzdHJpbmc=") // "this is a valid base64 string" in base64
|
||||
.Create();
|
||||
|
||||
// Act
|
||||
FluentValidation.Results.ValidationResult result = _validator.Validate(model);
|
||||
|
||||
// Assert
|
||||
result.IsValid.Should().BeTrue();
|
||||
result.Errors.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EncryptionSettingsModelValidator_WhenSecretKeyIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
EncryptionSettingsModel model = _fixture.Build<EncryptionSettingsModel>()
|
||||
.With(x => x.SecretKey, string.Empty)
|
||||
.Create();
|
||||
|
||||
// Act
|
||||
FluentValidation.Results.ValidationResult result = _validator.Validate(model);
|
||||
|
||||
// Assert
|
||||
result.IsValid.Should().BeFalse();
|
||||
result.Errors.Should().ContainSingle()
|
||||
.Which.ErrorMessage.Should().Be(Errors.Configuration.EncryptionSecretKeyCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("not-a-base64-string")]
|
||||
[InlineData("invalid!base64")]
|
||||
[InlineData("123")]
|
||||
public void EncryptionSettingsModelValidator_WhenSecretKeyIsNotBase64_ShouldHaveValidationError(string invalidBase64)
|
||||
{
|
||||
// Arrange
|
||||
EncryptionSettingsModel model = _fixture.Build<EncryptionSettingsModel>()
|
||||
.With(x => x.SecretKey, invalidBase64)
|
||||
.Create();
|
||||
|
||||
// Act
|
||||
FluentValidation.Results.ValidationResult result = _validator.Validate(model);
|
||||
|
||||
// Assert
|
||||
result.IsValid.Should().BeFalse();
|
||||
result.Errors.Should().ContainSingle()
|
||||
.Which.ErrorMessage.Should().Be(Errors.Configuration.EncryptionSecretKeyMustBeABase64String.Description);
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using FluentAssertions;
|
||||
using Lumina.Infrastructure.Common.Errors;
|
||||
using Lumina.Infrastructure.Common.Models.Configuration;
|
||||
using Lumina.Infrastructure.Common.Validators;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="JwtSettingsModelValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class JwtSettingsModelValidatorTests
|
||||
{
|
||||
private readonly JwtSettingsModelValidator _validator;
|
||||
private readonly IFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JwtSettingsModelValidatorTests"/> class.
|
||||
/// </summary>
|
||||
public JwtSettingsModelValidatorTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
_validator = new();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void JwtSettingsModelValidator_WhenAllPropertiesValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
JwtSettingsModel model = _fixture.Build<JwtSettingsModel>()
|
||||
.With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing")
|
||||
.With(x => x.ExpiryMinutes, 30)
|
||||
.With(x => x.Issuer, "test-issuer")
|
||||
.With(x => x.Audience, "test-audience")
|
||||
.Create();
|
||||
|
||||
// Act
|
||||
FluentValidation.Results.ValidationResult result = _validator.Validate(model);
|
||||
|
||||
// Assert
|
||||
result.IsValid.Should().BeTrue();
|
||||
result.Errors.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void JwtSettingsModelValidator_WhenSecretKeyIsEmpty_ShouldHaveValidationErrors()
|
||||
{
|
||||
// Arrange
|
||||
JwtSettingsModel model = _fixture.Build<JwtSettingsModel>()
|
||||
.With(x => x.SecretKey, string.Empty)
|
||||
.With(x => x.ExpiryMinutes, 30)
|
||||
.With(x => x.Issuer, "test-issuer")
|
||||
.With(x => x.Audience, "test-audience")
|
||||
.Create();
|
||||
|
||||
// Act
|
||||
FluentValidation.Results.ValidationResult result = _validator.Validate(model);
|
||||
|
||||
// Assert
|
||||
result.IsValid.Should().BeFalse();
|
||||
result.Errors.Should().HaveCount(2);
|
||||
result.Errors.Select(e => e.ErrorMessage).Should().Contain(new[]
|
||||
{
|
||||
Errors.Configuration.JwtSecretKeyCannotBeEmpty.Description,
|
||||
Errors.Configuration.JwtSecretKeyTooShort.Description
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void JwtSettingsModelValidator_WhenSecretKeyTooShort_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
JwtSettingsModel model = _fixture.Build<JwtSettingsModel>()
|
||||
.With(x => x.SecretKey, "short-key")
|
||||
.With(x => x.ExpiryMinutes, 30)
|
||||
.With(x => x.Issuer, "test-issuer")
|
||||
.With(x => x.Audience, "test-audience")
|
||||
.Create();
|
||||
|
||||
// Act
|
||||
FluentValidation.Results.ValidationResult result = _validator.Validate(model);
|
||||
|
||||
// Assert
|
||||
result.IsValid.Should().BeFalse();
|
||||
result.Errors.Should().ContainSingle()
|
||||
.Which.ErrorMessage.Should().Be(Errors.Configuration.JwtSecretKeyTooShort.Description);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(-1)]
|
||||
[InlineData(-60)]
|
||||
public void JwtSettingsModelValidator_WhenExpiryMinutesNotPositive_ShouldHaveValidationError(int minutes)
|
||||
{
|
||||
// Arrange
|
||||
JwtSettingsModel model = _fixture.Build<JwtSettingsModel>()
|
||||
.With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing")
|
||||
.With(x => x.ExpiryMinutes, minutes)
|
||||
.With(x => x.Issuer, "test-issuer")
|
||||
.With(x => x.Audience, "test-audience")
|
||||
.Create();
|
||||
|
||||
// Act
|
||||
FluentValidation.Results.ValidationResult result = _validator.Validate(model);
|
||||
|
||||
// Assert
|
||||
result.IsValid.Should().BeFalse();
|
||||
result.Errors.Should().ContainSingle()
|
||||
.Which.ErrorMessage.Should().Be(Errors.Configuration.JwtExpiryMinutesMustBePositive.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void JwtSettingsModelValidator_WhenIssuerIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
JwtSettingsModel model = _fixture.Build<JwtSettingsModel>()
|
||||
.With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing")
|
||||
.With(x => x.ExpiryMinutes, 30)
|
||||
.With(x => x.Issuer, string.Empty)
|
||||
.With(x => x.Audience, "test-audience")
|
||||
.Create();
|
||||
|
||||
// Act
|
||||
FluentValidation.Results.ValidationResult result = _validator.Validate(model);
|
||||
|
||||
// Assert
|
||||
result.IsValid.Should().BeFalse();
|
||||
result.Errors.Should().ContainSingle()
|
||||
.Which.ErrorMessage.Should().Be(Errors.Configuration.JwtIssuerCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void JwtSettingsModelValidator_WhenAudienceIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
JwtSettingsModel model = _fixture.Build<JwtSettingsModel>()
|
||||
.With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing")
|
||||
.With(x => x.ExpiryMinutes, 30)
|
||||
.With(x => x.Issuer, "test-issuer")
|
||||
.With(x => x.Audience, string.Empty)
|
||||
.Create();
|
||||
|
||||
// Act
|
||||
FluentValidation.Results.ValidationResult result = _validator.Validate(model);
|
||||
|
||||
// Assert
|
||||
result.IsValid.Should().BeFalse();
|
||||
result.Errors.Should().ContainSingle()
|
||||
.Which.ErrorMessage.Should().Be(Errors.Configuration.JwtAudienceCannotBeEmpty.Description);
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using FluentAssertions;
|
||||
using Lumina.Infrastructure.Common.Errors;
|
||||
using Lumina.Infrastructure.Common.Models.Configuration;
|
||||
using Lumina.Infrastructure.Common.Validators;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaSettingsModelValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaSettingsModelValidatorTests
|
||||
{
|
||||
private readonly MediaSettingsModelValidator _validator;
|
||||
private readonly IFixture _fixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaSettingsModelValidatorTests"/> class.
|
||||
/// </summary>
|
||||
public MediaSettingsModelValidatorTests()
|
||||
{
|
||||
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
|
||||
_validator = new();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MediaSettingsModelValidator_WhenRootDirectoryProvided_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
MediaSettingsModel model = _fixture.Build<MediaSettingsModel>()
|
||||
.With(x => x.RootDirectory, "/path/to/media")
|
||||
.Create();
|
||||
|
||||
// Act
|
||||
FluentValidation.Results.ValidationResult result = _validator.Validate(model);
|
||||
|
||||
// Assert
|
||||
result.IsValid.Should().BeTrue();
|
||||
result.Errors.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MediaSettingsModelValidator_WhenRootDirectoryIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
MediaSettingsModel model = _fixture.Build<MediaSettingsModel>()
|
||||
.With(x => x.RootDirectory, string.Empty)
|
||||
.Create();
|
||||
|
||||
// Act
|
||||
FluentValidation.Results.ValidationResult result = _validator.Validate(model);
|
||||
|
||||
// Assert
|
||||
result.IsValid.Should().BeFalse();
|
||||
result.Errors.Should().ContainSingle()
|
||||
.Which.ErrorMessage.Should().Be(Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MediaSettingsModelValidator_WhenRootDirectoryIsWhitespace_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
MediaSettingsModel model = _fixture.Build<MediaSettingsModel>()
|
||||
.With(x => x.RootDirectory, " ")
|
||||
.Create();
|
||||
|
||||
// Act
|
||||
FluentValidation.Results.ValidationResult result = _validator.Validate(model);
|
||||
|
||||
// Assert
|
||||
result.IsValid.Should().BeFalse();
|
||||
result.Errors.Should().ContainSingle()
|
||||
.Which.ErrorMessage.Should().Be(Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description);
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Infrastructure.Common.Models.Configuration;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for JWT token generation tests.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class JwtTokenGeneratorFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a valid JWT settings model for testing.
|
||||
/// </summary>
|
||||
/// <returns>The created settings model.</returns>
|
||||
public static JwtSettingsModel CreateJwtSettings()
|
||||
{
|
||||
return new Faker<JwtSettingsModel>()
|
||||
.CustomInstantiator(f => new JwtSettingsModel
|
||||
{
|
||||
SecretKey = "this-is-a-very-long-secret-key-for-testing-jwt-tokens",
|
||||
ExpiryMinutes = 30,
|
||||
Issuer = "test-issuer",
|
||||
Audience = "test-audience"
|
||||
})
|
||||
.Generate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates test user credentials.
|
||||
/// </summary>
|
||||
/// <returns>A tuple containing the user ID and username.</returns>
|
||||
public static (string Id, string Username) CreateUserCredentials()
|
||||
{
|
||||
return (Guid.NewGuid().ToString(), new Faker().Person.UserName);
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for QR code generation tests.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class QRCodeGeneratorFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates test data for QR code generation.
|
||||
/// </summary>
|
||||
/// <returns>A tuple containing username and secret bytes.</returns>
|
||||
public static (string Username, byte[] Secret) CreateQrCodeTestData()
|
||||
{
|
||||
string username = new Faker().Person.UserName;
|
||||
byte[] secret = new byte[20]; // Standard TOTP secret length
|
||||
new Random().NextBytes(secret);
|
||||
return (username, secret);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the expected otpauth URI format for validation.
|
||||
/// </summary>
|
||||
/// <param name="username">The username to use in the URI.</param>
|
||||
/// <param name="base32Secret">The Base32 encoded secret.</param>
|
||||
/// <returns>The formatted otpauth URI.</returns>
|
||||
public static string GetExpectedOtpauthUri(string username, string base32Secret)
|
||||
{
|
||||
return $"otpauth://totp/Lumina:{Uri.EscapeDataString(username)}?secret={base32Secret}&issuer=Lumina";
|
||||
}
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Infrastructure.Common.Models.Configuration;
|
||||
using Lumina.Infrastructure.Core.Authentication;
|
||||
using Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="JwtTokenGenerator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class JwtTokenGeneratorTests
|
||||
{
|
||||
private readonly IDateTimeProvider _mockDateTimeProvider;
|
||||
private readonly JwtSettingsModel _jwtSettings;
|
||||
private readonly JwtTokenGenerator _sut;
|
||||
private readonly DateTime _fixedUtcNow;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JwtTokenGeneratorTests"/> class.
|
||||
/// </summary>
|
||||
public JwtTokenGeneratorTests()
|
||||
{
|
||||
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
|
||||
_jwtSettings = JwtTokenGeneratorFixture.CreateJwtSettings();
|
||||
_fixedUtcNow = new DateTime(2024, 1, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
_mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow);
|
||||
|
||||
IOptions<JwtSettingsModel> options = Substitute.For<IOptions<JwtSettingsModel>>();
|
||||
options.Value.Returns(_jwtSettings);
|
||||
|
||||
_sut = new JwtTokenGenerator(_mockDateTimeProvider, options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateToken_WhenCalled_ShouldCreateValidJwtToken()
|
||||
{
|
||||
// Arrange
|
||||
(string userId, string username) = JwtTokenGeneratorFixture.CreateUserCredentials();
|
||||
JwtSecurityTokenHandler tokenHandler = new();
|
||||
|
||||
// Act
|
||||
string token = _sut.GenerateToken(userId, username);
|
||||
|
||||
// Assert
|
||||
token.Should().NotBeNullOrEmpty();
|
||||
|
||||
JwtSecurityToken jwtToken = tokenHandler.ReadJwtToken(token);
|
||||
|
||||
// verify token properties
|
||||
jwtToken.Issuer.Should().Be(_jwtSettings.Issuer);
|
||||
jwtToken.Audiences.Should().ContainSingle().Which.Should().Be(_jwtSettings.Audience);
|
||||
jwtToken.ValidTo.Should().Be(_fixedUtcNow.AddMinutes(_jwtSettings.ExpiryMinutes));
|
||||
|
||||
// verify claims
|
||||
jwtToken.Claims.Should().Contain(c => c.Type == JwtRegisteredClaimNames.Sub && c.Value == userId);
|
||||
jwtToken.Claims.Should().Contain(c => c.Type == JwtRegisteredClaimNames.UniqueName && c.Value == username);
|
||||
jwtToken.Claims.Should().Contain(c => c.Type == JwtRegisteredClaimNames.Jti && c.Value == userId);
|
||||
|
||||
// verify the token is actually valid
|
||||
TokenValidationParameters validationParameters = new()
|
||||
{
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey)),
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = _jwtSettings.Issuer,
|
||||
ValidateAudience = true,
|
||||
ValidAudience = _jwtSettings.Audience,
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.Zero,
|
||||
// override the current time to match our fixed test time
|
||||
LifetimeValidator = (notBefore, expires, token, parameters) => expires > _fixedUtcNow
|
||||
};
|
||||
|
||||
ClaimsPrincipal principal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);
|
||||
|
||||
principal.Should().NotBeNull();
|
||||
validatedToken.Should().NotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateToken_WhenCalled_ShouldUseProvidedDateTimeForExpiration()
|
||||
{
|
||||
// Arrange
|
||||
(string userId, string username) = JwtTokenGeneratorFixture.CreateUserCredentials();
|
||||
JwtSecurityTokenHandler tokenHandler = new();
|
||||
|
||||
// Act
|
||||
string token = _sut.GenerateToken(userId, username);
|
||||
JwtSecurityToken jwtToken = tokenHandler.ReadJwtToken(token);
|
||||
|
||||
// Assert
|
||||
jwtToken.ValidTo.Should().Be(_fixedUtcNow.AddMinutes(_jwtSettings.ExpiryMinutes));
|
||||
_ = _mockDateTimeProvider.Received(1).UtcNow;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateToken_WhenCalledWithDifferentUsers_ShouldCreateUniqueTokens()
|
||||
{
|
||||
// Arrange
|
||||
(string userId1, string username1) = JwtTokenGeneratorFixture.CreateUserCredentials();
|
||||
(string userId2, string username2) = JwtTokenGeneratorFixture.CreateUserCredentials();
|
||||
|
||||
// Act
|
||||
string token1 = _sut.GenerateToken(userId1, username1);
|
||||
string token2 = _sut.GenerateToken(userId2, username2);
|
||||
|
||||
// Assert
|
||||
token1.Should().NotBe(token2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateToken_WhenCalledMultipleTimesForSameUser_ShouldCreateIdenticalTokens()
|
||||
{
|
||||
// Arrange
|
||||
(string userId, string username) = JwtTokenGeneratorFixture.CreateUserCredentials();
|
||||
|
||||
// Act
|
||||
string token1 = _sut.GenerateToken(userId, username);
|
||||
string token2 = _sut.GenerateToken(userId, username);
|
||||
|
||||
// Assert
|
||||
token1.Should().Be(token2);
|
||||
}
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using AutoFixture;
|
||||
using AutoFixture.AutoNSubstitute;
|
||||
using FluentAssertions;
|
||||
using Lumina.Infrastructure.Common.Errors;
|
||||
using Lumina.Infrastructure.Common.Models.Configuration;
|
||||
using Lumina.Infrastructure.Common.Validators;
|
||||
using Lumina.Infrastructure.Core.Authentication;
|
||||
using Lumina.Infrastructure.UnitTests.Core.Authentication.Fixtures;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="QRCodeGenerator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class QRCodeGeneratorTests
|
||||
{
|
||||
private readonly QRCodeGenerator _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="QRCodeGeneratorTests"/> class.
|
||||
/// </summary>
|
||||
public QRCodeGeneratorTests()
|
||||
{
|
||||
_sut = new QRCodeGenerator();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateQrCodeDataUri_WhenCalled_ShouldReturnValidDataUri()
|
||||
{
|
||||
// Arrange
|
||||
(string username, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData();
|
||||
|
||||
// Act
|
||||
string result = _sut.GenerateQrCodeDataUri(username, secret);
|
||||
|
||||
// Assert
|
||||
result.Should().StartWith("data:image/png;base64,");
|
||||
result.Should().Match(uri => IsBase64String(uri.Substring(22))); // Skip "data:image/png;base64,"
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateQrCodeDataUri_WhenUsernameContainsSpecialCharacters_ShouldEscapeUsername()
|
||||
{
|
||||
// Arrange
|
||||
string username = "user@example.com";
|
||||
(_, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData();
|
||||
|
||||
// Act
|
||||
string result = _sut.GenerateQrCodeDataUri(username, secret);
|
||||
|
||||
// Assert
|
||||
result.Should().StartWith("data:image/png;base64,");
|
||||
result.Should().Match(uri => IsBase64String(uri.Substring(22)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateQrCodeDataUri_WhenCalled_ShouldGenerateUniqueQrCodesForDifferentUsers()
|
||||
{
|
||||
// Arrange
|
||||
(string username1, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData();
|
||||
string username2 = username1 + "_different";
|
||||
|
||||
// Act
|
||||
string result1 = _sut.GenerateQrCodeDataUri(username1, secret);
|
||||
string result2 = _sut.GenerateQrCodeDataUri(username2, secret);
|
||||
|
||||
// Assert
|
||||
result1.Should().NotBe(result2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateQrCodeDataUri_WhenCalledWithSameInput_ShouldGenerateIdenticalQrCodes()
|
||||
{
|
||||
// Arrange
|
||||
(string username, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData();
|
||||
|
||||
// Act
|
||||
string result1 = _sut.GenerateQrCodeDataUri(username, secret);
|
||||
string result2 = _sut.GenerateQrCodeDataUri(username, secret);
|
||||
|
||||
// Assert
|
||||
result1.Should().Be(result2);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public void GenerateQrCodeDataUri_WhenUsernameIsInvalid_ShouldStillGenerateQrCode(string? invalidUsername)
|
||||
{
|
||||
// Arrange
|
||||
(_, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData();
|
||||
|
||||
// Act
|
||||
string result = _sut.GenerateQrCodeDataUri(invalidUsername!, secret);
|
||||
|
||||
// Assert
|
||||
result.Should().StartWith("data:image/png;base64,");
|
||||
result.Should().Match(uri => IsBase64String(uri.Substring(22)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("user@example.com")]
|
||||
[InlineData("user name with spaces")]
|
||||
[InlineData("user+with+plus")]
|
||||
[InlineData("user/with/slashes")]
|
||||
public void GenerateQrCodeDataUri_WhenUsernameHasSpecialCharacters_ShouldStillGenerateQrCode(string username)
|
||||
{
|
||||
// Arrange
|
||||
(_, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData();
|
||||
|
||||
// Act
|
||||
string result = _sut.GenerateQrCodeDataUri(username, secret);
|
||||
|
||||
// Assert
|
||||
result.Should().StartWith("data:image/png;base64,");
|
||||
result.Should().Match(uri => IsBase64String(uri.Substring(22)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateQrCodeDataUri_WhenSecretIsTooShort_ShouldStillGenerateQrCode()
|
||||
{
|
||||
// Arrange
|
||||
(string username, _) = QRCodeGeneratorFixture.CreateQrCodeTestData();
|
||||
byte[] shortSecret = [1]; // minimum length for Base32 encoding
|
||||
|
||||
// Act
|
||||
string result = _sut.GenerateQrCodeDataUri(username, shortSecret);
|
||||
|
||||
// Assert
|
||||
result.Should().StartWith("data:image/png;base64,");
|
||||
result.Should().Match(uri => IsBase64String(uri.Substring(22)));
|
||||
}
|
||||
|
||||
private static bool IsBase64String(string base64)
|
||||
{
|
||||
try
|
||||
{
|
||||
Convert.FromBase64String(base64);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Infrastructure.Core.Authentication;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="TokenGenerator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TokenGeneratorTests
|
||||
{
|
||||
private readonly TokenGenerator _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TokenGeneratorTests"/> class.
|
||||
/// </summary>
|
||||
public TokenGeneratorTests()
|
||||
{
|
||||
_sut = new TokenGenerator();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateToken_WhenCalled_ShouldGenerateNonEmptyToken()
|
||||
{
|
||||
// Act
|
||||
string token = _sut.GenerateToken();
|
||||
|
||||
// Assert
|
||||
token.Should().NotBeNullOrEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateToken_WhenCalled_ShouldGenerateUrlSafeToken()
|
||||
{
|
||||
// Act
|
||||
string token = _sut.GenerateToken();
|
||||
|
||||
// Assert
|
||||
token.Should().NotContain("+", "Token should not contain '+'");
|
||||
token.Should().NotContain("/", "Token should not contain '/'");
|
||||
token.Should().NotContain("=", "Token should not contain '='");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateToken_WhenCalledMultipleTimes_ShouldGenerateUniqueTokens()
|
||||
{
|
||||
// Act
|
||||
string token1 = _sut.GenerateToken();
|
||||
string token2 = _sut.GenerateToken();
|
||||
string token3 = _sut.GenerateToken();
|
||||
|
||||
// Assert
|
||||
token1.Should().NotBe(token2);
|
||||
token1.Should().NotBe(token3);
|
||||
token2.Should().NotBe(token3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateToken_WhenCalled_ShouldGenerateTokenOfCorrectLength()
|
||||
{
|
||||
// Act
|
||||
string token = _sut.GenerateToken();
|
||||
|
||||
// Assert
|
||||
// 32 bytes in Base64 without padding should be 43 characters
|
||||
token.Length.Should().Be(43);
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Infrastructure.Core.Authentication;
|
||||
using OtpNet;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="TotpTokenGenerator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TotpTokenGeneratorTests
|
||||
{
|
||||
private readonly TotpTokenGenerator _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TotpTokenGeneratorTests"/> class.
|
||||
/// </summary>
|
||||
public TotpTokenGeneratorTests()
|
||||
{
|
||||
_sut = new TotpTokenGenerator();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateSecret_WhenCalled_ShouldGenerateNonEmptySecret()
|
||||
{
|
||||
// Act
|
||||
byte[] secret = _sut.GenerateSecret();
|
||||
|
||||
// Assert
|
||||
secret.Should().NotBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateSecret_WhenCalledMultipleTimes_ShouldGenerateUniqueSecrets()
|
||||
{
|
||||
// Act
|
||||
byte[] secret1 = _sut.GenerateSecret();
|
||||
byte[] secret2 = _sut.GenerateSecret();
|
||||
byte[] secret3 = _sut.GenerateSecret();
|
||||
|
||||
// Assert
|
||||
secret1.Should().NotBeEquivalentTo(secret2);
|
||||
secret1.Should().NotBeEquivalentTo(secret3);
|
||||
secret2.Should().NotBeEquivalentTo(secret3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidateToken_WhenTokenIsValid_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
byte[] secret = _sut.GenerateSecret();
|
||||
Totp totp = new(secret);
|
||||
string validToken = totp.ComputeTotp();
|
||||
|
||||
// Act
|
||||
bool result = _sut.ValidateToken(secret, validToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
[InlineData("123456")] // Valid format but wrong token
|
||||
[InlineData("abcdef")] // Invalid format
|
||||
[InlineData("12345")] // Too short
|
||||
[InlineData("1234567")] // Too long
|
||||
public void ValidateToken_WhenTokenIsInvalid_ShouldReturnFalse(string invalidToken)
|
||||
{
|
||||
// Arrange
|
||||
byte[] secret = _sut.GenerateSecret();
|
||||
|
||||
// Act
|
||||
bool result = _sut.ValidateToken(secret, invalidToken);
|
||||
|
||||
// Assert
|
||||
result.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ValidateToken_WhenSecretIsWrong_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
byte[] secret1 = _sut.GenerateSecret();
|
||||
byte[] secret2 = _sut.GenerateSecret();
|
||||
Totp totp = new(secret1);
|
||||
string token = totp.ComputeTotp();
|
||||
|
||||
// Act
|
||||
bool result = _sut.ValidateToken(secret2, token);
|
||||
|
||||
// Assert
|
||||
result.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateSecret_WhenCalled_ShouldGenerateSecretOfCorrectLength()
|
||||
{
|
||||
// Act
|
||||
byte[] secret = _sut.GenerateSecret();
|
||||
|
||||
// Assert
|
||||
secret.Length.Should().Be(20); // Standard TOTP secret length
|
||||
}
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Infrastructure.Common.Models.Configuration;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Infrastructure.UnitTests.Core.Security.Fixtures;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Security.Cryptography;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CryptographyService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CryptographyServiceTests
|
||||
{
|
||||
private readonly CryptographyService _sut;
|
||||
private readonly IOptions<EncryptionSettingsModel> _encryptionSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CryptographyServiceTests"/> class.
|
||||
/// </summary>
|
||||
public CryptographyServiceTests()
|
||||
{
|
||||
_encryptionSettings = CryptographyServiceFixture.CreateEncryptionSettings();
|
||||
_sut = new CryptographyService(_encryptionSettings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Encrypt_WhenCalledWithValidData_ShouldReturnNonEmptyString()
|
||||
{
|
||||
// Arrange
|
||||
string plaintext = CryptographyServiceFixture.CreateTestData();
|
||||
|
||||
// Act
|
||||
string result = _sut.Encrypt(plaintext);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNullOrEmpty();
|
||||
result.Should().NotBe(plaintext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Encrypt_WhenCalledMultipleTimesWithSameInput_ShouldReturnDifferentResults()
|
||||
{
|
||||
// Arrange
|
||||
string plaintext = CryptographyServiceFixture.CreateTestData();
|
||||
|
||||
// Act
|
||||
string result1 = _sut.Encrypt(plaintext);
|
||||
string result2 = _sut.Encrypt(plaintext);
|
||||
|
||||
// Assert
|
||||
result1.Should().NotBe(result2);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
public void Encrypt_WhenInputIsNullOrEmpty_ShouldThrowArgumentException(string? invalidInput)
|
||||
{
|
||||
// Act
|
||||
Action act = () => _sut.Encrypt(invalidInput!);
|
||||
|
||||
// Assert
|
||||
act.Should().Throw<ArgumentException>()
|
||||
.WithParameterName("plaintext")
|
||||
.WithMessage("Value cannot be null or empty*");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Decrypt_WhenCalledWithValidData_ShouldReturnOriginalText()
|
||||
{
|
||||
// Arrange
|
||||
string originalText = CryptographyServiceFixture.CreateTestData();
|
||||
string encrypted = _sut.Encrypt(originalText);
|
||||
|
||||
// Act
|
||||
string decrypted = _sut.Decrypt(encrypted);
|
||||
|
||||
// Assert
|
||||
decrypted.Should().Be(originalText);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
public void Decrypt_WhenInputIsNullOrEmpty_ShouldThrowArgumentException(string? invalidInput)
|
||||
{
|
||||
// Act
|
||||
Action act = () => _sut.Decrypt(invalidInput!);
|
||||
|
||||
// Assert
|
||||
act.Should().Throw<ArgumentException>()
|
||||
.WithParameterName("ciphertext")
|
||||
.WithMessage("Value cannot be null or empty*");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("invalid")]
|
||||
[InlineData("not-base64-!@#")]
|
||||
public void Decrypt_WhenInputIsNotBase64_ShouldThrowFormatException(string invalidInput)
|
||||
{
|
||||
// Act
|
||||
Action act = () => _sut.Decrypt(invalidInput);
|
||||
|
||||
// Assert
|
||||
act.Should().Throw<FormatException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Decrypt_WhenInputIsTooShort_ShouldThrowArgumentException()
|
||||
{
|
||||
// Arrange
|
||||
string shortCiphertext = Convert.ToBase64String(new byte[8]); // less than required 16 bytes
|
||||
|
||||
// Act
|
||||
Action act = () => _sut.Decrypt(shortCiphertext);
|
||||
|
||||
// Assert
|
||||
act.Should().Throw<ArgumentException>()
|
||||
.WithMessage("Invalid ciphertext");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Decrypt_WhenInputIsCorrupted_ShouldThrowCryptographicException()
|
||||
{
|
||||
// Arrange
|
||||
string originalText = CryptographyServiceFixture.CreateTestData();
|
||||
string encrypted = _sut.Encrypt(originalText);
|
||||
|
||||
// decode the Base64 string, modify one byte, then re-encode
|
||||
byte[] encryptedBytes = Convert.FromBase64String(encrypted);
|
||||
encryptedBytes[^1] ^= 0xFF; // flip all bits in the last byte
|
||||
string corrupted = Convert.ToBase64String(encryptedBytes);
|
||||
|
||||
// Act
|
||||
Action act = () => _sut.Decrypt(corrupted);
|
||||
|
||||
// Assert
|
||||
act.Should().Throw<CryptographicException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dispose_WhenCalled_ShouldClearKey()
|
||||
{
|
||||
// Arrange
|
||||
string plaintext = CryptographyServiceFixture.CreateTestData();
|
||||
string encrypted = _sut.Encrypt(plaintext);
|
||||
|
||||
// Act
|
||||
_sut.Dispose();
|
||||
|
||||
// Assert
|
||||
Action act = () => _sut.Decrypt(encrypted);
|
||||
act.Should().Throw<CryptographicException>();
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Infrastructure.Common.Models.Configuration;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Security.Cryptography;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Security.Fixtures;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for cryptography service tests.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CryptographyServiceFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a valid encryption settings model for testing.
|
||||
/// </summary>
|
||||
/// <returns>The configured options.</returns>
|
||||
public static IOptions<EncryptionSettingsModel> CreateEncryptionSettings()
|
||||
{
|
||||
// Generate a valid 256-bit (32 byte) key for AES-256
|
||||
byte[] key = new byte[32];
|
||||
RandomNumberGenerator.Fill(key);
|
||||
string base64Key = Convert.ToBase64String(key);
|
||||
|
||||
EncryptionSettingsModel settings = new()
|
||||
{
|
||||
SecretKey = base64Key
|
||||
};
|
||||
|
||||
IOptions<EncryptionSettingsModel> options = Substitute.For<IOptions<EncryptionSettingsModel>>();
|
||||
options.Value.Returns(settings);
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates test data for encryption/decryption.
|
||||
/// </summary>
|
||||
/// <returns>A string to be encrypted/decrypted.</returns>
|
||||
public static string CreateTestData()
|
||||
{
|
||||
return new Faker().Lorem.Sentence();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentAssertions;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="HashService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class HashServiceTests
|
||||
{
|
||||
private readonly HashService _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HashServiceTests"/> class.
|
||||
/// </summary>
|
||||
public HashServiceTests()
|
||||
{
|
||||
_sut = new HashService();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HashString_WhenCalled_ShouldReturnNonEmptyHash()
|
||||
{
|
||||
// Arrange
|
||||
string password = "TestPassword123!";
|
||||
|
||||
// Act
|
||||
string result = _sut.HashString(password);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNullOrEmpty();
|
||||
result.Should().NotBe(password);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HashString_WhenCalledMultipleTimesWithSameInput_ShouldReturnDifferentHashes()
|
||||
{
|
||||
// Arrange
|
||||
string password = "TestPassword123!";
|
||||
|
||||
// Act
|
||||
string hash1 = _sut.HashString(password);
|
||||
string hash2 = _sut.HashString(password);
|
||||
|
||||
// Assert
|
||||
hash1.Should().NotBe(hash2);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(" ")]
|
||||
[InlineData("short")]
|
||||
[InlineData("verylongpasswordwithlotsofcharactersbutnostringformatting")]
|
||||
[InlineData("Password123!")]
|
||||
[InlineData("@#$%^&*()")]
|
||||
public void HashString_WhenCalledWithDifferentInputs_ShouldGenerateValidHashes(string input)
|
||||
{
|
||||
// Act
|
||||
string hash = _sut.HashString(input);
|
||||
|
||||
// Assert
|
||||
hash.Should().NotBeNullOrEmpty();
|
||||
// verify it's a valid Base64 string
|
||||
Action decode = () => Convert.FromBase64String(hash);
|
||||
decode.Should().NotThrow();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CheckStringAgainstHash_WhenPasswordMatches_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
string password = "TestPassword123!";
|
||||
string hash = _sut.HashString(password);
|
||||
|
||||
// Act
|
||||
bool result = _sut.CheckStringAgainstHash(password, hash);
|
||||
|
||||
// Assert
|
||||
result.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CheckStringAgainstHash_WhenPasswordDoesNotMatch_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
string password = "TestPassword123!";
|
||||
string wrongPassword = "WrongPassword123!";
|
||||
string hash = _sut.HashString(password);
|
||||
|
||||
// Act
|
||||
bool result = _sut.CheckStringAgainstHash(wrongPassword, hash);
|
||||
|
||||
// Assert
|
||||
result.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("dGVzdA==")] // valid base64 but wrong length
|
||||
[InlineData("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=")] // valid base64 but wrong length
|
||||
public void CheckStringAgainstHash_WhenHashIsInvalidLength_ShouldReturnFalse(string invalidHash)
|
||||
{
|
||||
// Arrange
|
||||
string password = "TestPassword123!";
|
||||
|
||||
// Act
|
||||
bool result = _sut.CheckStringAgainstHash(password, invalidHash);
|
||||
|
||||
// Assert
|
||||
result.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CheckStringAgainstHash_WhenHashIsNotBase64_ShouldThrowFormatException()
|
||||
{
|
||||
// Arrange
|
||||
string password = "TestPassword123!";
|
||||
string invalidHash = "not-base64-string";
|
||||
|
||||
// Act
|
||||
Action act = () => _sut.CheckStringAgainstHash(password, invalidHash);
|
||||
|
||||
// Assert
|
||||
act.Should().Throw<FormatException>();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
public void HashString_WhenPasswordIsNull_ShouldThrowArgumentNullException(string? nullPassword)
|
||||
{
|
||||
// Act
|
||||
Action act = () => _sut.HashString(nullPassword!);
|
||||
|
||||
// Assert
|
||||
act.Should().Throw<ArgumentNullException>();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
public void CheckStringAgainstHash_WhenPasswordIsNull_ShouldThrowArgumentNullException(string? nullPassword)
|
||||
{
|
||||
// Arrange
|
||||
string hash = _sut.HashString("somepassword");
|
||||
|
||||
// Act
|
||||
Action act = () => _sut.CheckStringAgainstHash(nullPassword!, hash);
|
||||
|
||||
// Assert
|
||||
act.Should().Throw<ArgumentNullException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CheckStringAgainstHash_WhenHashIsNull_ShouldThrowArgumentNullException()
|
||||
{
|
||||
// Act
|
||||
Action act = () => _sut.CheckStringAgainstHash("password", null!);
|
||||
|
||||
// Assert
|
||||
act.Should().Throw<ArgumentNullException>();
|
||||
}
|
||||
}
|
||||
+12
-4
@@ -9,19 +9,27 @@
|
||||
<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="5.0.0-preview0011" />
|
||||
<PackageReference Include="AutoFixture.Xunit2" Version="5.0.0-preview0011" />
|
||||
<PackageReference Include="Bogus" Version="35.6.1" />
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.2">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="FluentAssertions" Version="7.0.0-alpha.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.0-rc.2.24473.5" />
|
||||
<PackageReference Include="FluentAssertions" Version="7.0.0-alpha.5" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
|
||||
<PackageReference Include="NSubstitute" Version="5.1.0" />
|
||||
<PackageReference Include="NSubstitute" Version="5.3.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.2" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.0.0-pre.35">
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.0.0-pre.49">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
|
||||
Reference in new issue
Block a user