mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 18:21:10 +00:00
Adds authentication unit tests
This commit is contained in:
1 parent
a6dcf65d1c
commit
4f91f29b62
101 files changed
+5549
-135
No files matched your search
+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
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user