1
0
mirror of https://github.com/bitwarden/server.git synced 2025-06-30 15:42:48 -05:00

Auth/PM-12613 - Registration with Email Verification - Provider Invite Flow (#4917)

* PM-12613 - Add RegisterUserViaProviderInviteToken flow (needs manual, unit, and integration tests)

* PM-12613 - RegisterUserCommandTests - test register via provider inv

* PM-12613 - AccountsControllerTests.cs - Add integration test for provider

* PM-12613 - Remove comment

* PM-12613 - Add temp logging to help debug integration test failure in pipeline

* PM-12613 - WebApplicationFactoryBase.cs - add ConfigureServices

* PM-12613 - AccountsControllerTests.cs - refactor test to sidestep encryption

* PM-12613 - Per PR feedback, refactor AccountsController.cs and move token type checking into request model.

* PM-12613 - Remove debug writelines

* PM-12613 - Add RegisterFinishRequestModelTests
This commit is contained in:
Jared Snider
2024-10-23 18:06:24 -04:00
committed by GitHub
parent a952d10637
commit e6245bbece
8 changed files with 535 additions and 43 deletions

View File

@ -6,6 +6,14 @@ using Bit.Core.Utilities;
namespace Bit.Core.Auth.Models.Api.Request.Accounts;
using System.ComponentModel.DataAnnotations;
public enum RegisterFinishTokenType : byte
{
EmailVerification = 1,
OrganizationInvite = 2,
OrgSponsoredFreeFamilyPlan = 3,
EmergencyAccessInvite = 4,
ProviderInvite = 5,
}
public class RegisterFinishRequestModel : IValidatableObject
{
@ -36,6 +44,10 @@ public class RegisterFinishRequestModel : IValidatableObject
public string? AcceptEmergencyAccessInviteToken { get; set; }
public Guid? AcceptEmergencyAccessId { get; set; }
public string? ProviderInviteToken { get; set; }
public Guid? ProviderUserId { get; set; }
public User ToUser()
{
var user = new User
@ -54,6 +66,32 @@ public class RegisterFinishRequestModel : IValidatableObject
return user;
}
public RegisterFinishTokenType GetTokenType()
{
if (!string.IsNullOrWhiteSpace(EmailVerificationToken))
{
return RegisterFinishTokenType.EmailVerification;
}
if (!string.IsNullOrEmpty(OrgInviteToken) && OrganizationUserId.HasValue)
{
return RegisterFinishTokenType.OrganizationInvite;
}
if (!string.IsNullOrWhiteSpace(OrgSponsoredFreeFamilyPlanToken))
{
return RegisterFinishTokenType.OrgSponsoredFreeFamilyPlan;
}
if (!string.IsNullOrWhiteSpace(AcceptEmergencyAccessInviteToken) && AcceptEmergencyAccessId.HasValue)
{
return RegisterFinishTokenType.EmergencyAccessInvite;
}
if (!string.IsNullOrWhiteSpace(ProviderInviteToken) && ProviderUserId.HasValue)
{
return RegisterFinishTokenType.ProviderInvite;
}
throw new InvalidOperationException("Invalid token type.");
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{

View File

@ -61,4 +61,16 @@ public interface IRegisterUserCommand
public Task<IdentityResult> RegisterUserViaAcceptEmergencyAccessInviteToken(User user, string masterPasswordHash,
string acceptEmergencyAccessInviteToken, Guid acceptEmergencyAccessId);
/// <summary>
/// Creates a new user with a given master password hash, sends a welcome email, and raises the signup reference event.
/// If a valid token is provided, the user will be created with their email verified.
/// If the token is invalid or expired, an error will be thrown.
/// </summary>
/// <param name="user">The <see cref="User"/> to create</param>
/// <param name="masterPasswordHash">The hashed master password the user entered</param>
/// <param name="providerInviteToken">The provider invite token sent to the user via email</param>
/// <param name="providerUserId">The provider user id which is used to validate the invite token</param>
/// <returns><see cref="IdentityResult"/></returns>
public Task<IdentityResult> RegisterUserViaProviderInviteToken(User user, string masterPasswordHash, string providerInviteToken, Guid providerUserId);
}

View File

@ -32,6 +32,7 @@ public class RegisterUserCommand : IRegisterUserCommand
private readonly IDataProtectorTokenFactory<OrgUserInviteTokenable> _orgUserInviteTokenDataFactory;
private readonly IDataProtectorTokenFactory<RegistrationEmailVerificationTokenable> _registrationEmailVerificationTokenDataFactory;
private readonly IDataProtector _organizationServiceDataProtector;
private readonly IDataProtector _providerServiceDataProtector;
private readonly ICurrentContext _currentContext;
@ -75,6 +76,8 @@ public class RegisterUserCommand : IRegisterUserCommand
_validateRedemptionTokenCommand = validateRedemptionTokenCommand;
_emergencyAccessInviteTokenDataFactory = emergencyAccessInviteTokenDataFactory;
_providerServiceDataProtector = dataProtectionProvider.CreateProtector("ProviderServiceDataProtector");
}
@ -303,6 +306,25 @@ public class RegisterUserCommand : IRegisterUserCommand
return result;
}
public async Task<IdentityResult> RegisterUserViaProviderInviteToken(User user, string masterPasswordHash,
string providerInviteToken, Guid providerUserId)
{
ValidateOpenRegistrationAllowed();
ValidateProviderInviteToken(providerInviteToken, providerUserId, user.Email);
user.EmailVerified = true;
user.ApiKey = CoreHelpers.SecureRandomString(30); // API key can't be null.
var result = await _userService.CreateUserAsync(user, masterPasswordHash);
if (result == IdentityResult.Success)
{
await _mailService.SendWelcomeEmailAsync(user);
await _referenceEventService.RaiseEventAsync(new ReferenceEvent(ReferenceEventType.Signup, user, _currentContext));
}
return result;
}
private void ValidateOpenRegistrationAllowed()
{
// We validate open registration on send of initial email and here b/c a user could technically start the
@ -333,6 +355,15 @@ public class RegisterUserCommand : IRegisterUserCommand
}
}
private void ValidateProviderInviteToken(string providerInviteToken, Guid providerUserId, string userEmail)
{
if (!CoreHelpers.TokenIsValid("ProviderUserInvite", _providerServiceDataProtector, providerInviteToken, userEmail, providerUserId,
_globalSettings.OrganizationInviteExpirationHours))
{
throw new BadRequestException("Invalid provider invite token.");
}
}
private RegistrationEmailVerificationTokenable ValidateRegistrationEmailVerificationTokenable(string emailVerificationToken, string userEmail)
{

View File

@ -1,4 +1,5 @@
using Bit.Core;
using System.Diagnostics;
using Bit.Core;
using Bit.Core.Auth.Enums;
using Bit.Core.Auth.Models.Api.Request.Accounts;
using Bit.Core.Auth.Models.Api.Response.Accounts;
@ -149,40 +150,44 @@ public class AccountsController : Controller
IdentityResult identityResult = null;
var delaysEnabled = !_featureService.IsEnabled(FeatureFlagKeys.EmailVerificationDisableTimingDelays);
if (!string.IsNullOrEmpty(model.OrgInviteToken) && model.OrganizationUserId.HasValue)
switch (model.GetTokenType())
{
identityResult = await _registerUserCommand.RegisterUserViaOrganizationInviteToken(user, model.MasterPasswordHash,
model.OrgInviteToken, model.OrganizationUserId);
case RegisterFinishTokenType.EmailVerification:
identityResult =
await _registerUserCommand.RegisterUserViaEmailVerificationToken(user, model.MasterPasswordHash,
model.EmailVerificationToken);
return await ProcessRegistrationResult(identityResult, user, delaysEnabled);
return await ProcessRegistrationResult(identityResult, user, delaysEnabled);
break;
case RegisterFinishTokenType.OrganizationInvite:
identityResult = await _registerUserCommand.RegisterUserViaOrganizationInviteToken(user, model.MasterPasswordHash,
model.OrgInviteToken, model.OrganizationUserId);
return await ProcessRegistrationResult(identityResult, user, delaysEnabled);
break;
case RegisterFinishTokenType.OrgSponsoredFreeFamilyPlan:
identityResult = await _registerUserCommand.RegisterUserViaOrganizationSponsoredFreeFamilyPlanInviteToken(user, model.MasterPasswordHash, model.OrgSponsoredFreeFamilyPlanToken);
return await ProcessRegistrationResult(identityResult, user, delaysEnabled);
break;
case RegisterFinishTokenType.EmergencyAccessInvite:
Debug.Assert(model.AcceptEmergencyAccessId.HasValue);
identityResult = await _registerUserCommand.RegisterUserViaAcceptEmergencyAccessInviteToken(user, model.MasterPasswordHash,
model.AcceptEmergencyAccessInviteToken, model.AcceptEmergencyAccessId.Value);
return await ProcessRegistrationResult(identityResult, user, delaysEnabled);
break;
case RegisterFinishTokenType.ProviderInvite:
Debug.Assert(model.ProviderUserId.HasValue);
identityResult = await _registerUserCommand.RegisterUserViaProviderInviteToken(user, model.MasterPasswordHash,
model.ProviderInviteToken, model.ProviderUserId.Value);
return await ProcessRegistrationResult(identityResult, user, delaysEnabled);
break;
default:
throw new BadRequestException("Invalid registration finish request");
}
if (!string.IsNullOrEmpty(model.OrgSponsoredFreeFamilyPlanToken))
{
identityResult = await _registerUserCommand.RegisterUserViaOrganizationSponsoredFreeFamilyPlanInviteToken(user, model.MasterPasswordHash, model.OrgSponsoredFreeFamilyPlanToken);
return await ProcessRegistrationResult(identityResult, user, delaysEnabled);
}
if (!string.IsNullOrEmpty(model.AcceptEmergencyAccessInviteToken) && model.AcceptEmergencyAccessId.HasValue)
{
identityResult = await _registerUserCommand.RegisterUserViaAcceptEmergencyAccessInviteToken(user, model.MasterPasswordHash,
model.AcceptEmergencyAccessInviteToken, model.AcceptEmergencyAccessId.Value);
return await ProcessRegistrationResult(identityResult, user, delaysEnabled);
}
if (string.IsNullOrEmpty(model.EmailVerificationToken))
{
throw new BadRequestException("Invalid registration finish request");
}
identityResult =
await _registerUserCommand.RegisterUserViaEmailVerificationToken(user, model.MasterPasswordHash,
model.EmailVerificationToken);
return await ProcessRegistrationResult(identityResult, user, delaysEnabled);
}
private async Task<RegisterResponseModel> ProcessRegistrationResult(IdentityResult result, User user, bool delaysEnabled)