1
0
mirror of https://github.com/bitwarden/server.git synced 2025-05-22 12:04:27 -05:00

[EC-343] Gate custom permissions behind enterprise plan (#2352)

* [EC-343] Added column 'UseCustomPermissions' to Organization table

* [EC-343] Added 'UseCustomPermissions' to Api responses

* [EC-343] Added 'UseCustomPermissions' to Admin view

* [EC-343] Add constraint to Organization table to have default UseCustomPermissions value

* [EC-343] Recreate OrganizationView to include UseCustomPermissions column

* [EC-343] Add MySql EF migrations

* [EC-343] Add Postgres EF migrations

* Revert "[EC-343] Add Postgres EF migrations"

This reverts commit 8f1654cb7d4b2d40ef01417bf73490ddd4f54add.

* [EC-343] Add Postgres migrations and script

* [EC-343] dotnet format

* [EC-343] Set 'Custom Permissions' feature as unchecked for teams plan

* [EC-343] Add CustomPermissions to plan upgrades

* [EC-343] Update CURRENT_LICENSE_FILE_VERSION

* [EC-343] Enable 'Custom Permissions' on Enterprise 2019 plan

* [EC-343] Updated migration script to include Enterprise 2019 plan

* [EC-343] Update CURRENT_LICENSE_FILE_VERSION to 10

* [EC-343] Move logic checking if Organization can use custom permissions to OrganizationService

* [EC-343] Add unit tests to validate UseCustomPermissions check

* [EC-343] Revert UseCustomPermissionsFlag migration

* [EC-343] Fix typo in OrganizationUserOrganizationDetailsViewQuery

* [EC-343] Add Postgres migrations without affecting other datetime column

* [EC-343] Create ValidateOrganizationCustomPermissionsEnabledAsync. Add more unit tests around CustomPermissions check

* [EC-343] Add curly brackets to if condition

* [EC-343] Rename unit tests
This commit is contained in:
Rui Tomé 2022-12-06 09:50:08 +00:00 committed by GitHub
parent e0f37e514e
commit ae280a313c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
33 changed files with 4135 additions and 11 deletions

View File

@ -42,6 +42,7 @@ public class OrganizationEditModel : OrganizationViewModel
UseResetPassword = org.UseResetPassword;
SelfHost = org.SelfHost;
UsersGetPremium = org.UsersGetPremium;
UseCustomPermissions = org.UseCustomPermissions;
MaxStorageGb = org.MaxStorageGb;
Gateway = org.Gateway;
GatewayCustomerId = org.GatewayCustomerId;
@ -101,6 +102,8 @@ public class OrganizationEditModel : OrganizationViewModel
public bool SelfHost { get; set; }
[Display(Name = "Users Get Premium")]
public bool UsersGetPremium { get; set; }
[Display(Name = "Custom Permissions")]
public bool UseCustomPermissions { get; set; }
[Display(Name = "Max. Storage GB")]
public short? MaxStorageGb { get; set; }
[Display(Name = "Gateway")]
@ -139,6 +142,7 @@ public class OrganizationEditModel : OrganizationViewModel
existingOrganization.UseResetPassword = UseResetPassword;
existingOrganization.SelfHost = SelfHost;
existingOrganization.UsersGetPremium = UsersGetPremium;
existingOrganization.UseCustomPermissions = UseCustomPermissions;
existingOrganization.MaxStorageGb = MaxStorageGb;
existingOrganization.Gateway = Gateway;
existingOrganization.GatewayCustomerId = GatewayCustomerId;

View File

@ -27,6 +27,7 @@
document.getElementById('@(nameof(Model.UseDirectory))').checked = true;
document.getElementById('@(nameof(Model.UseEvents))').checked = true;
document.getElementById('@(nameof(Model.UsersGetPremium))').checked = true;
document.getElementById('@(nameof(Model.UseCustomPermissions))').checked = false;
document.getElementById('@(nameof(Model.UseTotp))').checked = true;
document.getElementById('@(nameof(Model.Use2fa))').checked = true;
document.getElementById('@(nameof(Model.UseApi))').checked = true;
@ -61,6 +62,7 @@
document.getElementById('@(nameof(Model.UseDirectory))').checked = true;
document.getElementById('@(nameof(Model.UseEvents))').checked = true;
document.getElementById('@(nameof(Model.UsersGetPremium))').checked = true;
document.getElementById('@(nameof(Model.UseCustomPermissions))').checked = true;
document.getElementById('@(nameof(Model.UseTotp))').checked = true;
document.getElementById('@(nameof(Model.Use2fa))').checked = true;
document.getElementById('@(nameof(Model.UseApi))').checked = true;
@ -237,10 +239,14 @@
<input type="checkbox" class="form-check-input" asp-for="UseResetPassword">
<label class="form-check-label" asp-for="UseResetPassword"></label>
</div>
<div class="form-check mb-3">
<div class="form-check">
<input type="checkbox" class="form-check-input" asp-for="UsersGetPremium">
<label class="form-check-label" asp-for="UsersGetPremium"></label>
</div>
<div class="form-check mb-3">
<input type="checkbox" class="form-check-input" asp-for="UseCustomPermissions">
<label class="form-check-label" asp-for="UseCustomPermissions"></label>
</div>
<h2>Licensing</h2>
<div class="row">
<div class="col-sm">

View File

@ -44,6 +44,7 @@ public class OrganizationResponseModel : ResponseModel
UseApi = organization.UseApi;
UseResetPassword = organization.UseResetPassword;
UsersGetPremium = organization.UsersGetPremium;
UseCustomPermissions = organization.UseCustomPermissions;
SelfHost = organization.SelfHost;
HasPublicAndPrivateKeys = organization.PublicKey != null && organization.PrivateKey != null;
}
@ -76,6 +77,7 @@ public class OrganizationResponseModel : ResponseModel
public bool UseApi { get; set; }
public bool UseResetPassword { get; set; }
public bool UsersGetPremium { get; set; }
public bool UseCustomPermissions { get; set; }
public bool SelfHost { get; set; }
public bool HasPublicAndPrivateKeys { get; set; }
}

View File

@ -26,6 +26,7 @@ public class ProfileOrganizationResponseModel : ResponseModel
UseApi = organization.UseApi;
UseResetPassword = organization.UseResetPassword;
UsersGetPremium = organization.UsersGetPremium;
UseCustomPermissions = organization.UseCustomPermissions;
SelfHost = organization.SelfHost;
Seats = organization.Seats;
MaxCollections = organization.MaxCollections;
@ -73,6 +74,7 @@ public class ProfileOrganizationResponseModel : ResponseModel
public bool UseApi { get; set; }
public bool UseResetPassword { get; set; }
public bool UsersGetPremium { get; set; }
public bool UseCustomPermissions { get; set; }
public bool SelfHost { get; set; }
public int? Seats { get; set; }
public short? MaxCollections { get; set; }

View File

@ -22,6 +22,7 @@ public class ProfileProviderOrganizationResponseModel : ProfileOrganizationRespo
UseApi = organization.UseApi;
UseResetPassword = organization.UseResetPassword;
UsersGetPremium = organization.UsersGetPremium;
UseCustomPermissions = organization.UseCustomPermissions;
SelfHost = organization.SelfHost;
Seats = organization.Seats;
MaxCollections = organization.MaxCollections;

View File

@ -47,6 +47,7 @@ public class Organization : ITableObject<Guid>, ISubscriber, IStorable, IStorabl
public bool UseResetPassword { get; set; }
public bool SelfHost { get; set; }
public bool UsersGetPremium { get; set; }
public bool UseCustomPermissions { get; set; }
public long? Storage { get; set; }
public short? MaxStorageGb { get; set; }
public GatewayType? Gateway { get; set; }

View File

@ -45,6 +45,7 @@ public class OrganizationLicense : ILicense
MaxStorageGb = org.MaxStorageGb;
SelfHost = org.SelfHost;
UsersGetPremium = org.UsersGetPremium;
UseCustomPermissions = org.UseCustomPermissions;
Issued = DateTime.UtcNow;
if (subscriptionInfo?.Subscription == null)
@ -117,6 +118,7 @@ public class OrganizationLicense : ILicense
public short? MaxStorageGb { get; set; }
public bool SelfHost { get; set; }
public bool UsersGetPremium { get; set; }
public bool UseCustomPermissions { get; set; }
public int Version { get; set; }
public DateTime Issued { get; set; }
public DateTime? Refresh { get; set; }
@ -131,10 +133,10 @@ public class OrganizationLicense : ILicense
/// <summary>
/// Represents the current version of the license format. Should be updated whenever new fields are added.
/// </summary>
private const int CURRENT_LICENSE_FILE_VERSION = 9;
private const int CURRENT_LICENSE_FILE_VERSION = 10;
private bool ValidLicenseVersion
{
get => Version is >= 1 and <= 10;
get => Version is >= 1 and <= 11;
}
public byte[] GetDataBytes(bool forHash = false)
@ -166,6 +168,8 @@ public class OrganizationLicense : ILicense
(Version >= 9 || !p.Name.Equals(nameof(UseKeyConnector))) &&
// UseScim was added in Version 10
(Version >= 10 || !p.Name.Equals(nameof(UseScim))) &&
// UseCustomPermissions was added in Version 11
(Version >= 11 || !p.Name.Equals(nameof(UseCustomPermissions))) &&
(
!forHash ||
(
@ -279,6 +283,11 @@ public class OrganizationLicense : ILicense
valid = organization.UseScim == UseScim;
}
if (valid && Version >= 11)
{
valid = organization.UseCustomPermissions == UseCustomPermissions;
}
return valid;
}
else

View File

@ -19,6 +19,7 @@ public class OrganizationAbility
UseKeyConnector = organization.UseKeyConnector;
UseScim = organization.UseScim;
UseResetPassword = organization.UseResetPassword;
UseCustomPermissions = organization.UseCustomPermissions;
}
public Guid Id { get; set; }
@ -31,4 +32,5 @@ public class OrganizationAbility
public bool UseKeyConnector { get; set; }
public bool UseScim { get; set; }
public bool UseResetPassword { get; set; }
public bool UseCustomPermissions { get; set; }
}

View File

@ -18,6 +18,7 @@ public class OrganizationUserOrganizationDetails
public bool UseResetPassword { get; set; }
public bool SelfHost { get; set; }
public bool UsersGetPremium { get; set; }
public bool UseCustomPermissions { get; set; }
public int? Seats { get; set; }
public short? MaxCollections { get; set; }
public short? MaxStorageGb { get; set; }

View File

@ -20,6 +20,7 @@ public class ProviderUserOrganizationDetails
public bool UseResetPassword { get; set; }
public bool SelfHost { get; set; }
public bool UsersGetPremium { get; set; }
public bool UseCustomPermissions { get; set; }
public int? Seats { get; set; }
public short? MaxCollections { get; set; }
public short? MaxStorageGb { get; set; }

View File

@ -37,6 +37,7 @@ public class Plan
public bool HasScim { get; set; }
public bool HasResetPassword { get; set; }
public bool UsersGetPremium { get; set; }
public bool HasCustomPermissions { get; set; }
public int UpgradeSortOrder { get; set; }
public int DisplaySortOrder { get; set; }

View File

@ -280,6 +280,18 @@ public class OrganizationService : IOrganizationService
}
}
if (!newPlan.HasCustomPermissions && organization.UseCustomPermissions)
{
var organizationCustomUsers =
await _organizationUserRepository.GetManyByOrganizationAsync(organization.Id,
OrganizationUserType.Custom);
if (organizationCustomUsers.Any())
{
throw new BadRequestException("Your new plan does not allow the Custom Permissions feature. " +
"Disable your Custom Permissions configuration.");
}
}
// TODO: Check storage?
string paymentIntentClientSecret = null;
@ -322,6 +334,7 @@ public class OrganizationService : IOrganizationService
organization.UseResetPassword = newPlan.HasResetPassword;
organization.SelfHost = newPlan.HasSelfHost;
organization.UsersGetPremium = newPlan.UsersGetPremium || upgrade.PremiumAccessAddon;
organization.UseCustomPermissions = newPlan.HasCustomPermissions;
organization.Plan = newPlan.Name;
organization.Enabled = success;
organization.PublicKey = upgrade.PublicKey;
@ -621,6 +634,7 @@ public class OrganizationService : IOrganizationService
UseResetPassword = plan.HasResetPassword,
SelfHost = plan.HasSelfHost,
UsersGetPremium = plan.UsersGetPremium || signup.PremiumAccessAddon,
UseCustomPermissions = plan.HasCustomPermissions,
UseScim = plan.HasScim,
Plan = plan.Name,
Gateway = null,
@ -730,6 +744,7 @@ public class OrganizationService : IOrganizationService
Plan = license.Plan,
SelfHost = license.SelfHost,
UsersGetPremium = license.UsersGetPremium,
UseCustomPermissions = license.UseCustomPermissions,
Gateway = null,
GatewayCustomerId = null,
GatewaySubscriptionId = null,
@ -931,6 +946,18 @@ public class OrganizationService : IOrganizationService
}
}
if (!license.UseCustomPermissions && organization.UseCustomPermissions)
{
var organizationCustomUsers =
await _organizationUserRepository.GetManyByOrganizationAsync(organization.Id,
OrganizationUserType.Custom);
if (organizationCustomUsers.Any())
{
throw new BadRequestException("Your new plan does not allow the Custom Permissions feature. " +
"Disable your Custom Permissions configuration.");
}
}
if (!license.UseResetPassword && organization.UseResetPassword)
{
var resetPasswordPolicy =
@ -966,6 +993,7 @@ public class OrganizationService : IOrganizationService
organization.UseResetPassword = license.UseResetPassword;
organization.SelfHost = license.SelfHost;
organization.UsersGetPremium = license.UsersGetPremium;
organization.UseCustomPermissions = license.UseCustomPermissions;
organization.Plan = license.Plan;
organization.Enabled = license.Enabled;
organization.ExpirationDate = license.Expires;
@ -1122,6 +1150,7 @@ public class OrganizationService : IOrganizationService
foreach (var type in inviteTypes)
{
await ValidateOrganizationUserUpdatePermissions(organizationId, type, null);
await ValidateOrganizationCustomPermissionsEnabledAsync(organizationId, type);
}
}
@ -1648,6 +1677,8 @@ public class OrganizationService : IOrganizationService
await ValidateOrganizationUserUpdatePermissions(user.OrganizationId, user.Type, originalUser.Type);
}
await ValidateOrganizationCustomPermissionsEnabledAsync(user.OrganizationId, user.Type);
if (user.Type != OrganizationUserType.Owner &&
!await HasConfirmedOwnersExceptAsync(user.OrganizationId, new[] { user.Id }))
{
@ -2256,6 +2287,25 @@ public class OrganizationService : IOrganizationService
}
}
private async Task ValidateOrganizationCustomPermissionsEnabledAsync(Guid organizationId, OrganizationUserType newType)
{
if (newType != OrganizationUserType.Custom)
{
return;
}
var organization = await _organizationRepository.GetByIdAsync(organizationId);
if (organization == null)
{
throw new NotFoundException();
}
if (!organization.UseCustomPermissions)
{
throw new BadRequestException("To enable custom permissions the organization must be on an Enterprise plan.");
}
}
private async Task ValidateDeleteOrganizationAsync(Organization organization)
{
var ssoConfig = await _ssoConfigRepository.GetByOrganizationIdAsync(organization.Id);

View File

@ -241,6 +241,7 @@ public class StaticStore
Has2fa = true,
HasApi = true,
UsersGetPremium = true,
HasCustomPermissions = true,
UpgradeSortOrder = 3,
DisplaySortOrder = 3,
@ -279,6 +280,7 @@ public class StaticStore
HasApi = true,
HasSelfHost = true,
UsersGetPremium = true,
HasCustomPermissions = true,
UpgradeSortOrder = 3,
DisplaySortOrder = 3,
@ -418,6 +420,7 @@ public class StaticStore
HasScim = true,
HasResetPassword = true,
UsersGetPremium = true,
HasCustomPermissions = true,
UpgradeSortOrder = 3,
DisplaySortOrder = 3,
@ -458,6 +461,7 @@ public class StaticStore
HasScim = true,
HasResetPassword = true,
UsersGetPremium = true,
HasCustomPermissions = true,
UpgradeSortOrder = 3,
DisplaySortOrder = 3,

View File

@ -85,6 +85,7 @@ public class OrganizationRepository : Repository<Core.Entities.Organization, Org
UseKeyConnector = e.UseKeyConnector,
UseResetPassword = e.UseResetPassword,
UseScim = e.UseScim,
UseCustomPermissions = e.UseCustomPermissions
}).ToListAsync();
}
}

View File

@ -39,6 +39,7 @@ public class OrganizationUserOrganizationDetailsViewQuery : IQuery<OrganizationU
UseResetPassword = o.UseResetPassword,
SelfHost = o.SelfHost,
UsersGetPremium = o.UsersGetPremium,
UseCustomPermissions = o.UseCustomPermissions,
Seats = o.Seats,
MaxCollections = o.MaxCollections,
MaxStorageGb = o.MaxStorageGb,

View File

@ -29,6 +29,7 @@ public class ProviderUserOrganizationDetailsViewQuery : IQuery<ProviderUserOrgan
UseApi = x.o.UseApi,
SelfHost = x.o.SelfHost,
UsersGetPremium = x.o.UsersGetPremium,
UseCustomPermissions = x.o.UseCustomPermissions,
Seats = x.o.Seats,
MaxCollections = x.o.MaxCollections,
MaxStorageGb = x.o.MaxStorageGb,

View File

@ -41,7 +41,8 @@
@OwnersNotifiedOfAutoscaling DATETIME2(7),
@MaxAutoscaleSeats INT,
@UseKeyConnector BIT = 0,
@UseScim BIT = 0
@UseScim BIT = 0,
@UseCustomPermissions BIT = 0
AS
BEGIN
SET NOCOUNT ON
@ -90,7 +91,8 @@ BEGIN
[OwnersNotifiedOfAutoscaling],
[MaxAutoscaleSeats],
[UseKeyConnector],
[UseScim]
[UseScim],
[UseCustomPermissions]
)
VALUES
(
@ -136,6 +138,7 @@ BEGIN
@OwnersNotifiedOfAutoscaling,
@MaxAutoscaleSeats,
@UseKeyConnector,
@UseScim
@UseScim,
@UseCustomPermissions
)
END

View File

@ -14,6 +14,7 @@ BEGIN
0
END AS [Using2fa],
[UsersGetPremium],
[UseCustomPermissions],
[UseSso],
[UseKeyConnector],
[UseScim],

View File

@ -41,7 +41,8 @@
@OwnersNotifiedOfAutoscaling DATETIME2(7),
@MaxAutoscaleSeats INT,
@UseKeyConnector BIT = 0,
@UseScim BIT = 0
@UseScim BIT = 0,
@UseCustomPermissions BIT = 0
AS
BEGIN
SET NOCOUNT ON
@ -90,7 +91,8 @@ BEGIN
[OwnersNotifiedOfAutoscaling] = @OwnersNotifiedOfAutoscaling,
[MaxAutoscaleSeats] = @MaxAutoscaleSeats,
[UseKeyConnector] = @UseKeyConnector,
[UseScim] = @UseScim
[UseScim] = @UseScim,
[UseCustomPermissions] = @UseCustomPermissions
WHERE
[Id] = @Id
END

View File

@ -42,6 +42,7 @@
[MaxAutoscaleSeats] INT NULL,
[UseKeyConnector] BIT NOT NULL,
[UseScim] BIT NOT NULL CONSTRAINT [DF_Organization_UseScim] DEFAULT (0),
[UseCustomPermissions] BIT NOT NULL CONSTRAINT [DF_Organization_UseCustomPermissions] DEFAULT (0),
CONSTRAINT [PK_Organization] PRIMARY KEY CLUSTERED ([Id] ASC)
);

View File

@ -19,6 +19,7 @@ SELECT
O.[UseResetPassword],
O.[SelfHost],
O.[UsersGetPremium],
O.[UseCustomPermissions],
O.[Seats],
O.[MaxCollections],
O.[MaxStorageGb],

View File

@ -18,6 +18,7 @@ SELECT
O.[UseResetPassword],
O.[SelfHost],
O.[UsersGetPremium],
O.[UseCustomPermissions],
O.[Seats],
O.[MaxCollections],
O.[MaxStorageGb],

View File

@ -263,6 +263,8 @@ public class OrganizationServiceTests
public async Task InviteUser_NonAdminConfiguringAdmin_Throws(Organization organization, OrganizationUserInvite invite,
OrganizationUser invitor, SutProvider<OrganizationService> sutProvider)
{
organization.UseCustomPermissions = true;
var organizationRepository = sutProvider.GetDependency<IOrganizationRepository>();
var currentContext = sutProvider.GetDependency<ICurrentContext>();
@ -274,6 +276,84 @@ public class OrganizationServiceTests
Assert.Contains("only owners and admins", exception.Message.ToLowerInvariant());
}
[Theory]
[OrganizationInviteCustomize(
InviteeUserType = OrganizationUserType.Custom,
InvitorUserType = OrganizationUserType.Admin
), BitAutoData]
public async Task InviteUser_WithCustomType_WhenUseCustomPermissionsIsFalse_Throws(Organization organization, OrganizationUserInvite invite,
OrganizationUser invitor, SutProvider<OrganizationService> sutProvider)
{
organization.UseCustomPermissions = false;
invite.Permissions = null;
invitor.Status = OrganizationUserStatusType.Confirmed;
var organizationRepository = sutProvider.GetDependency<IOrganizationRepository>();
var organizationUserRepository = sutProvider.GetDependency<IOrganizationUserRepository>();
var currentContext = sutProvider.GetDependency<ICurrentContext>();
organizationRepository.GetByIdAsync(organization.Id).Returns(organization);
organizationUserRepository.GetManyByOrganizationAsync(organization.Id, OrganizationUserType.Owner)
.Returns(new[] { invitor });
currentContext.OrganizationOwner(organization.Id).Returns(true);
currentContext.ManageUsers(organization.Id).Returns(true);
var exception = await Assert.ThrowsAsync<BadRequestException>(
() => sutProvider.Sut.InviteUsersAsync(organization.Id, invitor.UserId, new (OrganizationUserInvite, string)[] { (invite, null) }));
Assert.Contains("to enable custom permissions", exception.Message.ToLowerInvariant());
}
[Theory]
[OrganizationInviteCustomize(
InviteeUserType = OrganizationUserType.Custom,
InvitorUserType = OrganizationUserType.Admin
), BitAutoData]
public async Task InviteUser_WithCustomType_WhenUseCustomPermissionsIsTrue_Passes(Organization organization, OrganizationUserInvite invite,
OrganizationUser invitor, SutProvider<OrganizationService> sutProvider)
{
organization.UseCustomPermissions = true;
invite.Permissions = null;
invitor.Status = OrganizationUserStatusType.Confirmed;
var organizationRepository = sutProvider.GetDependency<IOrganizationRepository>();
var organizationUserRepository = sutProvider.GetDependency<IOrganizationUserRepository>();
var currentContext = sutProvider.GetDependency<ICurrentContext>();
organizationRepository.GetByIdAsync(organization.Id).Returns(organization);
organizationUserRepository.GetManyByOrganizationAsync(organization.Id, OrganizationUserType.Owner)
.Returns(new[] { invitor });
currentContext.OrganizationOwner(organization.Id).Returns(true);
currentContext.ManageUsers(organization.Id).Returns(true);
await sutProvider.Sut.InviteUsersAsync(organization.Id, invitor.UserId, new (OrganizationUserInvite, string)[] { (invite, null) });
}
[Theory]
[BitAutoData(OrganizationUserType.Admin)]
[BitAutoData(OrganizationUserType.Manager)]
[BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.User)]
public async Task InviteUser_WithNonCustomType_WhenUseCustomPermissionsIsFalse_Passes(OrganizationUserType inviteUserType, Organization organization, OrganizationUserInvite invite,
OrganizationUser invitor, SutProvider<OrganizationService> sutProvider)
{
organization.UseCustomPermissions = false;
invite.Type = inviteUserType;
invite.Permissions = null;
invitor.Status = OrganizationUserStatusType.Confirmed;
var organizationRepository = sutProvider.GetDependency<IOrganizationRepository>();
var organizationUserRepository = sutProvider.GetDependency<IOrganizationUserRepository>();
var currentContext = sutProvider.GetDependency<ICurrentContext>();
organizationRepository.GetByIdAsync(organization.Id).Returns(organization);
organizationUserRepository.GetManyByOrganizationAsync(organization.Id, OrganizationUserType.Owner)
.Returns(new[] { invitor });
currentContext.OrganizationOwner(organization.Id).Returns(true);
currentContext.ManageUsers(organization.Id).Returns(true);
await sutProvider.Sut.InviteUsersAsync(organization.Id, invitor.UserId, new (OrganizationUserInvite, string)[] { (invite, null) });
}
[Theory]
[OrganizationInviteCustomize(
InviteeUserType = OrganizationUserType.Manager,
@ -440,18 +520,114 @@ public class OrganizationServiceTests
[Theory, BitAutoData]
public async Task SaveUser_Passes(
Organization organization,
OrganizationUser oldUserData,
OrganizationUser newUserData,
IEnumerable<SelectionReadOnly> collections,
[OrganizationUser(type: OrganizationUserType.Owner)] OrganizationUser savingUser,
SutProvider<OrganizationService> sutProvider)
{
var organizationRepository = sutProvider.GetDependency<IOrganizationRepository>();
var organizationUserRepository = sutProvider.GetDependency<IOrganizationUserRepository>();
var currentContext = sutProvider.GetDependency<ICurrentContext>();
organizationRepository.GetByIdAsync(organization.Id).Returns(organization);
newUserData.Id = oldUserData.Id;
newUserData.UserId = oldUserData.UserId;
newUserData.OrganizationId = savingUser.OrganizationId = oldUserData.OrganizationId;
newUserData.OrganizationId = savingUser.OrganizationId = oldUserData.OrganizationId = organization.Id;
organizationUserRepository.GetByIdAsync(oldUserData.Id).Returns(oldUserData);
organizationUserRepository.GetManyByOrganizationAsync(savingUser.OrganizationId, OrganizationUserType.Owner)
.Returns(new List<OrganizationUser> { savingUser });
currentContext.OrganizationOwner(savingUser.OrganizationId).Returns(true);
await sutProvider.Sut.SaveUserAsync(newUserData, savingUser.UserId, collections);
}
[Theory, BitAutoData]
public async Task SaveUser_WithCustomType_WhenUseCustomPermissionsIsFalse_Throws(
Organization organization,
OrganizationUser oldUserData,
[OrganizationUser(type: OrganizationUserType.Custom)] OrganizationUser newUserData,
IEnumerable<SelectionReadOnly> collections,
[OrganizationUser(type: OrganizationUserType.Owner)] OrganizationUser savingUser,
SutProvider<OrganizationService> sutProvider)
{
organization.UseCustomPermissions = false;
var organizationRepository = sutProvider.GetDependency<IOrganizationRepository>();
var organizationUserRepository = sutProvider.GetDependency<IOrganizationUserRepository>();
var currentContext = sutProvider.GetDependency<ICurrentContext>();
organizationRepository.GetByIdAsync(organization.Id).Returns(organization);
newUserData.Id = oldUserData.Id;
newUserData.UserId = oldUserData.UserId;
newUserData.OrganizationId = savingUser.OrganizationId = oldUserData.OrganizationId = organization.Id;
organizationUserRepository.GetByIdAsync(oldUserData.Id).Returns(oldUserData);
organizationUserRepository.GetManyByOrganizationAsync(savingUser.OrganizationId, OrganizationUserType.Owner)
.Returns(new List<OrganizationUser> { savingUser });
currentContext.OrganizationOwner(savingUser.OrganizationId).Returns(true);
var exception = await Assert.ThrowsAsync<BadRequestException>(
() => sutProvider.Sut.SaveUserAsync(newUserData, savingUser.UserId, collections));
Assert.Contains("to enable custom permissions", exception.Message.ToLowerInvariant());
}
[Theory]
[BitAutoData(OrganizationUserType.Admin)]
[BitAutoData(OrganizationUserType.Manager)]
[BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.User)]
public async Task SaveUser_WithNonCustomType_WhenUseCustomPermissionsIsFalse_Passes(
OrganizationUserType newUserType,
Organization organization,
OrganizationUser oldUserData,
OrganizationUser newUserData,
IEnumerable<SelectionReadOnly> collections,
[OrganizationUser(type: OrganizationUserType.Owner)] OrganizationUser savingUser,
SutProvider<OrganizationService> sutProvider)
{
organization.UseCustomPermissions = false;
var organizationRepository = sutProvider.GetDependency<IOrganizationRepository>();
var organizationUserRepository = sutProvider.GetDependency<IOrganizationUserRepository>();
var currentContext = sutProvider.GetDependency<ICurrentContext>();
organizationRepository.GetByIdAsync(organization.Id).Returns(organization);
newUserData.Id = oldUserData.Id;
newUserData.UserId = oldUserData.UserId;
newUserData.OrganizationId = savingUser.OrganizationId = oldUserData.OrganizationId = organization.Id;
newUserData.Type = newUserType;
organizationUserRepository.GetByIdAsync(oldUserData.Id).Returns(oldUserData);
organizationUserRepository.GetManyByOrganizationAsync(savingUser.OrganizationId, OrganizationUserType.Owner)
.Returns(new List<OrganizationUser> { savingUser });
currentContext.OrganizationOwner(savingUser.OrganizationId).Returns(true);
await sutProvider.Sut.SaveUserAsync(newUserData, savingUser.UserId, collections);
}
[Theory, BitAutoData]
public async Task SaveUser_WithCustomType_WhenUseCustomPermissionsIsTrue_Passes(
Organization organization,
OrganizationUser oldUserData,
[OrganizationUser(type: OrganizationUserType.Custom)] OrganizationUser newUserData,
IEnumerable<SelectionReadOnly> collections,
[OrganizationUser(type: OrganizationUserType.Owner)] OrganizationUser savingUser,
SutProvider<OrganizationService> sutProvider)
{
organization.UseCustomPermissions = true;
var organizationRepository = sutProvider.GetDependency<IOrganizationRepository>();
var organizationUserRepository = sutProvider.GetDependency<IOrganizationUserRepository>();
var currentContext = sutProvider.GetDependency<ICurrentContext>();
organizationRepository.GetByIdAsync(organization.Id).Returns(organization);
newUserData.Id = oldUserData.Id;
newUserData.UserId = oldUserData.UserId;
newUserData.OrganizationId = savingUser.OrganizationId = oldUserData.OrganizationId = organization.Id;
organizationUserRepository.GetByIdAsync(oldUserData.Id).Returns(oldUserData);
organizationUserRepository.GetManyByOrganizationAsync(savingUser.OrganizationId, OrganizationUserType.Owner)
.Returns(new List<OrganizationUser> { savingUser });

View File

@ -34,6 +34,7 @@ public class OrganizationCompare : IEqualityComparer<Organization>
x.UseApi.Equals(y.UseApi) &&
x.SelfHost.Equals(y.SelfHost) &&
x.UsersGetPremium.Equals(y.UsersGetPremium) &&
x.UseCustomPermissions.Equals(y.UseCustomPermissions) &&
x.Storage.Equals(y.Storage) &&
x.MaxStorageGb.Equals(y.MaxStorageGb) &&
x.Gateway.Equals(y.Gateway) &&

View File

@ -0,0 +1,412 @@
IF COL_LENGTH('[dbo].[Organization]', 'UseCustomPermissions') IS NULL
BEGIN
ALTER TABLE
[dbo].[Organization]
ADD
[UseCustomPermissions] BIT NOT NULL CONSTRAINT [DF_Organization_UseCustomPermissions] DEFAULT (0);
END
GO
-- Recreate OrganizationView so that it includes the UseCustomPermissions column
IF OBJECT_ID('[dbo].[OrganizationView]') IS NOT NULL
BEGIN
DROP VIEW [dbo].[OrganizationView]
END
GO
CREATE VIEW [dbo].[OrganizationView]
AS
SELECT
*
FROM
[dbo].[Organization]
GO
CREATE OR ALTER VIEW [dbo].[OrganizationUserOrganizationDetailsView]
AS
SELECT
OU.[UserId],
OU.[OrganizationId],
O.[Name],
O.[Enabled],
O.[PlanType],
O.[UsePolicies],
O.[UseSso],
O.[UseKeyConnector],
O.[UseScim],
O.[UseGroups],
O.[UseDirectory],
O.[UseEvents],
O.[UseTotp],
O.[Use2fa],
O.[UseApi],
O.[UseResetPassword],
O.[SelfHost],
O.[UsersGetPremium],
O.[UseCustomPermissions],
O.[Seats],
O.[MaxCollections],
O.[MaxStorageGb],
O.[Identifier],
OU.[Key],
OU.[ResetPasswordKey],
O.[PublicKey],
O.[PrivateKey],
OU.[Status],
OU.[Type],
SU.[ExternalId] SsoExternalId,
OU.[Permissions],
PO.[ProviderId],
P.[Name] ProviderName,
SS.[Data] SsoConfig,
OS.[FriendlyName] FamilySponsorshipFriendlyName,
OS.[LastSyncDate] FamilySponsorshipLastSyncDate,
OS.[ToDelete] FamilySponsorshipToDelete,
OS.[ValidUntil] FamilySponsorshipValidUntil
FROM
[dbo].[OrganizationUser] OU
LEFT JOIN
[dbo].[Organization] O ON O.[Id] = OU.[OrganizationId]
LEFT JOIN
[dbo].[SsoUser] SU ON SU.[UserId] = OU.[UserId] AND SU.[OrganizationId] = OU.[OrganizationId]
LEFT JOIN
[dbo].[ProviderOrganization] PO ON PO.[OrganizationId] = O.[Id]
LEFT JOIN
[dbo].[Provider] P ON P.[Id] = PO.[ProviderId]
LEFT JOIN
[dbo].[SsoConfig] SS ON SS.[OrganizationId] = OU.[OrganizationId]
LEFT JOIN
[dbo].[OrganizationSponsorship] OS ON OS.[SponsoringOrganizationUserID] = OU.[Id]
GO
CREATE OR ALTER VIEW [dbo].[ProviderUserProviderOrganizationDetailsView]
AS
SELECT
PU.[UserId],
PO.[OrganizationId],
O.[Name],
O.[Enabled],
O.[UsePolicies],
O.[UseSso],
O.[UseKeyConnector],
O.[UseScim],
O.[UseGroups],
O.[UseDirectory],
O.[UseEvents],
O.[UseTotp],
O.[Use2fa],
O.[UseApi],
O.[UseResetPassword],
O.[SelfHost],
O.[UsersGetPremium],
O.[UseCustomPermissions],
O.[Seats],
O.[MaxCollections],
O.[MaxStorageGb],
O.[Identifier],
PO.[Key],
O.[PublicKey],
O.[PrivateKey],
PU.[Status],
PU.[Type],
PO.[ProviderId],
PU.[Id] ProviderUserId,
P.[Name] ProviderName
FROM
[dbo].[ProviderUser] PU
INNER JOIN
[dbo].[ProviderOrganization] PO ON PO.[ProviderId] = PU.[ProviderId]
INNER JOIN
[dbo].[Organization] O ON O.[Id] = PO.[OrganizationId]
INNER JOIN
[dbo].[Provider] P ON P.[Id] = PU.[ProviderId]
GO
CREATE OR ALTER PROCEDURE [dbo].[Organization_Create]
@Id UNIQUEIDENTIFIER OUTPUT,
@Identifier NVARCHAR(50),
@Name NVARCHAR(50),
@BusinessName NVARCHAR(50),
@BusinessAddress1 NVARCHAR(50),
@BusinessAddress2 NVARCHAR(50),
@BusinessAddress3 NVARCHAR(50),
@BusinessCountry VARCHAR(2),
@BusinessTaxNumber NVARCHAR(30),
@BillingEmail NVARCHAR(256),
@Plan NVARCHAR(50),
@PlanType TINYINT,
@Seats INT,
@MaxCollections SMALLINT,
@UsePolicies BIT,
@UseSso BIT,
@UseGroups BIT,
@UseDirectory BIT,
@UseEvents BIT,
@UseTotp BIT,
@Use2fa BIT,
@UseApi BIT,
@UseResetPassword BIT,
@SelfHost BIT,
@UsersGetPremium BIT,
@Storage BIGINT,
@MaxStorageGb SMALLINT,
@Gateway TINYINT,
@GatewayCustomerId VARCHAR(50),
@GatewaySubscriptionId VARCHAR(50),
@ReferenceData VARCHAR(MAX),
@Enabled BIT,
@LicenseKey VARCHAR(100),
@PublicKey VARCHAR(MAX),
@PrivateKey VARCHAR(MAX),
@TwoFactorProviders NVARCHAR(MAX),
@ExpirationDate DATETIME2(7),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@OwnersNotifiedOfAutoscaling DATETIME2(7),
@MaxAutoscaleSeats INT,
@UseKeyConnector BIT = 0,
@UseScim BIT = 0,
@UseCustomPermissions BIT = 0
AS
BEGIN
SET NOCOUNT ON
INSERT INTO [dbo].[Organization]
(
[Id],
[Identifier],
[Name],
[BusinessName],
[BusinessAddress1],
[BusinessAddress2],
[BusinessAddress3],
[BusinessCountry],
[BusinessTaxNumber],
[BillingEmail],
[Plan],
[PlanType],
[Seats],
[MaxCollections],
[UsePolicies],
[UseSso],
[UseGroups],
[UseDirectory],
[UseEvents],
[UseTotp],
[Use2fa],
[UseApi],
[UseResetPassword],
[SelfHost],
[UsersGetPremium],
[Storage],
[MaxStorageGb],
[Gateway],
[GatewayCustomerId],
[GatewaySubscriptionId],
[ReferenceData],
[Enabled],
[LicenseKey],
[PublicKey],
[PrivateKey],
[TwoFactorProviders],
[ExpirationDate],
[CreationDate],
[RevisionDate],
[OwnersNotifiedOfAutoscaling],
[MaxAutoscaleSeats],
[UseKeyConnector],
[UseScim],
[UseCustomPermissions]
)
VALUES
(
@Id,
@Identifier,
@Name,
@BusinessName,
@BusinessAddress1,
@BusinessAddress2,
@BusinessAddress3,
@BusinessCountry,
@BusinessTaxNumber,
@BillingEmail,
@Plan,
@PlanType,
@Seats,
@MaxCollections,
@UsePolicies,
@UseSso,
@UseGroups,
@UseDirectory,
@UseEvents,
@UseTotp,
@Use2fa,
@UseApi,
@UseResetPassword,
@SelfHost,
@UsersGetPremium,
@Storage,
@MaxStorageGb,
@Gateway,
@GatewayCustomerId,
@GatewaySubscriptionId,
@ReferenceData,
@Enabled,
@LicenseKey,
@PublicKey,
@PrivateKey,
@TwoFactorProviders,
@ExpirationDate,
@CreationDate,
@RevisionDate,
@OwnersNotifiedOfAutoscaling,
@MaxAutoscaleSeats,
@UseKeyConnector,
@UseScim,
@UseCustomPermissions
)
END
GO
CREATE OR ALTER PROCEDURE [dbo].[Organization_Update]
@Id UNIQUEIDENTIFIER,
@Identifier NVARCHAR(50),
@Name NVARCHAR(50),
@BusinessName NVARCHAR(50),
@BusinessAddress1 NVARCHAR(50),
@BusinessAddress2 NVARCHAR(50),
@BusinessAddress3 NVARCHAR(50),
@BusinessCountry VARCHAR(2),
@BusinessTaxNumber NVARCHAR(30),
@BillingEmail NVARCHAR(256),
@Plan NVARCHAR(50),
@PlanType TINYINT,
@Seats INT,
@MaxCollections SMALLINT,
@UsePolicies BIT,
@UseSso BIT,
@UseGroups BIT,
@UseDirectory BIT,
@UseEvents BIT,
@UseTotp BIT,
@Use2fa BIT,
@UseApi BIT,
@UseResetPassword BIT,
@SelfHost BIT,
@UsersGetPremium BIT,
@Storage BIGINT,
@MaxStorageGb SMALLINT,
@Gateway TINYINT,
@GatewayCustomerId VARCHAR(50),
@GatewaySubscriptionId VARCHAR(50),
@ReferenceData VARCHAR(MAX),
@Enabled BIT,
@LicenseKey VARCHAR(100),
@PublicKey VARCHAR(MAX),
@PrivateKey VARCHAR(MAX),
@TwoFactorProviders NVARCHAR(MAX),
@ExpirationDate DATETIME2(7),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@OwnersNotifiedOfAutoscaling DATETIME2(7),
@MaxAutoscaleSeats INT,
@UseKeyConnector BIT = 0,
@UseScim BIT = 0,
@UseCustomPermissions BIT = 0
AS
BEGIN
SET NOCOUNT ON
UPDATE
[dbo].[Organization]
SET
[Identifier] = @Identifier,
[Name] = @Name,
[BusinessName] = @BusinessName,
[BusinessAddress1] = @BusinessAddress1,
[BusinessAddress2] = @BusinessAddress2,
[BusinessAddress3] = @BusinessAddress3,
[BusinessCountry] = @BusinessCountry,
[BusinessTaxNumber] = @BusinessTaxNumber,
[BillingEmail] = @BillingEmail,
[Plan] = @Plan,
[PlanType] = @PlanType,
[Seats] = @Seats,
[MaxCollections] = @MaxCollections,
[UsePolicies] = @UsePolicies,
[UseSso] = @UseSso,
[UseGroups] = @UseGroups,
[UseDirectory] = @UseDirectory,
[UseEvents] = @UseEvents,
[UseTotp] = @UseTotp,
[Use2fa] = @Use2fa,
[UseApi] = @UseApi,
[UseResetPassword] = @UseResetPassword,
[SelfHost] = @SelfHost,
[UsersGetPremium] = @UsersGetPremium,
[Storage] = @Storage,
[MaxStorageGb] = @MaxStorageGb,
[Gateway] = @Gateway,
[GatewayCustomerId] = @GatewayCustomerId,
[GatewaySubscriptionId] = @GatewaySubscriptionId,
[ReferenceData] = @ReferenceData,
[Enabled] = @Enabled,
[LicenseKey] = @LicenseKey,
[PublicKey] = @PublicKey,
[PrivateKey] = @PrivateKey,
[TwoFactorProviders] = @TwoFactorProviders,
[ExpirationDate] = @ExpirationDate,
[CreationDate] = @CreationDate,
[RevisionDate] = @RevisionDate,
[OwnersNotifiedOfAutoscaling] = @OwnersNotifiedOfAutoscaling,
[MaxAutoscaleSeats] = @MaxAutoscaleSeats,
[UseKeyConnector] = @UseKeyConnector,
[UseScim] = @UseScim,
[UseCustomPermissions] = @UseCustomPermissions
WHERE
[Id] = @Id
END
GO
CREATE OR ALTER PROCEDURE [dbo].[Organization_ReadAbilities]
AS
BEGIN
SET NOCOUNT ON
SELECT
[Id],
[UseEvents],
[Use2fa],
CASE
WHEN [Use2fa] = 1 AND [TwoFactorProviders] IS NOT NULL AND [TwoFactorProviders] != '{}' THEN
1
ELSE
0
END AS [Using2fa],
[UsersGetPremium],
[UseCustomPermissions],
[UseSso],
[UseKeyConnector],
[UseScim],
[UseResetPassword],
[Enabled]
FROM
[dbo].[Organization]
END
GO
-- Enable Existing Enterprise Customers to use Custom Permissions
UPDATE [dbo].[Organization]
SET [UseCustomPermissions] = 1
WHERE [PlanType] IN (4, 5, 10, 11) -- Enterprise Annual/Monthly (2019 and 2020)
AND [UseCustomPermissions] = 0;
GO
-- Update non Enterprise Customers using Custom Permissions role to a Manager role
UPDATE [OU]
SET [OU].[Type] = 3, [OU].Permissions = NULL
FROM [dbo].[OrganizationUser] as OU
LEFT JOIN
[dbo].[Organization] O ON O.[Id] = OU.[OrganizationId]
WHERE O.[PlanType] NOT IN (4, 5, 10, 11) AND OU.[Type] = 4
GO

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,25 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bit.MySqlMigrations.Migrations;
public partial class UseCustomPermissionsFlag : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "UseCustomPermissions",
table: "Organization",
type: "tinyint(1)",
nullable: false,
defaultValue: false);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "UseCustomPermissions",
table: "Organization");
}
}

View File

@ -622,6 +622,9 @@ namespace Bit.MySqlMigrations.Migrations
b.Property<bool>("UseApi")
.HasColumnType("tinyint(1)");
b.Property<bool>("UseCustomPermissions")
.HasColumnType("tinyint(1)");
b.Property<bool>("UseDirectory")
.HasColumnType("tinyint(1)");

View File

@ -0,0 +1,8 @@
START TRANSACTION;
ALTER TABLE `Organization` ADD `UseCustomPermissions` tinyint(1) NOT NULL DEFAULT FALSE;
INSERT INTO `__EFMigrationsHistory` (`MigrationId`, `ProductVersion`)
VALUES ('20221020154432_UseCustomPermissionsFlag', '6.0.4');
COMMIT;

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,25 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bit.PostgresMigrations.Migrations;
public partial class UseCustomPermissionsFlag : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "UseCustomPermissions",
table: "Organization",
type: "boolean",
nullable: false,
defaultValue: false);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "UseCustomPermissions",
table: "Organization");
}
}

View File

@ -190,7 +190,7 @@ namespace Bit.PostgresMigrations.Migrations
b.HasIndex("GroupId");
b.ToTable("CollectionGroups");
b.ToTable("CollectionGroups", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionUser", b =>
@ -216,7 +216,7 @@ namespace Bit.PostgresMigrations.Migrations
b.HasIndex("UserId");
b.ToTable("CollectionUsers");
b.ToTable("CollectionUsers", (string)null);
});
modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Device", b =>
@ -624,6 +624,9 @@ namespace Bit.PostgresMigrations.Migrations
b.Property<bool>("UseApi")
.HasColumnType("boolean");
b.Property<bool>("UseCustomPermissions")
.HasColumnType("boolean");
b.Property<bool>("UseDirectory")
.HasColumnType("boolean");

View File

@ -0,0 +1,8 @@
START TRANSACTION;
ALTER TABLE "Organization" ADD "UseCustomPermissions" boolean NOT NULL DEFAULT FALSE;
INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
VALUES ('20221116102326_UseCustomPermissionsFlag', '6.0.4');
COMMIT;