diff --git a/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs index 19826e36f..f8ea4aa56 100644 --- a/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs +++ b/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs @@ -2,10 +2,13 @@ using Grand.Business.Core.Interfaces.Authentication; using Grand.Business.Core.Interfaces.Customers; using Grand.Business.Core.Utilities.Authentication; +using Grand.Data; using Grand.Domain.Common; using Grand.Domain.Customers; using Grand.Domain.Localization; using Grand.Domain.Stores; +using System.Security.Cryptography; +using System.Text; namespace Grand.Business.Authentication.Services; @@ -14,13 +17,16 @@ public class TwoFactorAuthenticationService : ITwoFactorAuthenticationService private readonly IEnumerable _smsVerificationService; private readonly TwoFactorAuthenticator _twoFactorAuthentication; private readonly ICustomerService _customerService; + private readonly IResourceLock _resourceLock; public TwoFactorAuthenticationService( ICustomerService customerService, - IEnumerable smsVerificationService) + IEnumerable smsVerificationService, + IResourceLock resourceLock) { _customerService = customerService; _smsVerificationService = smsVerificationService; + _resourceLock = resourceLock; _twoFactorAuthentication = new TwoFactorAuthenticator(); } @@ -33,13 +39,7 @@ public virtual async Task AuthenticateTwoFactor(string secretKey, string t return _twoFactorAuthentication.ValidateTwoFactorPIN(secretKey, token.Trim()); case TwoFactorAuthenticationType.EmailVerification: - var customerToken = - customer.GetUserFieldFromEntity(SystemCustomerFieldNames.TwoFactorValidCode); - if (customerToken != token?.Trim()) - return false; - var validUntil = - customer.GetUserFieldFromEntity(SystemCustomerFieldNames.TwoFactorCodeValidUntil); - return validUntil >= DateTime.UtcNow; + return await UseEmailCode(customer, token?.Trim()); case TwoFactorAuthenticationType.SMSVerification: if (!_smsVerificationService.Any()) @@ -86,9 +86,34 @@ await _customerService.UpdateUserField(customer, SystemCustomerFieldNames.TwoFac return model; } + //a code signs in once: it is read again and cleared under a lock, so two requests with it cannot both pass + private async Task UseEmailCode(Customer customer, string token) + { + await using var _ = await _resourceLock.Acquire([$"TwoFactorCode:{customer.Id}"]); + + var current = await _customerService.GetCustomerById(customer.Id); + if (current == null) + return false; + + var customerToken = current.GetUserFieldFromEntity(SystemCustomerFieldNames.TwoFactorValidCode); + if (string.IsNullOrEmpty(customerToken) || !CodesMatch(customerToken, token)) + return false; + var validUntil = current.GetUserFieldFromEntity(SystemCustomerFieldNames.TwoFactorCodeValidUntil); + if (validUntil < DateTime.UtcNow) + return false; + + await _customerService.UpdateUserField(current, SystemCustomerFieldNames.TwoFactorValidCode, string.Empty); + return true; + } + private static string PrepareRandomCode() { - var generator = new Random(); - return generator.Next(0, 999999).ToString("D6"); + return RandomNumberGenerator.GetInt32(1_000_000).ToString("D6"); + } + + private static bool CodesMatch(string expected, string given) + { + return given != null && + CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(given)); } } \ No newline at end of file diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs index 4e2b978b6..9c87594c3 100644 --- a/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs +++ b/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs @@ -1,9 +1,12 @@ using Grand.Business.Authentication.Services; using Grand.Business.Core.Interfaces.Authentication; using Grand.Business.Core.Interfaces.Customers; +using Grand.Data; +using Grand.Domain.Common; using Grand.Domain.Customers; using Grand.Domain.Localization; using Grand.Domain.Stores; +using Grand.SharedKernel.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; @@ -15,14 +18,18 @@ public class TwoFactorAuthenticationServiceTests private Mock> _sMsVerificationService; private TwoFactorAuthenticationService _twoFactorAuthenticationService; private Mock _customerServiceMock; + private Mock _resourceLockMock; [TestInitialize] public void Init() { _customerServiceMock = new Mock(); _sMsVerificationService = new Mock>(); + _resourceLockMock = new Mock(); + _resourceLockMock.Setup(x => x.Acquire(It.IsAny>(), It.IsAny())) + .ReturnsAsync(Mock.Of()); _twoFactorAuthenticationService = new TwoFactorAuthenticationService( - _customerServiceMock.Object, _sMsVerificationService.Object); + _customerServiceMock.Object, _sMsVerificationService.Object, _resourceLockMock.Object); } [TestMethod] @@ -47,4 +54,92 @@ public async Task GenerateCodeSetupTest_Email() //Assert Assert.IsTrue(result.CustomValues.ContainsKey("Token")); } -} \ No newline at end of file + + //the service reads the code again from the database, so the stored customer is what the mock returns + private Customer CustomerWithCode(string code, DateTime validUntil) + { + var stored = NewCustomerWithCode(code, validUntil); + _customerServiceMock.Setup(x => x.GetCustomerById(stored.Id)).ReturnsAsync(stored); + return stored; + } + + private static Customer NewCustomerWithCode(string code, DateTime validUntil) + { + var customer = new Customer { Id = "c1" }; + customer.UserFields.Add(new UserField { Key = SystemCustomerFieldNames.TwoFactorValidCode, Value = code, StoreId = "" }); + customer.UserFields.Add(new UserField { + Key = SystemCustomerFieldNames.TwoFactorCodeValidUntil, //stored the way UpdateUserField stores it + Value = CommonHelper.To(validUntil), StoreId = "" + }); + return customer; + } + + [TestMethod] + public async Task EmailCode_Correct_SignsIn_AndIsUsedUp() + { + var customer = CustomerWithCode("123456", DateTime.UtcNow.AddMinutes(10)); + + Assert.IsTrue(await _twoFactorAuthenticationService.AuthenticateTwoFactor(null, " 123456 ", customer, + TwoFactorAuthenticationType.EmailVerification)); + _customerServiceMock.Verify(x => x.UpdateUserField(customer, SystemCustomerFieldNames.TwoFactorValidCode, + string.Empty, It.IsAny()), Times.Once); + } + + [TestMethod] + [DataRow("654321")] + [DataRow("")] + [DataRow(null)] + public async Task EmailCode_Wrong_Refused(string given) + { + var customer = CustomerWithCode("123456", DateTime.UtcNow.AddMinutes(10)); + + Assert.IsFalse(await _twoFactorAuthenticationService.AuthenticateTwoFactor(null, given, customer, + TwoFactorAuthenticationType.EmailVerification)); + _customerServiceMock.Verify(x => x.UpdateUserField(It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task EmailCode_UsedUp_Refused() + { + var customer = CustomerWithCode("", DateTime.UtcNow.AddMinutes(10)); + + Assert.IsFalse(await _twoFactorAuthenticationService.AuthenticateTwoFactor(null, "", customer, + TwoFactorAuthenticationType.EmailVerification)); + } + + [TestMethod] + public async Task EmailCode_Expired_Refused() + { + var customer = CustomerWithCode("123456", DateTime.UtcNow.AddMinutes(-1)); + + Assert.IsFalse(await _twoFactorAuthenticationService.AuthenticateTwoFactor(null, "123456", customer, + TwoFactorAuthenticationType.EmailVerification)); + } + + [TestMethod] + public async Task EmailCode_UsedUpByAnotherRequest_Refused() + { + //the request still holds the customer it loaded before another request used the code + var loaded = NewCustomerWithCode("123456", DateTime.UtcNow.AddMinutes(10)); + _customerServiceMock.Setup(x => x.GetCustomerById(loaded.Id)) + .ReturnsAsync(NewCustomerWithCode("", DateTime.UtcNow.AddMinutes(10))); + + Assert.IsFalse(await _twoFactorAuthenticationService.AuthenticateTwoFactor(null, "123456", loaded, + TwoFactorAuthenticationType.EmailVerification)); + _customerServiceMock.Verify(x => x.UpdateUserField(It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task EmailCode_CheckedAndUsedUpUnderTheCustomersLock() + { + var customer = CustomerWithCode("123456", DateTime.UtcNow.AddMinutes(10)); + + await _twoFactorAuthenticationService.AuthenticateTwoFactor(null, "123456", customer, + TwoFactorAuthenticationType.EmailVerification); + + _resourceLockMock.Verify(x => x.Acquire(It.Is>(k => k.Single() == "TwoFactorCode:c1"), + It.IsAny()), Times.Once); + } +}