1
0
mirror of https://github.com/bitwarden/server.git synced 2024-12-01 13:43:23 +01:00
bitwarden-server/test/Api.Test/Controllers/AccountsControllerTests.cs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

435 lines
15 KiB
C#
Raw Normal View History

using System.Security.Claims;
[PM-1188] Server owner auth migration (#2825) * [PM-1188] add sso project to auth * [PM-1188] move sso api models to auth * [PM-1188] fix sso api model namespace & imports * [PM-1188] move core files to auth * [PM-1188] fix core sso namespace & models * [PM-1188] move sso repository files to auth * [PM-1188] fix sso repo files namespace & imports * [PM-1188] move sso sql files to auth folder * [PM-1188] move sso test files to auth folders * [PM-1188] fix sso tests namespace & imports * [PM-1188] move auth api files to auth folder * [PM-1188] fix auth api files namespace & imports * [PM-1188] move auth core files to auth folder * [PM-1188] fix auth core files namespace & imports * [PM-1188] move auth email templates to auth folder * [PM-1188] move auth email folder back into shared directory * [PM-1188] fix auth email names * [PM-1188] move auth core models to auth folder * [PM-1188] fix auth model namespace & imports * [PM-1188] add entire Identity project to auth codeowners * [PM-1188] fix auth orm files namespace & imports * [PM-1188] move auth orm files to auth folder * [PM-1188] move auth sql files to auth folder * [PM-1188] move auth tests to auth folder * [PM-1188] fix auth test files namespace & imports * [PM-1188] move emergency access api files to auth folder * [PM-1188] fix emergencyaccess api files namespace & imports * [PM-1188] move emergency access core files to auth folder * [PM-1188] fix emergency access core files namespace & imports * [PM-1188] move emergency access orm files to auth folder * [PM-1188] fix emergency access orm files namespace & imports * [PM-1188] move emergency access sql files to auth folder * [PM-1188] move emergencyaccess test files to auth folder * [PM-1188] fix emergency access test files namespace & imports * [PM-1188] move captcha files to auth folder * [PM-1188] fix captcha files namespace & imports * [PM-1188] move auth admin files into auth folder * [PM-1188] fix admin auth files namespace & imports - configure mvc to look in auth folders for views * [PM-1188] remove extra imports and formatting * [PM-1188] fix ef auth model imports * [PM-1188] fix DatabaseContextModelSnapshot paths * [PM-1188] fix grant import in ef * [PM-1188] update sqlproj * [PM-1188] move missed sqlproj files * [PM-1188] move auth ef models out of auth folder * [PM-1188] fix auth ef models namespace * [PM-1188] remove auth ef models unused imports * [PM-1188] fix imports for auth ef models * [PM-1188] fix more ef model imports * [PM-1188] fix file encodings
2023-04-14 19:25:56 +02:00
using Bit.Api.Auth.Models.Request.Accounts;
using Bit.Api.Controllers;
[PM-1188] Server owner auth migration (#2825) * [PM-1188] add sso project to auth * [PM-1188] move sso api models to auth * [PM-1188] fix sso api model namespace & imports * [PM-1188] move core files to auth * [PM-1188] fix core sso namespace & models * [PM-1188] move sso repository files to auth * [PM-1188] fix sso repo files namespace & imports * [PM-1188] move sso sql files to auth folder * [PM-1188] move sso test files to auth folders * [PM-1188] fix sso tests namespace & imports * [PM-1188] move auth api files to auth folder * [PM-1188] fix auth api files namespace & imports * [PM-1188] move auth core files to auth folder * [PM-1188] fix auth core files namespace & imports * [PM-1188] move auth email templates to auth folder * [PM-1188] move auth email folder back into shared directory * [PM-1188] fix auth email names * [PM-1188] move auth core models to auth folder * [PM-1188] fix auth model namespace & imports * [PM-1188] add entire Identity project to auth codeowners * [PM-1188] fix auth orm files namespace & imports * [PM-1188] move auth orm files to auth folder * [PM-1188] move auth sql files to auth folder * [PM-1188] move auth tests to auth folder * [PM-1188] fix auth test files namespace & imports * [PM-1188] move emergency access api files to auth folder * [PM-1188] fix emergencyaccess api files namespace & imports * [PM-1188] move emergency access core files to auth folder * [PM-1188] fix emergency access core files namespace & imports * [PM-1188] move emergency access orm files to auth folder * [PM-1188] fix emergency access orm files namespace & imports * [PM-1188] move emergency access sql files to auth folder * [PM-1188] move emergencyaccess test files to auth folder * [PM-1188] fix emergency access test files namespace & imports * [PM-1188] move captcha files to auth folder * [PM-1188] fix captcha files namespace & imports * [PM-1188] move auth admin files into auth folder * [PM-1188] fix admin auth files namespace & imports - configure mvc to look in auth folders for views * [PM-1188] remove extra imports and formatting * [PM-1188] fix ef auth model imports * [PM-1188] fix DatabaseContextModelSnapshot paths * [PM-1188] fix grant import in ef * [PM-1188] update sqlproj * [PM-1188] move missed sqlproj files * [PM-1188] move auth ef models out of auth folder * [PM-1188] fix auth ef models namespace * [PM-1188] remove auth ef models unused imports * [PM-1188] fix imports for auth ef models * [PM-1188] fix more ef model imports * [PM-1188] fix file encodings
2023-04-14 19:25:56 +02:00
using Bit.Core.Auth.Models.Api.Request.Accounts;
using Bit.Core.Auth.Services;
using Bit.Core.Entities;
using Bit.Core.Enums;
using Bit.Core.Exceptions;
using Bit.Core.Models.Data;
using Bit.Core.Repositories;
using Bit.Core.Services;
using Bit.Core.Settings;
using Bit.Core.Tools.Repositories;
using Bit.Core.Tools.Services;
using Bit.Core.Vault.Repositories;
using Microsoft.AspNetCore.Identity;
using NSubstitute;
using Xunit;
namespace Bit.Api.Test.Controllers;
2022-08-29 22:06:55 +02:00
public class AccountsControllerTests : IDisposable
{
private readonly AccountsController _sut;
private readonly GlobalSettings _globalSettings;
private readonly ICipherRepository _cipherRepository;
2021-06-30 09:35:26 +02:00
private readonly IFolderRepository _folderRepository;
private readonly IOrganizationService _organizationService;
private readonly IOrganizationUserRepository _organizationUserRepository;
private readonly IPaymentService _paymentService;
private readonly IUserRepository _userRepository;
private readonly IUserService _userService;
private readonly ISendRepository _sendRepository;
private readonly ISendService _sendService;
2021-06-30 09:35:26 +02:00
private readonly IProviderUserRepository _providerUserRepository;
private readonly ICaptchaValidationService _captchaValidationService;
[AC-1070] Enforce master password policy on login (#2714) * [EC-1070] Add API endpoint to retrieve all policies for the current user The additional API endpoint is required to avoid forcing a full sync call before every login for master password policy enforcement on login. * [EC-1070] Add MasterPasswordPolicyData model * [EC-1070] Move PolicyResponseModel to Core project The response model is used by both the Identity and Api projects. * [EC-1070] Supply master password polices as a custom identity token response * [EC-1070] Include master password policies in 2FA token response * [EC-1070] Add response model to verify-password endpoint that includes master password policies * [AC-1070] Introduce MasterPasswordPolicyResponseModel * [AC-1070] Add policy service method to retrieve a user's master password policy * [AC-1070] User new policy service method - Update BaseRequestValidator - Update AccountsController for /verify-password endpoint - Update VerifyMasterPasswordResponseModel to accept MasterPasswordPolicyData * [AC-1070] Cleanup new policy service method - Use User object instead of Guid - Remove TODO message - Use `PolicyRepository.GetManyByTypeApplicableToUserIdAsync` instead of filtering locally * [AC-1070] Cleanup MasterPasswordPolicy models - Remove default values from both models - Add missing `RequireLower` - Fix mismatched properties in `CombineWith` method - Make properties nullable in response model * [AC-1070] Remove now un-used GET /policies endpoint * [AC-1070] Update policy service method to use GetManyByUserIdAsync * [AC-1070] Ensure existing value is not null before comparison * [AC-1070] Remove redundant VerifyMasterPasswordResponse model * [AC-1070] Fix service typo in constructor
2023-04-17 16:35:47 +02:00
private readonly IPolicyService _policyService;
2022-08-29 22:06:55 +02:00
public AccountsControllerTests()
2022-08-29 22:06:55 +02:00
{
_userService = Substitute.For<IUserService>();
_userRepository = Substitute.For<IUserRepository>();
_cipherRepository = Substitute.For<ICipherRepository>();
_folderRepository = Substitute.For<IFolderRepository>();
_organizationService = Substitute.For<IOrganizationService>();
_organizationUserRepository = Substitute.For<IOrganizationUserRepository>();
_providerUserRepository = Substitute.For<IProviderUserRepository>();
_paymentService = Substitute.For<IPaymentService>();
_globalSettings = new GlobalSettings();
_sendRepository = Substitute.For<ISendRepository>();
_sendService = Substitute.For<ISendService>();
_captchaValidationService = Substitute.For<ICaptchaValidationService>();
[AC-1070] Enforce master password policy on login (#2714) * [EC-1070] Add API endpoint to retrieve all policies for the current user The additional API endpoint is required to avoid forcing a full sync call before every login for master password policy enforcement on login. * [EC-1070] Add MasterPasswordPolicyData model * [EC-1070] Move PolicyResponseModel to Core project The response model is used by both the Identity and Api projects. * [EC-1070] Supply master password polices as a custom identity token response * [EC-1070] Include master password policies in 2FA token response * [EC-1070] Add response model to verify-password endpoint that includes master password policies * [AC-1070] Introduce MasterPasswordPolicyResponseModel * [AC-1070] Add policy service method to retrieve a user's master password policy * [AC-1070] User new policy service method - Update BaseRequestValidator - Update AccountsController for /verify-password endpoint - Update VerifyMasterPasswordResponseModel to accept MasterPasswordPolicyData * [AC-1070] Cleanup new policy service method - Use User object instead of Guid - Remove TODO message - Use `PolicyRepository.GetManyByTypeApplicableToUserIdAsync` instead of filtering locally * [AC-1070] Cleanup MasterPasswordPolicy models - Remove default values from both models - Add missing `RequireLower` - Fix mismatched properties in `CombineWith` method - Make properties nullable in response model * [AC-1070] Remove now un-used GET /policies endpoint * [AC-1070] Update policy service method to use GetManyByUserIdAsync * [AC-1070] Ensure existing value is not null before comparison * [AC-1070] Remove redundant VerifyMasterPasswordResponse model * [AC-1070] Fix service typo in constructor
2023-04-17 16:35:47 +02:00
_policyService = Substitute.For<IPolicyService>();
_sut = new AccountsController(
_globalSettings,
_cipherRepository,
_folderRepository,
_organizationService,
_organizationUserRepository,
_providerUserRepository,
_paymentService,
_userRepository,
_userService,
_sendRepository,
_sendService,
[AC-1070] Enforce master password policy on login (#2714) * [EC-1070] Add API endpoint to retrieve all policies for the current user The additional API endpoint is required to avoid forcing a full sync call before every login for master password policy enforcement on login. * [EC-1070] Add MasterPasswordPolicyData model * [EC-1070] Move PolicyResponseModel to Core project The response model is used by both the Identity and Api projects. * [EC-1070] Supply master password polices as a custom identity token response * [EC-1070] Include master password policies in 2FA token response * [EC-1070] Add response model to verify-password endpoint that includes master password policies * [AC-1070] Introduce MasterPasswordPolicyResponseModel * [AC-1070] Add policy service method to retrieve a user's master password policy * [AC-1070] User new policy service method - Update BaseRequestValidator - Update AccountsController for /verify-password endpoint - Update VerifyMasterPasswordResponseModel to accept MasterPasswordPolicyData * [AC-1070] Cleanup new policy service method - Use User object instead of Guid - Remove TODO message - Use `PolicyRepository.GetManyByTypeApplicableToUserIdAsync` instead of filtering locally * [AC-1070] Cleanup MasterPasswordPolicy models - Remove default values from both models - Add missing `RequireLower` - Fix mismatched properties in `CombineWith` method - Make properties nullable in response model * [AC-1070] Remove now un-used GET /policies endpoint * [AC-1070] Update policy service method to use GetManyByUserIdAsync * [AC-1070] Ensure existing value is not null before comparison * [AC-1070] Remove redundant VerifyMasterPasswordResponse model * [AC-1070] Fix service typo in constructor
2023-04-17 16:35:47 +02:00
_captchaValidationService,
_policyService
2022-08-29 22:06:55 +02:00
);
}
public void Dispose()
2022-08-29 22:06:55 +02:00
{
_sut?.Dispose();
2022-08-29 22:06:55 +02:00
}
2022-08-29 20:53:16 +02:00
[Fact]
public async Task PostPrelogin_WhenUserExists_ShouldReturnUserKdfInfo()
2022-08-29 22:06:55 +02:00
{
var userKdfInfo = new UserKdfInformation
2022-08-29 20:53:16 +02:00
{
Kdf = KdfType.PBKDF2_SHA256,
KdfIterations = 5000
};
_userRepository.GetKdfInformationByEmailAsync(Arg.Any<string>()).Returns(Task.FromResult(userKdfInfo));
var response = await _sut.PostPrelogin(new PreloginRequestModel { Email = "user@example.com" });
Assert.Equal(userKdfInfo.Kdf, response.Kdf);
Assert.Equal(userKdfInfo.KdfIterations, response.KdfIterations);
}
2022-08-29 20:53:16 +02:00
[Fact]
public async Task PostPrelogin_WhenUserDoesNotExist_ShouldDefaultToSha256And100000Iterations()
2022-08-29 20:53:16 +02:00
{
_userRepository.GetKdfInformationByEmailAsync(Arg.Any<string>()).Returns(Task.FromResult((UserKdfInformation)null));
var response = await _sut.PostPrelogin(new PreloginRequestModel { Email = "user@example.com" });
Assert.Equal(KdfType.PBKDF2_SHA256, response.Kdf);
Assert.Equal(100000, response.KdfIterations);
}
[Fact]
public async Task PostRegister_ShouldRegisterUser()
{
var passwordHash = "abcdef";
var token = "123456";
var userGuid = new Guid();
_userService.RegisterUserAsync(Arg.Any<User>(), passwordHash, token, userGuid)
.Returns(Task.FromResult(IdentityResult.Success));
var request = new RegisterRequestModel
2022-08-29 22:06:55 +02:00
{
Name = "Example User",
Email = "user@example.com",
MasterPasswordHash = passwordHash,
MasterPasswordHint = "example",
Token = token,
OrganizationUserId = userGuid
};
2022-08-29 22:06:55 +02:00
await _sut.PostRegister(request);
2022-08-29 22:06:55 +02:00
await _userService.Received(1).RegisterUserAsync(Arg.Any<User>(), passwordHash, token, userGuid);
2022-08-29 22:06:55 +02:00
}
2022-08-29 22:06:55 +02:00
[Fact]
public async Task PostRegister_WhenUserServiceFails_ShouldThrowBadRequestException()
{
var passwordHash = "abcdef";
var token = "123456";
var userGuid = new Guid();
_userService.RegisterUserAsync(Arg.Any<User>(), passwordHash, token, userGuid)
.Returns(Task.FromResult(IdentityResult.Failed()));
var request = new RegisterRequestModel
2022-08-29 22:06:55 +02:00
{
Name = "Example User",
Email = "user@example.com",
MasterPasswordHash = passwordHash,
MasterPasswordHint = "example",
Token = token,
OrganizationUserId = userGuid
};
2022-08-29 22:06:55 +02:00
await Assert.ThrowsAsync<BadRequestException>(() => _sut.PostRegister(request));
2022-08-29 22:06:55 +02:00
}
2022-08-29 22:06:55 +02:00
[Fact]
public async Task PostPasswordHint_ShouldNotifyUserService()
2022-08-29 22:06:55 +02:00
{
var email = "user@example.com";
await _sut.PostPasswordHint(new PasswordHintRequestModel { Email = email });
await _userService.Received(1).SendMasterPasswordHintAsync(email);
}
2022-08-29 22:06:55 +02:00
[Fact]
public async Task PostEmailToken_ShouldInitiateEmailChange()
2022-08-29 22:06:55 +02:00
{
var user = GenerateExampleUser();
ConfigureUserServiceToReturnValidPrincipalFor(user);
ConfigureUserServiceToAcceptPasswordFor(user);
var newEmail = "example@user.com";
await _sut.PostEmailToken(new EmailTokenRequestModel { NewEmail = newEmail });
await _userService.Received(1).InitiateEmailChangeAsync(user, newEmail);
}
[Fact]
public async Task PostEmailToken_WhenNotAuthorized_ShouldThrowUnauthorizedAccessException()
{
ConfigureUserServiceToReturnNullPrincipal();
await Assert.ThrowsAsync<UnauthorizedAccessException>(
() => _sut.PostEmailToken(new EmailTokenRequestModel())
2022-08-29 20:53:16 +02:00
);
}
[Fact]
public async Task PostEmailToken_WhenInvalidPasssword_ShouldThrowBadRequestException()
{
var user = GenerateExampleUser();
ConfigureUserServiceToReturnValidPrincipalFor(user);
ConfigureUserServiceToRejectPasswordFor(user);
await Assert.ThrowsAsync<BadRequestException>(
() => _sut.PostEmailToken(new EmailTokenRequestModel())
);
2022-08-29 22:06:55 +02:00
}
2022-08-29 22:06:55 +02:00
[Fact]
public async Task PostEmail_ShouldChangeUserEmail()
2022-08-29 22:06:55 +02:00
{
var user = GenerateExampleUser();
ConfigureUserServiceToReturnValidPrincipalFor(user);
_userService.ChangeEmailAsync(user, default, default, default, default, default)
.Returns(Task.FromResult(IdentityResult.Success));
await _sut.PostEmail(new EmailRequestModel());
await _userService.Received(1).ChangeEmailAsync(user, default, default, default, default, default);
}
[Fact]
public async Task PostEmail_WhenNotAuthorized_ShouldThrownUnauthorizedAccessException()
{
ConfigureUserServiceToReturnNullPrincipal();
await Assert.ThrowsAsync<UnauthorizedAccessException>(
() => _sut.PostEmail(new EmailRequestModel())
);
2022-08-29 22:06:55 +02:00
}
2022-08-29 22:06:55 +02:00
[Fact]
public async Task PostEmail_WhenEmailCannotBeChanged_ShouldThrowBadRequestException()
2022-08-29 22:06:55 +02:00
{
var user = GenerateExampleUser();
ConfigureUserServiceToReturnValidPrincipalFor(user);
_userService.ChangeEmailAsync(user, default, default, default, default, default)
.Returns(Task.FromResult(IdentityResult.Failed()));
2022-08-29 22:06:55 +02:00
await Assert.ThrowsAsync<BadRequestException>(
() => _sut.PostEmail(new EmailRequestModel())
2022-08-29 22:06:55 +02:00
);
}
2022-08-29 20:53:16 +02:00
[Fact]
public async Task PostVerifyEmail_ShouldSendEmailVerification()
2022-08-29 20:53:16 +02:00
{
var user = GenerateExampleUser();
ConfigureUserServiceToReturnValidPrincipalFor(user);
await _sut.PostVerifyEmail();
await _userService.Received(1).SendEmailVerificationAsync(user);
2022-08-29 22:06:55 +02:00
}
2022-08-29 22:06:55 +02:00
[Fact]
public async Task PostVerifyEmail_WhenNotAuthorized_ShouldThrownUnauthorizedAccessException()
{
ConfigureUserServiceToReturnNullPrincipal();
await Assert.ThrowsAsync<UnauthorizedAccessException>(
() => _sut.PostVerifyEmail()
);
}
[Fact]
public async Task PostVerifyEmailToken_ShouldConfirmEmail()
{
var user = GenerateExampleUser();
ConfigureUserServiceToReturnValidIdFor(user);
_userService.ConfirmEmailAsync(user, Arg.Any<string>())
.Returns(Task.FromResult(IdentityResult.Success));
await _sut.PostVerifyEmailToken(new VerifyEmailRequestModel { UserId = "12345678-1234-1234-1234-123456789012" });
await _userService.Received(1).ConfirmEmailAsync(user, Arg.Any<string>());
}
2022-08-29 22:06:55 +02:00
[Fact]
public async Task PostVerifyEmailToken_WhenUserDoesNotExist_ShouldThrowUnauthorizedAccessException()
2022-08-29 22:06:55 +02:00
{
var user = GenerateExampleUser();
ConfigureUserServiceToReturnNullUserId();
await Assert.ThrowsAsync<UnauthorizedAccessException>(
() => _sut.PostVerifyEmailToken(new VerifyEmailRequestModel { UserId = "12345678-1234-1234-1234-123456789012" })
);
}
2022-08-29 20:53:16 +02:00
[Fact]
public async Task PostVerifyEmailToken_WhenEmailConfirmationFails_ShouldThrowBadRequestException()
2022-08-29 20:53:16 +02:00
{
var user = GenerateExampleUser();
ConfigureUserServiceToReturnValidIdFor(user);
_userService.ConfirmEmailAsync(user, Arg.Any<string>())
.Returns(Task.FromResult(IdentityResult.Failed()));
2022-08-29 22:06:55 +02:00
await Assert.ThrowsAsync<BadRequestException>(
() => _sut.PostVerifyEmailToken(new VerifyEmailRequestModel { UserId = "12345678-1234-1234-1234-123456789012" })
2022-08-29 22:06:55 +02:00
);
}
[Fact]
public async Task PostPassword_ShouldChangePassword()
2022-08-29 22:06:55 +02:00
{
var user = GenerateExampleUser();
ConfigureUserServiceToReturnValidPrincipalFor(user);
_userService.ChangePasswordAsync(user, default, default, default, default)
.Returns(Task.FromResult(IdentityResult.Success));
await _sut.PostPassword(new PasswordRequestModel());
await _userService.Received(1).ChangePasswordAsync(user, default, default, default, default);
2022-08-29 20:53:16 +02:00
}
[Fact]
public async Task PostPassword_WhenNotAuthorized_ShouldThrowUnauthorizedAccessException()
{
ConfigureUserServiceToReturnNullPrincipal();
2022-08-29 20:53:16 +02:00
await Assert.ThrowsAsync<UnauthorizedAccessException>(
() => _sut.PostPassword(new PasswordRequestModel())
2022-08-29 20:53:16 +02:00
);
}
[Fact]
public async Task PostPassword_WhenPasswordChangeFails_ShouldBadRequestException()
{
var user = GenerateExampleUser();
ConfigureUserServiceToReturnValidPrincipalFor(user);
_userService.ChangePasswordAsync(user, default, default, default, default)
.Returns(Task.FromResult(IdentityResult.Failed()));
2022-08-29 22:06:55 +02:00
await Assert.ThrowsAsync<BadRequestException>(
() => _sut.PostPassword(new PasswordRequestModel())
2022-08-29 20:53:16 +02:00
);
}
2022-08-29 22:06:55 +02:00
[Fact]
public async Task GetApiKey_ShouldReturnApiKeyResponse()
2022-08-29 22:06:55 +02:00
{
var user = GenerateExampleUser();
ConfigureUserServiceToReturnValidPrincipalFor(user);
ConfigureUserServiceToAcceptPasswordFor(user);
await _sut.ApiKey(new SecretVerificationRequestModel());
2022-08-29 20:53:16 +02:00
}
2022-08-29 22:06:55 +02:00
[Fact]
public async Task GetApiKey_WhenUserDoesNotExist_ShouldThrowUnauthorizedAccessException()
2022-08-29 22:06:55 +02:00
{
ConfigureUserServiceToReturnNullPrincipal();
2022-08-29 20:53:16 +02:00
await Assert.ThrowsAsync<UnauthorizedAccessException>(
() => _sut.ApiKey(new SecretVerificationRequestModel())
);
2022-08-29 20:53:16 +02:00
}
[Fact]
public async Task GetApiKey_WhenPasswordCheckFails_ShouldThrowBadRequestException()
2022-08-29 22:06:55 +02:00
{
var user = GenerateExampleUser();
ConfigureUserServiceToReturnValidPrincipalFor(user);
ConfigureUserServiceToRejectPasswordFor(user);
await Assert.ThrowsAsync<BadRequestException>(
() => _sut.ApiKey(new SecretVerificationRequestModel())
);
2022-08-29 20:53:16 +02:00
}
2022-08-29 22:06:55 +02:00
[Fact]
public async Task PostRotateApiKey_ShouldRotateApiKey()
2022-08-29 22:06:55 +02:00
{
var user = GenerateExampleUser();
ConfigureUserServiceToReturnValidPrincipalFor(user);
ConfigureUserServiceToAcceptPasswordFor(user);
await _sut.RotateApiKey(new SecretVerificationRequestModel());
2022-08-29 22:06:55 +02:00
}
[Fact]
public async Task PostRotateApiKey_WhenUserDoesNotExist_ShouldThrowUnauthorizedAccessException()
2022-08-29 22:06:55 +02:00
{
ConfigureUserServiceToReturnNullPrincipal();
2022-08-29 22:06:55 +02:00
await Assert.ThrowsAsync<UnauthorizedAccessException>(
() => _sut.ApiKey(new SecretVerificationRequestModel())
2022-08-29 22:06:55 +02:00
);
}
[Fact]
public async Task PostRotateApiKey_WhenPasswordCheckFails_ShouldThrowBadRequestException()
2022-08-29 22:06:55 +02:00
{
var user = GenerateExampleUser();
ConfigureUserServiceToReturnValidPrincipalFor(user);
ConfigureUserServiceToRejectPasswordFor(user);
await Assert.ThrowsAsync<BadRequestException>(
() => _sut.ApiKey(new SecretVerificationRequestModel())
2022-08-29 22:06:55 +02:00
);
2022-08-29 20:53:16 +02:00
}
// Below are helper functions that currently belong to this
// test class, but ultimately may need to be split out into
// something greater in order to share common test steps with
// other test suites. They are included here for the time being
// until that day comes.
private User GenerateExampleUser()
2022-08-29 22:06:55 +02:00
{
return new User
2022-08-29 20:53:16 +02:00
{
Email = "user@example.com"
2022-08-29 22:06:55 +02:00
};
}
private void ConfigureUserServiceToReturnNullPrincipal()
2022-08-29 22:06:55 +02:00
{
_userService.GetUserByPrincipalAsync(Arg.Any<ClaimsPrincipal>())
.Returns(Task.FromResult((User)null));
2022-08-29 22:06:55 +02:00
}
private void ConfigureUserServiceToReturnValidPrincipalFor(User user)
2022-08-29 22:06:55 +02:00
{
_userService.GetUserByPrincipalAsync(Arg.Any<ClaimsPrincipal>())
.Returns(Task.FromResult(user));
2022-08-29 22:06:55 +02:00
}
private void ConfigureUserServiceToRejectPasswordFor(User user)
2022-08-29 22:06:55 +02:00
{
_userService.CheckPasswordAsync(user, Arg.Any<string>())
.Returns(Task.FromResult(false));
2022-08-29 22:06:55 +02:00
}
private void ConfigureUserServiceToAcceptPasswordFor(User user)
2022-08-29 22:06:55 +02:00
{
_userService.CheckPasswordAsync(user, Arg.Any<string>())
.Returns(Task.FromResult(true));
_userService.VerifySecretAsync(user, Arg.Any<string>())
.Returns(Task.FromResult(true));
2022-08-29 22:06:55 +02:00
}
private void ConfigureUserServiceToReturnValidIdFor(User user)
2022-08-29 22:06:55 +02:00
{
_userService.GetUserByIdAsync(Arg.Any<Guid>())
.Returns(Task.FromResult(user));
2022-08-29 22:06:55 +02:00
}
private void ConfigureUserServiceToReturnNullUserId()
2022-08-29 22:06:55 +02:00
{
_userService.GetUserByIdAsync(Arg.Any<Guid>())
.Returns(Task.FromResult((User)null));
}
}