using System.Security.Claims; using Bit.Api.AdminConsole.Controllers; using Bit.Api.AdminConsole.Models.Request; using Bit.Api.Models.Request; using Bit.Api.Vault.AuthorizationHandlers.Collections; using Bit.Core; using Bit.Core.AdminConsole.Entities; using Bit.Core.AdminConsole.OrganizationFeatures.Groups.Interfaces; using Bit.Core.AdminConsole.Repositories; using Bit.Core.Context; using Bit.Core.Entities; using Bit.Core.Exceptions; using Bit.Core.Models.Data; using Bit.Core.Models.Data.Organizations; using Bit.Core.Repositories; using Bit.Core.Services; using Bit.Core.Utilities; using Bit.Test.Common.AutoFixture; using Bit.Test.Common.AutoFixture.Attributes; using Microsoft.AspNetCore.Authorization; using NSubstitute; using Xunit; namespace Bit.Api.Test.AdminConsole.Controllers; [ControllerCustomize(typeof(GroupsController))] [SutProviderCustomize] public class GroupsControllerTests { [Theory] [BitAutoData] public async Task Post_PreFCv1_Success(Organization organization, GroupRequestModel groupRequestModel, SutProvider sutProvider) { sutProvider.GetDependency().GetByIdAsync(organization.Id).Returns(organization); sutProvider.GetDependency().ManageGroups(organization.Id).Returns(true); var response = await sutProvider.Sut.Post(organization.Id, groupRequestModel); await sutProvider.GetDependency().Received(1).ManageGroups(organization.Id); await sutProvider.GetDependency().Received(1).CreateGroupAsync( Arg.Is(g => g.OrganizationId == organization.Id && g.Name == groupRequestModel.Name && g.AccessAll == groupRequestModel.AccessAll), organization, Arg.Any>(), Arg.Any>()); Assert.Equal(groupRequestModel.Name, response.Name); Assert.Equal(organization.Id, response.OrganizationId); Assert.Equal(groupRequestModel.AccessAll, response.AccessAll); } [Theory] [BitAutoData] public async Task Post_AuthorizedToGiveAccessToCollections_Success(Organization organization, GroupRequestModel groupRequestModel, SutProvider sutProvider) { // Enable FC and v1 sutProvider.GetDependency().GetOrganizationAbilityAsync(organization.Id).Returns( new OrganizationAbility { Id = organization.Id, FlexibleCollections = true, AllowAdminAccessToAllCollectionItems = false }); sutProvider.GetDependency().IsEnabled(FeatureFlagKeys.FlexibleCollectionsV1).Returns(true); sutProvider.GetDependency() .AuthorizeAsync(Arg.Any(), Arg.Any>(), Arg.Is>(reqs => reqs.Contains(BulkCollectionOperations.ModifyGroupAccess))) .Returns(AuthorizationResult.Success()); sutProvider.GetDependency().GetByIdAsync(organization.Id).Returns(organization); sutProvider.GetDependency().ManageGroups(organization.Id).Returns(true); var response = await sutProvider.Sut.Post(organization.Id, groupRequestModel); var requestModelCollectionIds = groupRequestModel.Collections.Select(c => c.Id).ToHashSet(); // Assert that it checked permissions await sutProvider.GetDependency().Received(1).ManageGroups(organization.Id); await sutProvider.GetDependency() .Received(1) .AuthorizeAsync(Arg.Any(), Arg.Is>(collections => collections.All(c => requestModelCollectionIds.Contains(c.Id))), Arg.Is>(reqs => reqs.Single() == BulkCollectionOperations.ModifyGroupAccess)); // Assert that it saved the data await sutProvider.GetDependency().Received(1).CreateGroupAsync( Arg.Is(g => g.OrganizationId == organization.Id && g.Name == groupRequestModel.Name && g.AccessAll == groupRequestModel.AccessAll), organization, Arg.Is>(access => access.All(c => requestModelCollectionIds.Contains(c.Id))), Arg.Any>()); Assert.Equal(groupRequestModel.Name, response.Name); Assert.Equal(organization.Id, response.OrganizationId); Assert.Equal(groupRequestModel.AccessAll, response.AccessAll); } [Theory] [BitAutoData] public async Task Post_NotAuthorizedToGiveAccessToCollections_Throws(Organization organization, GroupRequestModel groupRequestModel, SutProvider sutProvider) { // Enable FC and v1 sutProvider.GetDependency().GetOrganizationAbilityAsync(organization.Id).Returns( new OrganizationAbility { Id = organization.Id, FlexibleCollections = true, AllowAdminAccessToAllCollectionItems = false }); sutProvider.GetDependency().IsEnabled(FeatureFlagKeys.FlexibleCollectionsV1).Returns(true); sutProvider.GetDependency().GetByIdAsync(organization.Id).Returns(organization); sutProvider.GetDependency().ManageGroups(organization.Id).Returns(true); var requestModelCollectionIds = groupRequestModel.Collections.Select(c => c.Id).ToHashSet(); sutProvider.GetDependency() .AuthorizeAsync(Arg.Any(), Arg.Is>(collections => collections.All(c => requestModelCollectionIds.Contains(c.Id))), Arg.Is>(reqs => reqs.Contains(BulkCollectionOperations.ModifyGroupAccess))) .Returns(AuthorizationResult.Failed()); var exception = await Assert.ThrowsAsync(() => sutProvider.Sut.Post(organization.Id, groupRequestModel)); Assert.Contains("You are not authorized to grant access to these collections.", exception.Message); await sutProvider.GetDependency().DidNotReceiveWithAnyArgs() .CreateGroupAsync(default, default, default, default); } [Theory] [BitAutoData] public async Task Put_AdminsCanAccessAllCollections_Success(Organization organization, Group group, GroupRequestModel groupRequestModel, List existingCollectionAccess, SutProvider sutProvider) { group.OrganizationId = organization.Id; // Enable FC and v1, set Collection Management Setting sutProvider.GetDependency().GetOrganizationAbilityAsync(organization.Id).Returns( new OrganizationAbility { Id = organization.Id, AllowAdminAccessToAllCollectionItems = true, FlexibleCollections = true }); sutProvider.GetDependency().IsEnabled(FeatureFlagKeys.FlexibleCollectionsV1).Returns(true); sutProvider.GetDependency().GetByIdAsync(organization.Id).Returns(organization); sutProvider.GetDependency().GetByIdWithCollectionsAsync(group.Id) .Returns(new Tuple>(group, existingCollectionAccess)); sutProvider.GetDependency() .GetManyByManyIdsAsync(existingCollectionAccess.Select(c => c.Id)) .Returns(existingCollectionAccess.Select(c => new Collection { Id = c.Id }).ToList()); sutProvider.GetDependency().ManageGroups(organization.Id).Returns(true); var requestModelCollectionIds = groupRequestModel.Collections.Select(c => c.Id).ToHashSet(); var response = await sutProvider.Sut.Put(organization.Id, group.Id, groupRequestModel); await sutProvider.GetDependency().Received(1).ManageGroups(organization.Id); await sutProvider.GetDependency().Received(1).UpdateGroupAsync( Arg.Is(g => g.OrganizationId == organization.Id && g.Name == groupRequestModel.Name && g.AccessAll == groupRequestModel.AccessAll), Arg.Is(o => o.Id == organization.Id), // Should overwrite any existing collections Arg.Is>(access => access.All(c => requestModelCollectionIds.Contains(c.Id))), Arg.Any>()); Assert.Equal(groupRequestModel.Name, response.Name); Assert.Equal(organization.Id, response.OrganizationId); Assert.Equal(groupRequestModel.AccessAll, response.AccessAll); } [Theory] [BitAutoData] public async Task Put_UpdateMembers_AdminsCannotAccessAllCollections_CannotAddSelfToGroup(Organization organization, Group group, GroupRequestModel groupRequestModel, OrganizationUser savingOrganizationUser, List currentGroupUsers, SutProvider sutProvider) { group.OrganizationId = organization.Id; // Enable FC and v1 sutProvider.GetDependency().GetOrganizationAbilityAsync(organization.Id).Returns( new OrganizationAbility { Id = organization.Id, AllowAdminAccessToAllCollectionItems = false, FlexibleCollections = true }); sutProvider.GetDependency().IsEnabled(FeatureFlagKeys.FlexibleCollectionsV1).Returns(true); // Saving user is trying to add themselves to the group var updatedUsers = groupRequestModel.Users.ToList(); updatedUsers.Add(savingOrganizationUser.Id); groupRequestModel.Users = updatedUsers; sutProvider.GetDependency().GetByIdAsync(organization.Id).Returns(organization); sutProvider.GetDependency().GetByIdWithCollectionsAsync(group.Id) .Returns(new Tuple>(group, new List())); sutProvider.GetDependency().ManageGroups(organization.Id).Returns(true); sutProvider.GetDependency() .GetByOrganizationAsync(organization.Id, Arg.Any()) .Returns(savingOrganizationUser); sutProvider.GetDependency().GetProperUserId(Arg.Any()) .Returns(savingOrganizationUser.UserId); sutProvider.GetDependency().GetManyUserIdsByIdAsync(group.Id) .Returns(currentGroupUsers); var exception = await Assert.ThrowsAsync(() => sutProvider.Sut.Put(organization.Id, group.Id, groupRequestModel)); Assert.Contains("You cannot add yourself to groups", exception.Message); } [Theory] [BitAutoData] public async Task Put_UpdateMembers_AdminsCannotAccessAllCollections_AlreadyInGroup_Success(Organization organization, Group group, GroupRequestModel groupRequestModel, OrganizationUser savingOrganizationUser, List currentGroupUsers, SutProvider sutProvider) { group.OrganizationId = organization.Id; // Enable FC and v1 sutProvider.GetDependency().GetOrganizationAbilityAsync(organization.Id).Returns( new OrganizationAbility { Id = organization.Id, AllowAdminAccessToAllCollectionItems = false, FlexibleCollections = true }); sutProvider.GetDependency().IsEnabled(FeatureFlagKeys.FlexibleCollectionsV1).Returns(true); // Saving user is trying to add themselves to the group var updatedUsers = groupRequestModel.Users.ToList(); updatedUsers.Add(savingOrganizationUser.Id); groupRequestModel.Users = updatedUsers; // But! they are already a member of the group currentGroupUsers.Add(savingOrganizationUser.Id); sutProvider.GetDependency().GetByIdAsync(organization.Id).Returns(organization); sutProvider.GetDependency().GetByIdWithCollectionsAsync(group.Id) .Returns(new Tuple>(group, new List())); sutProvider.GetDependency().ManageGroups(organization.Id).Returns(true); sutProvider.GetDependency() .GetByOrganizationAsync(organization.Id, Arg.Any()) .Returns(savingOrganizationUser); sutProvider.GetDependency().GetProperUserId(Arg.Any()) .Returns(savingOrganizationUser.UserId); sutProvider.GetDependency().GetManyUserIdsByIdAsync(group.Id) .Returns(currentGroupUsers); // Make collection authorization pass, it's not being tested here groupRequestModel.Collections = Array.Empty(); var response = await sutProvider.Sut.Put(organization.Id, group.Id, groupRequestModel); await sutProvider.GetDependency().Received(1).ManageGroups(organization.Id); await sutProvider.GetDependency().Received(1).UpdateGroupAsync( Arg.Is(g => g.OrganizationId == organization.Id && g.Name == groupRequestModel.Name && g.AccessAll == groupRequestModel.AccessAll), Arg.Is(o => o.Id == organization.Id), Arg.Any>(), Arg.Any>()); Assert.Equal(groupRequestModel.Name, response.Name); Assert.Equal(organization.Id, response.OrganizationId); Assert.Equal(groupRequestModel.AccessAll, response.AccessAll); } [Theory] [BitAutoData] public async Task Put_UpdateMembers_AdminsCannotAccessAllCollections_ProviderUser_Success(Organization organization, Group group, GroupRequestModel groupRequestModel, List currentGroupUsers, Guid savingUserId, SutProvider sutProvider) { group.OrganizationId = organization.Id; // Enable FC and v1 sutProvider.GetDependency().GetOrganizationAbilityAsync(organization.Id).Returns( new OrganizationAbility { Id = organization.Id, AllowAdminAccessToAllCollectionItems = false, FlexibleCollections = true }); sutProvider.GetDependency().IsEnabled(FeatureFlagKeys.FlexibleCollectionsV1).Returns(true); sutProvider.GetDependency().GetByIdAsync(organization.Id).Returns(organization); sutProvider.GetDependency().GetByIdWithCollectionsAsync(group.Id) .Returns(new Tuple>(group, new List())); sutProvider.GetDependency().ManageGroups(organization.Id).Returns(true); sutProvider.GetDependency() .GetByOrganizationAsync(organization.Id, Arg.Any()) .Returns((OrganizationUser)null); // Provider is not an OrganizationUser, so it will always return null sutProvider.GetDependency().GetProperUserId(Arg.Any()) .Returns(savingUserId); sutProvider.GetDependency().GetManyUserIdsByIdAsync(group.Id) .Returns(currentGroupUsers); // Make collection authorization pass, it's not being tested here groupRequestModel.Collections = Array.Empty(); var response = await sutProvider.Sut.Put(organization.Id, group.Id, groupRequestModel); await sutProvider.GetDependency().Received(1).ManageGroups(organization.Id); await sutProvider.GetDependency().Received(1).UpdateGroupAsync( Arg.Is(g => g.OrganizationId == organization.Id && g.Name == groupRequestModel.Name && g.AccessAll == groupRequestModel.AccessAll), Arg.Is(o => o.Id == organization.Id), Arg.Any>(), Arg.Any>()); Assert.Equal(groupRequestModel.Name, response.Name); Assert.Equal(organization.Id, response.OrganizationId); Assert.Equal(groupRequestModel.AccessAll, response.AccessAll); } [Theory] [BitAutoData] public async Task Put_UpdateCollections_OnlyUpdatesCollectionsTheSavingUserCanUpdate(GroupRequestModel groupRequestModel, Group group, Organization organization, SutProvider sutProvider, Guid savingUserId) { organization.FlexibleCollections = true; sutProvider.GetDependency().IsEnabled(FeatureFlagKeys.FlexibleCollectionsV1).Returns(true); Put_Setup(sutProvider, organization, group, savingUserId); var editedCollectionId = CoreHelpers.GenerateComb(); var readonlyCollectionId1 = CoreHelpers.GenerateComb(); var readonlyCollectionId2 = CoreHelpers.GenerateComb(); var currentCollectionAccess = new List { new() { Id = editedCollectionId, HidePasswords = true, Manage = false, ReadOnly = true }, new() { Id = readonlyCollectionId1, HidePasswords = false, Manage = true, ReadOnly = false }, new() { Id = readonlyCollectionId2, HidePasswords = false, Manage = false, ReadOnly = false }, }; // User is upgrading editedCollectionId to manage groupRequestModel.Collections = new List { new() { Id = editedCollectionId, HidePasswords = false, Manage = true, ReadOnly = false } }; sutProvider.GetDependency() .GetByIdWithCollectionsAsync(group.Id) .Returns(new Tuple>(group, currentCollectionAccess)); var currentCollections = currentCollectionAccess .Select(cas => new Collection { Id = cas.Id }).ToList(); sutProvider.GetDependency() .GetManyByManyIdsAsync(Arg.Any>()) .Returns(currentCollections); // Authorize the editedCollection sutProvider.GetDependency() .AuthorizeAsync(Arg.Any(), Arg.Is(c => c.Id == editedCollectionId), Arg.Is>(reqs => reqs.Contains(BulkCollectionOperations.ModifyGroupAccess))) .Returns(AuthorizationResult.Success()); // Do not authorize the readonly collections sutProvider.GetDependency() .AuthorizeAsync(Arg.Any(), Arg.Is(c => c.Id == readonlyCollectionId1 || c.Id == readonlyCollectionId2), Arg.Is>(reqs => reqs.Contains(BulkCollectionOperations.ModifyGroupAccess))) .Returns(AuthorizationResult.Failed()); var response = await sutProvider.Sut.Put(organization.Id, group.Id, groupRequestModel); // Expect all collection access (modified and unmodified) to be saved await sutProvider.GetDependency().Received(1).ManageGroups(organization.Id); await sutProvider.GetDependency().Received(1).UpdateGroupAsync( Arg.Is(g => g.OrganizationId == organization.Id && g.Name == groupRequestModel.Name && g.AccessAll == groupRequestModel.AccessAll), Arg.Is(o => o.Id == organization.Id), Arg.Is>(cas => cas.Select(c => c.Id).SequenceEqual(currentCollectionAccess.Select(c => c.Id)) && cas.First(c => c.Id == editedCollectionId).Manage == true && cas.First(c => c.Id == editedCollectionId).ReadOnly == false && cas.First(c => c.Id == editedCollectionId).HidePasswords == false), Arg.Any>()); Assert.Equal(groupRequestModel.Name, response.Name); Assert.Equal(organization.Id, response.OrganizationId); Assert.Equal(groupRequestModel.AccessAll, response.AccessAll); } [Theory] [BitAutoData] public async Task Put_UpdateCollections_ThrowsIfSavingUserCannotUpdateCollections(GroupRequestModel groupRequestModel, Group group, Organization organization, SutProvider sutProvider, Guid savingUserId) { organization.FlexibleCollections = true; sutProvider.GetDependency().IsEnabled(FeatureFlagKeys.FlexibleCollectionsV1).Returns(true); Put_Setup(sutProvider, organization, group, savingUserId); sutProvider.GetDependency() .GetByIdWithCollectionsAsync(group.Id) .Returns(new Tuple>(group, groupRequestModel.Collections.Select(cas => cas.ToSelectionReadOnly()).ToList())); var collections = groupRequestModel.Collections.Select(cas => new Collection { Id = cas.Id }).ToList(); sutProvider.GetDependency() .GetManyByManyIdsAsync(Arg.Is>(guids => guids.SequenceEqual(collections.Select(c => c.Id)))) .Returns(collections); sutProvider.GetDependency() .AuthorizeAsync(Arg.Any(), Arg.Is(c => collections.Contains(c)), Arg.Is>(reqs => reqs.Contains(BulkCollectionOperations.ModifyGroupAccess))) .Returns(AuthorizationResult.Failed()); var exception = await Assert.ThrowsAsync(() => sutProvider.Sut.Put(organization.Id, group.Id, groupRequestModel)); Assert.Contains("You must have Can Manage permission", exception.Message); } private void Put_Setup(SutProvider sutProvider, Organization organization, Group group, Guid savingUserId) { var orgId = organization.Id = group.OrganizationId; sutProvider.GetDependency().ManageGroups(orgId).Returns(true); sutProvider.GetDependency().GetOrganizationAbilityAsync(orgId) .Returns(new OrganizationAbility { Id = organization.Id, FlexibleCollections = true, AllowAdminAccessToAllCollectionItems = false }); sutProvider.GetDependency().GetManyUserIdsByIdAsync(group.Id).Returns(new List()); sutProvider.GetDependency().GetProperUserId(Arg.Any()).Returns(savingUserId); sutProvider.GetDependency().GetByOrganizationAsync(orgId, savingUserId).Returns(new OrganizationUser { Id = savingUserId }); sutProvider.GetDependency().GetByIdAsync(organization.Id).Returns(organization); } }