diff --git a/bitwarden_license/src/Commercial.Core/SecretsManager/Commands/AccessPolicies/CreateAccessPoliciesCommand.cs b/bitwarden_license/src/Commercial.Core/SecretsManager/Commands/AccessPolicies/CreateAccessPoliciesCommand.cs index ffc39099e4..ec9ce3f357 100644 --- a/bitwarden_license/src/Commercial.Core/SecretsManager/Commands/AccessPolicies/CreateAccessPoliciesCommand.cs +++ b/bitwarden_license/src/Commercial.Core/SecretsManager/Commands/AccessPolicies/CreateAccessPoliciesCommand.cs @@ -1,5 +1,4 @@ -using Bit.Core.Context; -using Bit.Core.Enums; +using Bit.Core.Enums; using Bit.Core.Exceptions; using Bit.Core.SecretsManager.Commands.AccessPolicies.Interfaces; using Bit.Core.SecretsManager.Entities; @@ -10,54 +9,33 @@ namespace Bit.Commercial.Core.SecretsManager.Commands.AccessPolicies; public class CreateAccessPoliciesCommand : ICreateAccessPoliciesCommand { private readonly IAccessPolicyRepository _accessPolicyRepository; - private readonly ICurrentContext _currentContext; private readonly IProjectRepository _projectRepository; private readonly IServiceAccountRepository _serviceAccountRepository; public CreateAccessPoliciesCommand( IAccessPolicyRepository accessPolicyRepository, - ICurrentContext currentContext, IProjectRepository projectRepository, IServiceAccountRepository serviceAccountRepository) { _accessPolicyRepository = accessPolicyRepository; - _currentContext = currentContext; _projectRepository = projectRepository; _serviceAccountRepository = serviceAccountRepository; } - public async Task> CreateForProjectAsync(Guid projectId, - List accessPolicies, Guid userId) + private static IEnumerable GetDistinctGrantedProjectIds(List accessPolicies) { - var project = await _projectRepository.GetByIdAsync(projectId); - if (project == null || !_currentContext.AccessSecretsManager(project.OrganizationId)) - { - throw new NotFoundException(); - } - - await CheckPermissionAsync(project.OrganizationId, userId, projectId); - CheckForDistinctAccessPolicies(accessPolicies); - await CheckAccessPoliciesDoNotExistAsync(accessPolicies); - - await _accessPolicyRepository.CreateManyAsync(accessPolicies); - return await _accessPolicyRepository.GetManyByGrantedProjectIdAsync(projectId); + var userGrantedIds = accessPolicies.OfType().Select(ap => ap.GrantedProjectId); + var groupGrantedIds = accessPolicies.OfType().Select(ap => ap.GrantedProjectId); + var saGrantedIds = accessPolicies.OfType().Select(ap => ap.GrantedProjectId); + return userGrantedIds.Concat(groupGrantedIds).Concat(saGrantedIds).Distinct(); } - public async Task> CreateForServiceAccountAsync(Guid serviceAccountId, - List accessPolicies, Guid userId) + private static IEnumerable GetDistinctGrantedServiceAccountIds(List accessPolicies) { - var serviceAccount = await _serviceAccountRepository.GetByIdAsync(serviceAccountId); - if (serviceAccount == null || !_currentContext.AccessSecretsManager(serviceAccount.OrganizationId)) - { - throw new NotFoundException(); - } - - await CheckPermissionAsync(serviceAccount.OrganizationId, userId, serviceAccountIdToCheck: serviceAccountId); - CheckForDistinctAccessPolicies(accessPolicies); - await CheckAccessPoliciesDoNotExistAsync(accessPolicies); - - await _accessPolicyRepository.CreateManyAsync(accessPolicies); - return await _accessPolicyRepository.GetManyByGrantedServiceAccountIdAsync(serviceAccountId); + var userGrantedIds = accessPolicies.OfType().Select(ap => ap.GrantedServiceAccountId); + var groupGrantedIds = accessPolicies.OfType() + .Select(ap => ap.GrantedServiceAccountId); + return userGrantedIds.Concat(groupGrantedIds).Distinct(); } private static void CheckForDistinctAccessPolicies(IReadOnlyCollection accessPolicies) @@ -83,6 +61,40 @@ public class CreateAccessPoliciesCommand : ICreateAccessPoliciesCommand } } + public async Task> CreateManyAsync(List accessPolicies, Guid userId, AccessClientType accessType) + { + CheckForDistinctAccessPolicies(accessPolicies); + await CheckAccessPoliciesDoNotExistAsync(accessPolicies); + await CheckCanCreateAsync(accessPolicies, userId, accessType); + return await _accessPolicyRepository.CreateManyAsync(accessPolicies); + } + + private async Task CheckCanCreateAsync(List accessPolicies, Guid userId, AccessClientType accessType) + { + var projectIds = GetDistinctGrantedProjectIds(accessPolicies).ToList(); + var serviceAccountIds = GetDistinctGrantedServiceAccountIds(accessPolicies).ToList(); + + if (projectIds.Any()) + { + foreach (var projectId in projectIds) + { + await CheckPermissionAsync(accessType, userId, projectId); + } + } + if (serviceAccountIds.Any()) + { + foreach (var serviceAccountId in serviceAccountIds) + { + await CheckPermissionAsync(accessType, userId, serviceAccountIdToCheck: serviceAccountId); + } + } + + if (!projectIds.Any() && !serviceAccountIds.Any()) + { + throw new BadRequestException("No granted IDs specified"); + } + } + private async Task CheckAccessPoliciesDoNotExistAsync(List accessPolicies) { foreach (var accessPolicy in accessPolicies) @@ -94,14 +106,9 @@ public class CreateAccessPoliciesCommand : ICreateAccessPoliciesCommand } } - private async Task CheckPermissionAsync(Guid organizationId, - Guid userId, - Guid? projectIdToCheck = null, + private async Task CheckPermissionAsync(AccessClientType accessClient, Guid userId, Guid? projectIdToCheck = null, Guid? serviceAccountIdToCheck = null) { - var orgAdmin = await _currentContext.OrganizationAdmin(organizationId); - var accessClient = AccessClientHelper.ToAccessClient(_currentContext.ClientType, orgAdmin); - bool hasAccess; switch (accessClient) { @@ -109,20 +116,21 @@ public class CreateAccessPoliciesCommand : ICreateAccessPoliciesCommand hasAccess = true; break; case AccessClientType.User: - if (projectIdToCheck != null) + if (projectIdToCheck.HasValue) { hasAccess = await _projectRepository.UserHasWriteAccessToProject(projectIdToCheck.Value, userId); } - else if (serviceAccountIdToCheck != null) + else if (serviceAccountIdToCheck.HasValue) { - hasAccess = await _serviceAccountRepository.UserHasWriteAccessToServiceAccount( - serviceAccountIdToCheck.Value, - userId); + hasAccess = + await _serviceAccountRepository.UserHasWriteAccessToServiceAccount( + serviceAccountIdToCheck.Value, userId); } else { - hasAccess = false; + throw new ArgumentException("No ID to check provided."); } + break; default: hasAccess = false; diff --git a/bitwarden_license/src/Commercial.Infrastructure.EntityFramework/SecretsManager/Repositories/AccessPolicyRepository.cs b/bitwarden_license/src/Commercial.Infrastructure.EntityFramework/SecretsManager/Repositories/AccessPolicyRepository.cs index 8e5015f8b5..b456309051 100644 --- a/bitwarden_license/src/Commercial.Infrastructure.EntityFramework/SecretsManager/Repositories/AccessPolicyRepository.cs +++ b/bitwarden_license/src/Commercial.Infrastructure.EntityFramework/SecretsManager/Repositories/AccessPolicyRepository.cs @@ -1,10 +1,13 @@ -using AutoMapper; +using System.Linq.Expressions; +using AutoMapper; +using Bit.Core.Enums; using Bit.Core.SecretsManager.Repositories; using Bit.Infrastructure.EntityFramework.Repositories; using Bit.Infrastructure.EntityFramework.SecretsManager.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; + namespace Bit.Commercial.Infrastructure.EntityFramework.SecretsManager.Repositories; public class AccessPolicyRepository : BaseEntityFrameworkRepository, IAccessPolicyRepository @@ -14,6 +17,12 @@ public class AccessPolicyRepository : BaseEntityFrameworkRepository, IAccessPoli { } + private static Expression> UserHasWriteAccessToProject(Guid userId) => + policy => + policy.GrantedProject.UserAccessPolicies.Any(ap => ap.OrganizationUser.User.Id == userId && ap.Write) || + policy.GrantedProject.GroupAccessPolicies.Any(ap => + ap.Group.GroupUsers.Any(gu => gu.OrganizationUser.User.Id == userId && ap.Write)); + public async Task> CreateManyAsync(List baseAccessPolicies) { using var scope = ServiceScopeFactory.CreateScope(); @@ -191,16 +200,41 @@ public class AccessPolicyRepository : BaseEntityFrameworkRepository, IAccessPoli } } - private Core.SecretsManager.Entities.BaseAccessPolicy MapToCore(BaseAccessPolicy baseAccessPolicyEntity) + public async Task> GetManyByServiceAccountIdAsync(Guid id, Guid userId, + AccessClientType accessType) { - return baseAccessPolicyEntity switch + using var scope = ServiceScopeFactory.CreateScope(); + var dbContext = GetDatabaseContext(scope); + var query = dbContext.ServiceAccountProjectAccessPolicy.Where(ap => + ap.ServiceAccountId == id); + + query = accessType switch + { + AccessClientType.NoAccessCheck => query, + AccessClientType.User => query.Where(UserHasWriteAccessToProject(userId)), + _ => throw new ArgumentOutOfRangeException(nameof(accessType), accessType, null), + }; + + var entities = await query + .Include(ap => ap.ServiceAccount) + .Include(ap => ap.GrantedProject) + .ToListAsync(); + + return entities.Select(MapToCore); + } + + private Core.SecretsManager.Entities.BaseAccessPolicy MapToCore( + BaseAccessPolicy baseAccessPolicyEntity) => + baseAccessPolicyEntity switch { UserProjectAccessPolicy ap => Mapper.Map(ap), GroupProjectAccessPolicy ap => Mapper.Map(ap), - ServiceAccountProjectAccessPolicy ap => Mapper.Map(ap), - UserServiceAccountAccessPolicy ap => Mapper.Map(ap), - GroupServiceAccountAccessPolicy ap => Mapper.Map(ap), - _ => throw new ArgumentException("Unsupported access policy type") + ServiceAccountProjectAccessPolicy ap => Mapper + .Map(ap), + UserServiceAccountAccessPolicy ap => + Mapper.Map(ap), + GroupServiceAccountAccessPolicy ap => Mapper + .Map(ap), + _ => throw new ArgumentException("Unsupported access policy type"), }; - } } diff --git a/bitwarden_license/src/Commercial.Infrastructure.EntityFramework/SecretsManager/Repositories/ProjectRepository.cs b/bitwarden_license/src/Commercial.Infrastructure.EntityFramework/SecretsManager/Repositories/ProjectRepository.cs index fac888e18e..20d80d42f6 100644 --- a/bitwarden_license/src/Commercial.Infrastructure.EntityFramework/SecretsManager/Repositories/ProjectRepository.cs +++ b/bitwarden_license/src/Commercial.Infrastructure.EntityFramework/SecretsManager/Repositories/ProjectRepository.cs @@ -45,6 +45,24 @@ public class ProjectRepository : Repository>(projects); } + public async Task> GetManyByOrganizationIdWriteAccessAsync( + Guid organizationId, Guid userId, AccessClientType accessType) + { + using var scope = ServiceScopeFactory.CreateScope(); + var dbContext = GetDatabaseContext(scope); + var query = dbContext.Project.Where(p => p.OrganizationId == organizationId && p.DeletedDate == null); + + query = accessType switch + { + AccessClientType.NoAccessCheck => query, + AccessClientType.User => query.Where(UserHasWriteAccessToProject(userId)), + _ => throw new ArgumentOutOfRangeException(nameof(accessType), accessType, null), + }; + + var projects = await query.OrderBy(p => p.RevisionDate).ToListAsync(); + return Mapper.Map>(projects); + } + private static Expression> UserHasReadAccessToProject(Guid userId) => p => p.UserAccessPolicies.Any(ap => ap.OrganizationUser.User.Id == userId && ap.Read) || p.GroupAccessPolicies.Any(ap => ap.Group.GroupUsers.Any(gu => gu.OrganizationUser.User.Id == userId && ap.Read)); diff --git a/bitwarden_license/test/Commercial.Core.Test/SecretsManager/AccessPolicies/CreateAccessPoliciesCommandTests.cs b/bitwarden_license/test/Commercial.Core.Test/SecretsManager/AccessPolicies/CreateAccessPoliciesCommandTests.cs index d1c1a29145..2c61e5ec80 100644 --- a/bitwarden_license/test/Commercial.Core.Test/SecretsManager/AccessPolicies/CreateAccessPoliciesCommandTests.cs +++ b/bitwarden_license/test/Commercial.Core.Test/SecretsManager/AccessPolicies/CreateAccessPoliciesCommandTests.cs @@ -1,6 +1,6 @@ using Bit.Commercial.Core.SecretsManager.Commands.AccessPolicies; using Bit.Commercial.Core.Test.SecretsManager.Enums; -using Bit.Core.Context; +using Bit.Core.Enums; using Bit.Core.Exceptions; using Bit.Core.SecretsManager.Entities; using Bit.Core.SecretsManager.Repositories; @@ -17,6 +17,46 @@ namespace Bit.Commercial.Core.Test.SecretsManager.AccessPolicies; [ProjectCustomize] public class CreateAccessPoliciesCommandTests { + private static List MakeGrantedProjectAccessPolicies(Guid grantedProjectId, List userProjectAccessPolicies, + List groupProjectAccessPolicies, + List serviceAccountProjectAccessPolicies) + { + var data = new List(); + foreach (var ap in userProjectAccessPolicies) + { + ap.GrantedProjectId = grantedProjectId; + } + foreach (var ap in groupProjectAccessPolicies) + { + ap.GrantedProjectId = grantedProjectId; + } + foreach (var ap in serviceAccountProjectAccessPolicies) + { + ap.GrantedProjectId = grantedProjectId; + } + data.AddRange(userProjectAccessPolicies); + data.AddRange(groupProjectAccessPolicies); + data.AddRange(serviceAccountProjectAccessPolicies); + return data; + } + + private static List MakeGrantedServiceAccountAccessPolicies(Guid grantedServiceAccountId, List userServiceAccountAccessPolicies, + List groupServiceAccountAccessPolicies) + { + var data = new List(); + foreach (var ap in userServiceAccountAccessPolicies) + { + ap.GrantedServiceAccountId = grantedServiceAccountId; + } + foreach (var ap in groupServiceAccountAccessPolicies) + { + ap.GrantedServiceAccountId = grantedServiceAccountId; + } + data.AddRange(userServiceAccountAccessPolicies); + data.AddRange(groupServiceAccountAccessPolicies); + return data; + } + private static List MakeDuplicate(List data, AccessPolicyType accessPolicyType) { switch (accessPolicyType) @@ -91,97 +131,51 @@ public class CreateAccessPoliciesCommandTests return data; } - private static void SetupAdmin(SutProvider sutProvider, Guid organizationId) - { - sutProvider.GetDependency().AccessSecretsManager(organizationId).Returns(true); - sutProvider.GetDependency().OrganizationAdmin(organizationId).Returns(true); - } - - private static void SetupUser(SutProvider sutProvider, Guid organizationId) - { - sutProvider.GetDependency().AccessSecretsManager(organizationId).Returns(true); - sutProvider.GetDependency().OrganizationAdmin(organizationId).Returns(false); - } - private static void SetupPermission(SutProvider sutProvider, PermissionType permissionType, Project project, Guid userId) { - switch (permissionType) + if (permissionType == PermissionType.RunAsUserWithPermission) { - case PermissionType.RunAsAdmin: - SetupAdmin(sutProvider, project.OrganizationId); - break; - case PermissionType.RunAsUserWithPermission: - SetupUser(sutProvider, project.OrganizationId); - sutProvider.GetDependency().UserHasWriteAccessToProject(project.Id, userId) - .Returns(true); - break; + sutProvider.GetDependency().UserHasWriteAccessToProject(project.Id, userId) + .Returns(true); } } private static void SetupPermission(SutProvider sutProvider, PermissionType permissionType, ServiceAccount serviceAccount, Guid userId) { - switch (permissionType) + if (permissionType == PermissionType.RunAsUserWithPermission) { - case PermissionType.RunAsAdmin: - SetupAdmin(sutProvider, serviceAccount.OrganizationId); - break; - case PermissionType.RunAsUserWithPermission: - SetupUser(sutProvider, serviceAccount.OrganizationId); - sutProvider.GetDependency() - .UserHasWriteAccessToServiceAccount(serviceAccount.Id, userId).Returns(true); - break; + sutProvider.GetDependency() + .UserHasWriteAccessToServiceAccount(serviceAccount.Id, userId).Returns(true); } } [Theory] [BitAutoData] - public async Task CreateForProject_SmNotEnabled_Throws( + public async Task CreateMany_AlreadyExists_Throws_BadRequestException( Guid userId, Project project, + ServiceAccount serviceAccount, List userProjectAccessPolicies, List groupProjectAccessPolicies, List serviceAccountProjectAccessPolicies, + List userServiceAccountAccessPolicies, + List groupServiceAccountAccessPolicies, SutProvider sutProvider) { - var data = new List(); - data.AddRange(userProjectAccessPolicies); - data.AddRange(groupProjectAccessPolicies); - data.AddRange(serviceAccountProjectAccessPolicies); + var data = MakeGrantedProjectAccessPolicies(project.Id, userProjectAccessPolicies, groupProjectAccessPolicies, + serviceAccountProjectAccessPolicies); + var saData = MakeGrantedServiceAccountAccessPolicies(serviceAccount.Id, userServiceAccountAccessPolicies, groupServiceAccountAccessPolicies); + data = data.Concat(saData).ToList(); - sutProvider.GetDependency().AccessSecretsManager(Arg.Any()).Returns(false); - - await Assert.ThrowsAsync(() => - sutProvider.Sut.CreateForProjectAsync(project.Id, data, userId)); - - await sutProvider.GetDependency().DidNotReceiveWithAnyArgs().CreateManyAsync(default); - } - - [Theory] - [BitAutoData] - public async Task CreateForProject_AlreadyExists_Throws_BadRequestException( - Guid userId, - Project project, - List userProjectAccessPolicies, - List groupProjectAccessPolicies, - List serviceAccountProjectAccessPolicies, - SutProvider sutProvider) - { - var data = new List(); - data.AddRange(userProjectAccessPolicies); - data.AddRange(groupProjectAccessPolicies); - data.AddRange(serviceAccountProjectAccessPolicies); - - SetupAdmin(sutProvider, project.OrganizationId); - sutProvider.GetDependency().GetByIdAsync(project.Id).Returns(project); sutProvider.GetDependency().AccessPolicyExists(Arg.Any()) .Returns(true); await Assert.ThrowsAsync(() => - sutProvider.Sut.CreateForProjectAsync(project.Id, data, userId)); + sutProvider.Sut.CreateManyAsync(data, userId, AccessClientType.NoAccessCheck)); - await sutProvider.GetDependency().DidNotReceiveWithAnyArgs().CreateManyAsync(default); + await sutProvider.GetDependency().DidNotReceiveWithAnyArgs().CreateManyAsync(default!); } [Theory] @@ -190,29 +184,27 @@ public class CreateAccessPoliciesCommandTests [BitAutoData(AccessPolicyType.ServiceAccountProjectAccessPolicy)] [BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy)] [BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy)] - public async Task CreateForProjectAsync_NotUnique_ThrowsException( + public async Task CreateMany_NotUnique_ThrowsException( AccessPolicyType accessPolicyType, Guid userId, Project project, + ServiceAccount serviceAccount, List userProjectAccessPolicies, List groupProjectAccessPolicies, List serviceAccountProjectAccessPolicies, + List userServiceAccountAccessPolicies, + List groupServiceAccountAccessPolicies, SutProvider sutProvider ) { - var data = new List(); - data.AddRange(userProjectAccessPolicies); - data.AddRange(groupProjectAccessPolicies); - data.AddRange(serviceAccountProjectAccessPolicies); + var data = MakeGrantedProjectAccessPolicies(project.Id, userProjectAccessPolicies, groupProjectAccessPolicies, + serviceAccountProjectAccessPolicies); + var saData = MakeGrantedServiceAccountAccessPolicies(serviceAccount.Id, userServiceAccountAccessPolicies, groupServiceAccountAccessPolicies); + data = data.Concat(saData).ToList(); data = MakeDuplicate(data, accessPolicyType); - SetupAdmin(sutProvider, project.OrganizationId); - sutProvider.GetDependency().GetByIdAsync(project.Id).Returns(project); - sutProvider.GetDependency().AccessPolicyExists(Arg.Any()) - .Returns(true); - await Assert.ThrowsAsync(() => - sutProvider.Sut.CreateForProjectAsync(project.Id, data, userId)); + sutProvider.Sut.CreateManyAsync(data, userId, AccessClientType.NoAccessCheck)); await sutProvider.GetDependency().DidNotReceiveWithAnyArgs() .CreateManyAsync(Arg.Any>()); @@ -221,24 +213,34 @@ public class CreateAccessPoliciesCommandTests [Theory] [BitAutoData(PermissionType.RunAsAdmin)] [BitAutoData(PermissionType.RunAsUserWithPermission)] - public async Task CreateForProject_Success( + public async Task CreateMany_Success( PermissionType permissionType, Guid userId, Project project, + ServiceAccount serviceAccount, List userProjectAccessPolicies, List groupProjectAccessPolicies, List serviceAccountProjectAccessPolicies, + List userServiceAccountAccessPolicies, + List groupServiceAccountAccessPolicies, SutProvider sutProvider) { - var data = new List(); - data.AddRange(userProjectAccessPolicies); - data.AddRange(groupProjectAccessPolicies); - data.AddRange(serviceAccountProjectAccessPolicies); + var data = MakeGrantedProjectAccessPolicies(project.Id, userProjectAccessPolicies, groupProjectAccessPolicies, + serviceAccountProjectAccessPolicies); + var saData = MakeGrantedServiceAccountAccessPolicies(serviceAccount.Id, userServiceAccountAccessPolicies, groupServiceAccountAccessPolicies); + data = data.Concat(saData).ToList(); - sutProvider.GetDependency().GetByIdAsync(project.Id).Returns(project); + SetupPermission(sutProvider, permissionType, serviceAccount, userId); SetupPermission(sutProvider, permissionType, project, userId); - await sutProvider.Sut.CreateForProjectAsync(project.Id, data, userId); + if (permissionType == PermissionType.RunAsAdmin) + { + await sutProvider.Sut.CreateManyAsync(data, userId, AccessClientType.NoAccessCheck); + } + else if (permissionType == PermissionType.RunAsUserWithPermission) + { + await sutProvider.Sut.CreateManyAsync(data, userId, AccessClientType.User); + } await sutProvider.GetDependency().Received(1) .CreateManyAsync(Arg.Is(AssertHelper.AssertPropertyEqual(data))); @@ -246,159 +248,24 @@ public class CreateAccessPoliciesCommandTests [Theory] [BitAutoData] - public async Task CreateForProject_UserNoPermission_ThrowsNotFound( + public async Task CreateMany_UserWithoutPermission_Throws( Guid userId, Project project, - List userProjectAccessPolicies, - List groupProjectAccessPolicies, - List serviceAccountProjectAccessPolicies, - SutProvider sutProvider) - { - var data = new List(); - data.AddRange(userProjectAccessPolicies); - data.AddRange(groupProjectAccessPolicies); - data.AddRange(serviceAccountProjectAccessPolicies); - - SetupUser(sutProvider, project.OrganizationId); - sutProvider.GetDependency().UserHasWriteAccessToProject(project.Id, userId).Returns(false); - sutProvider.GetDependency().GetByIdAsync(project.Id).Returns(project); - - await Assert.ThrowsAsync(() => - sutProvider.Sut.CreateForProjectAsync(project.Id, data, userId)); - - await sutProvider.GetDependency().DidNotReceiveWithAnyArgs().CreateManyAsync(default); - } - - [Theory] - [BitAutoData] - public async Task CreateForServiceAccount_SmNotEnabled_Throws( - Guid userId, ServiceAccount serviceAccount, List userProjectAccessPolicies, List groupProjectAccessPolicies, List serviceAccountProjectAccessPolicies, - SutProvider sutProvider) - { - var data = new List(); - data.AddRange(userProjectAccessPolicies); - data.AddRange(groupProjectAccessPolicies); - data.AddRange(serviceAccountProjectAccessPolicies); - - sutProvider.GetDependency().AccessSecretsManager(Arg.Any()).Returns(false); - - await Assert.ThrowsAsync(() => - sutProvider.Sut.CreateForServiceAccountAsync(serviceAccount.Id, data, userId)); - - await sutProvider.GetDependency().DidNotReceiveWithAnyArgs() - .CreateManyAsync(Arg.Any>()); - } - - [Theory] - [BitAutoData] - public async Task CreateForServiceAccount_AlreadyExists_ThrowsBadRequestException( - Guid userId, - ServiceAccount serviceAccount, - List userProjectAccessPolicies, - List groupProjectAccessPolicies, - List serviceAccountProjectAccessPolicies, - SutProvider sutProvider) - { - var data = new List(); - data.AddRange(userProjectAccessPolicies); - data.AddRange(groupProjectAccessPolicies); - data.AddRange(serviceAccountProjectAccessPolicies); - - SetupAdmin(sutProvider, serviceAccount.OrganizationId); - sutProvider.GetDependency().GetByIdAsync(serviceAccount.Id).Returns(serviceAccount); - sutProvider.GetDependency().AccessPolicyExists(Arg.Any()) - .Returns(true); - - await Assert.ThrowsAsync(() => - sutProvider.Sut.CreateForServiceAccountAsync(serviceAccount.Id, data, userId)); - - await sutProvider.GetDependency().DidNotReceiveWithAnyArgs() - .CreateManyAsync(Arg.Any>()); - } - - [Theory] - [BitAutoData(AccessPolicyType.UserProjectAccessPolicy)] - [BitAutoData(AccessPolicyType.GroupProjectAccessPolicy)] - [BitAutoData(AccessPolicyType.ServiceAccountProjectAccessPolicy)] - [BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy)] - [BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy)] - public async Task CreateForServiceAccount_NotUnique_Throws( - AccessPolicyType accessPolicyType, - Guid userId, - ServiceAccount serviceAccount, - List userProjectAccessPolicies, - List groupProjectAccessPolicies, - List serviceAccountProjectAccessPolicies, - SutProvider sutProvider - ) - { - var data = new List(); - data.AddRange(userProjectAccessPolicies); - data.AddRange(groupProjectAccessPolicies); - data.AddRange(serviceAccountProjectAccessPolicies); - data = MakeDuplicate(data, accessPolicyType); - - SetupAdmin(sutProvider, serviceAccount.OrganizationId); - sutProvider.GetDependency().GetByIdAsync(serviceAccount.Id).Returns(serviceAccount); - sutProvider.GetDependency().AccessPolicyExists(Arg.Any()) - .Returns(true); - - await Assert.ThrowsAsync(() => - sutProvider.Sut.CreateForServiceAccountAsync(serviceAccount.Id, data, userId)); - - await sutProvider.GetDependency().DidNotReceiveWithAnyArgs() - .CreateManyAsync(Arg.Any>()); - } - - - [Theory] - [BitAutoData(PermissionType.RunAsAdmin)] - [BitAutoData(PermissionType.RunAsUserWithPermission)] - public async Task CreateForServiceAccount_Success( - PermissionType permissionType, - Guid userId, - ServiceAccount serviceAccount, List userServiceAccountAccessPolicies, List groupServiceAccountAccessPolicies, SutProvider sutProvider) { - var data = new List(); - data.AddRange(userServiceAccountAccessPolicies); - data.AddRange(groupServiceAccountAccessPolicies); - - sutProvider.GetDependency().GetByIdAsync(serviceAccount.Id).Returns(serviceAccount); - SetupPermission(sutProvider, permissionType, serviceAccount, userId); - - await sutProvider.Sut.CreateForServiceAccountAsync(serviceAccount.Id, data, userId); - - await sutProvider.GetDependency().Received(1) - .CreateManyAsync(Arg.Is(AssertHelper.AssertPropertyEqual(data))); - } - - [Theory] - [BitAutoData] - public async Task CreateForServiceAccount_UserWithoutPermission_ThrowsNotFound( - Guid userId, - ServiceAccount serviceAccount, - List userServiceAccountAccessPolicies, - List groupServiceAccountAccessPolicies, - SutProvider sutProvider) - { - var data = new List(); - data.AddRange(userServiceAccountAccessPolicies); - data.AddRange(groupServiceAccountAccessPolicies); - - SetupUser(sutProvider, serviceAccount.OrganizationId); - sutProvider.GetDependency().GetByIdAsync(serviceAccount.Id).Returns(serviceAccount); - sutProvider.GetDependency() - .UserHasWriteAccessToServiceAccount(serviceAccount.Id, userId).Returns(false); + var data = MakeGrantedProjectAccessPolicies(project.Id, userProjectAccessPolicies, groupProjectAccessPolicies, + serviceAccountProjectAccessPolicies); + var saData = MakeGrantedServiceAccountAccessPolicies(serviceAccount.Id, userServiceAccountAccessPolicies, groupServiceAccountAccessPolicies); + data = data.Concat(saData).ToList(); await Assert.ThrowsAsync(() => - sutProvider.Sut.CreateForServiceAccountAsync(serviceAccount.Id, data, userId)); + sutProvider.Sut.CreateManyAsync(data, userId, AccessClientType.User)); await sutProvider.GetDependency().DidNotReceiveWithAnyArgs() .CreateManyAsync(Arg.Any>()); diff --git a/src/Api/SecretsManager/Controllers/AccessPoliciesController.cs b/src/Api/SecretsManager/Controllers/AccessPoliciesController.cs index 1707fd33c2..876a71fa3d 100644 --- a/src/Api/SecretsManager/Controllers/AccessPoliciesController.cs +++ b/src/Api/SecretsManager/Controllers/AccessPoliciesController.cs @@ -19,14 +19,15 @@ namespace Bit.Api.SecretsManager.Controllers; [Route("access-policies")] public class AccessPoliciesController : Controller { + private const int _maxBulkCreation = 15; private readonly IAccessPolicyRepository _accessPolicyRepository; - private readonly IServiceAccountRepository _serviceAccountRepository; private readonly ICreateAccessPoliciesCommand _createAccessPoliciesCommand; private readonly ICurrentContext _currentContext; private readonly IDeleteAccessPolicyCommand _deleteAccessPolicyCommand; private readonly IGroupRepository _groupRepository; private readonly IOrganizationUserRepository _organizationUserRepository; private readonly IProjectRepository _projectRepository; + private readonly IServiceAccountRepository _serviceAccountRepository; private readonly IUpdateAccessPolicyCommand _updateAccessPolicyCommand; private readonly IUserService _userService; @@ -58,9 +59,21 @@ public class AccessPoliciesController : Controller public async Task CreateProjectAccessPoliciesAsync([FromRoute] Guid id, [FromBody] AccessPoliciesCreateRequest request) { - var userId = _userService.GetProperUserId(User).Value; + if (request.Count() > _maxBulkCreation) + { + throw new BadRequestException($"Can process no more than {_maxBulkCreation} creation requests at once."); + } + + var project = await _projectRepository.GetByIdAsync(id); + if (project == null) + { + throw new NotFoundException(); + } + + var (accessClient, userId) = await GetAccessClientTypeAsync(project.OrganizationId); var policies = request.ToBaseAccessPoliciesForProject(id); - var results = await _createAccessPoliciesCommand.CreateForProjectAsync(id, policies, userId); + await _createAccessPoliciesCommand.CreateManyAsync(policies, userId, accessClient); + var results = await _accessPolicyRepository.GetManyByGrantedProjectIdAsync(id); return new ProjectAccessPoliciesResponseModel(results); } @@ -75,17 +88,31 @@ public class AccessPoliciesController : Controller } [HttpPost("/service-accounts/{id}/access-policies")] - public async Task CreateServiceAccountAccessPoliciesAsync([FromRoute] Guid id, + public async Task CreateServiceAccountAccessPoliciesAsync( + [FromRoute] Guid id, [FromBody] AccessPoliciesCreateRequest request) { - var userId = _userService.GetProperUserId(User).Value; + if (request.Count() > _maxBulkCreation) + { + throw new BadRequestException($"Can process no more than {_maxBulkCreation} creation requests at once."); + } + + var serviceAccount = await _serviceAccountRepository.GetByIdAsync(id); + if (serviceAccount == null) + { + throw new NotFoundException(); + } + + var (accessClient, userId) = await GetAccessClientTypeAsync(serviceAccount.OrganizationId); var policies = request.ToBaseAccessPoliciesForServiceAccount(id); - var results = await _createAccessPoliciesCommand.CreateForServiceAccountAsync(id, policies, userId); + await _createAccessPoliciesCommand.CreateManyAsync(policies, userId, accessClient); + var results = await _accessPolicyRepository.GetManyByGrantedServiceAccountIdAsync(id); return new ServiceAccountAccessPoliciesResponseModel(results); } [HttpGet("/service-accounts/{id}/access-policies")] - public async Task GetServiceAccountAccessPoliciesAsync([FromRoute] Guid id) + public async Task GetServiceAccountAccessPoliciesAsync( + [FromRoute] Guid id) { var serviceAccount = await _serviceAccountRepository.GetByIdAsync(id); await CheckUserHasWriteAccessToServiceAccountAsync(serviceAccount); @@ -94,6 +121,48 @@ public class AccessPoliciesController : Controller return new ServiceAccountAccessPoliciesResponseModel(results); } + [HttpGet("/service-accounts/{id}/granted-policies")] + public async Task> + GetServiceAccountGrantedPoliciesAsync([FromRoute] Guid id) + { + var serviceAccount = await _serviceAccountRepository.GetByIdAsync(id); + if (serviceAccount == null) + { + throw new NotFoundException(); + } + + var (accessClient, userId) = await GetAccessClientTypeAsync(serviceAccount.OrganizationId); + var results = await _accessPolicyRepository.GetManyByServiceAccountIdAsync(id, userId, accessClient); + var responses = results.Select(ap => + new ServiceAccountProjectAccessPolicyResponseModel((ServiceAccountProjectAccessPolicy)ap)); + return new ListResponseModel(responses); + } + + [HttpPost("/service-accounts/{id}/granted-policies")] + public async Task> + CreateServiceAccountGrantedPoliciesAsync([FromRoute] Guid id, + [FromBody] List requests) + { + if (requests.Count > _maxBulkCreation) + { + throw new BadRequestException($"Can process no more than {_maxBulkCreation} creation requests at once."); + } + + var serviceAccount = await _serviceAccountRepository.GetByIdAsync(id); + if (serviceAccount == null) + { + throw new NotFoundException(); + } + + var (accessClient, userId) = await GetAccessClientTypeAsync(serviceAccount.OrganizationId); + var policies = requests.Select(request => request.ToServiceAccountProjectAccessPolicy(id)); + var results = + await _createAccessPoliciesCommand.CreateManyAsync(new List(policies), userId, accessClient); + var responses = results.Select(ap => + new ServiceAccountProjectAccessPolicyResponseModel((ServiceAccountProjectAccessPolicy)ap)); + return new ListResponseModel(responses); + } + [HttpPut("{id}")] public async Task UpdateAccessPolicyAsync([FromRoute] Guid id, [FromBody] AccessPolicyUpdateRequest request) @@ -104,9 +173,11 @@ public class AccessPoliciesController : Controller return result switch { UserProjectAccessPolicy accessPolicy => new UserProjectAccessPolicyResponseModel(accessPolicy), - UserServiceAccountAccessPolicy accessPolicy => new UserServiceAccountAccessPolicyResponseModel(accessPolicy), + UserServiceAccountAccessPolicy accessPolicy => + new UserServiceAccountAccessPolicyResponseModel(accessPolicy), GroupProjectAccessPolicy accessPolicy => new GroupProjectAccessPolicyResponseModel(accessPolicy), - GroupServiceAccountAccessPolicy accessPolicy => new GroupServiceAccountAccessPolicyResponseModel(accessPolicy), + GroupServiceAccountAccessPolicy accessPolicy => new GroupServiceAccountAccessPolicyResponseModel( + accessPolicy), ServiceAccountProjectAccessPolicy accessPolicy => new ServiceAccountProjectAccessPolicyResponseModel( accessPolicy), _ => throw new ArgumentException("Unsupported access policy type provided."), @@ -121,7 +192,8 @@ public class AccessPoliciesController : Controller } [HttpGet("/organizations/{id}/access-policies/people/potential-grantees")] - public async Task> GetPeoplePotentialGranteesAsync([FromRoute] Guid id) + public async Task> GetPeoplePotentialGranteesAsync( + [FromRoute] Guid id) { if (!_currentContext.AccessSecretsManager(id)) { @@ -141,16 +213,10 @@ public class AccessPoliciesController : Controller } [HttpGet("/organizations/{id}/access-policies/service-accounts/potential-grantees")] - public async Task> GetServiceAccountsPotentialGranteesAsync([FromRoute] Guid id) + public async Task> GetServiceAccountsPotentialGranteesAsync( + [FromRoute] Guid id) { - if (!_currentContext.AccessSecretsManager(id)) - { - throw new NotFoundException(); - } - - var userId = _userService.GetProperUserId(User).Value; - var orgAdmin = await _currentContext.OrganizationAdmin(id); - var accessClient = AccessClientHelper.ToAccessClient(_currentContext.ClientType, orgAdmin); + var (accessClient, userId) = await GetAccessClientTypeAsync(id); var serviceAccounts = await _serviceAccountRepository.GetManyByOrganizationIdWriteAccessAsync(id, @@ -162,17 +228,30 @@ public class AccessPoliciesController : Controller return new ListResponseModel(serviceAccountResponses); } + [HttpGet("/organizations/{id}/access-policies/projects/potential-grantees")] + public async Task> GetProjectPotentialGranteesAsync( + [FromRoute] Guid id) + { + var (accessClient, userId) = await GetAccessClientTypeAsync(id); + + var projects = + await _projectRepository.GetManyByOrganizationIdWriteAccessAsync(id, + userId, + accessClient); + var projectResponses = + projects.Select(project => new PotentialGranteeResponseModel(project)); + + return new ListResponseModel(projectResponses); + } + private async Task CheckUserHasWriteAccessToProjectAsync(Project project) { - if (project == null || !_currentContext.AccessSecretsManager(project.OrganizationId)) + if (project == null) { throw new NotFoundException(); } - var userId = _userService.GetProperUserId(User).Value; - var orgAdmin = await _currentContext.OrganizationAdmin(project.OrganizationId); - var accessClient = AccessClientHelper.ToAccessClient(_currentContext.ClientType, orgAdmin); - + var (accessClient, userId) = await GetAccessClientTypeAsync(project.OrganizationId); var hasAccess = accessClient switch { AccessClientType.NoAccessCheck => true, @@ -188,18 +267,17 @@ public class AccessPoliciesController : Controller private async Task CheckUserHasWriteAccessToServiceAccountAsync(ServiceAccount serviceAccount) { - if (serviceAccount == null || !_currentContext.AccessSecretsManager(serviceAccount.OrganizationId)) + if (serviceAccount == null) { throw new NotFoundException(); } - var userId = _userService.GetProperUserId(User).Value; - var orgAdmin = await _currentContext.OrganizationAdmin(serviceAccount.OrganizationId); - var accessClient = AccessClientHelper.ToAccessClient(_currentContext.ClientType, orgAdmin); + var (accessClient, userId) = await GetAccessClientTypeAsync(serviceAccount.OrganizationId); var hasAccess = accessClient switch { AccessClientType.NoAccessCheck => true, - AccessClientType.User => await _serviceAccountRepository.UserHasWriteAccessToServiceAccount(serviceAccount.Id, userId), + AccessClientType.User => await _serviceAccountRepository.UserHasWriteAccessToServiceAccount( + serviceAccount.Id, userId), _ => false, }; @@ -208,4 +286,17 @@ public class AccessPoliciesController : Controller throw new NotFoundException(); } } + + private async Task<(AccessClientType AccessClientType, Guid UserId)> GetAccessClientTypeAsync(Guid organizationId) + { + if (!_currentContext.AccessSecretsManager(organizationId)) + { + throw new NotFoundException(); + } + + var userId = _userService.GetProperUserId(User).Value; + var orgAdmin = await _currentContext.OrganizationAdmin(organizationId); + var accessClient = AccessClientHelper.ToAccessClient(_currentContext.ClientType, orgAdmin); + return (accessClient, userId); + } } diff --git a/src/Api/SecretsManager/Models/Request/AccessPoliciesCreateRequest.cs b/src/Api/SecretsManager/Models/Request/AccessPoliciesCreateRequest.cs index 689a6c59e1..e4de0a87a6 100644 --- a/src/Api/SecretsManager/Models/Request/AccessPoliciesCreateRequest.cs +++ b/src/Api/SecretsManager/Models/Request/AccessPoliciesCreateRequest.cs @@ -72,6 +72,26 @@ public class AccessPoliciesCreateRequest } return policies; } + + public int Count() + { + var total = 0; + + if (UserAccessPolicyRequests != null) + { + total += UserAccessPolicyRequests.Count(); + } + if (GroupAccessPolicyRequests != null) + { + total += GroupAccessPolicyRequests.Count(); + } + if (ServiceAccountAccessPolicyRequests != null) + { + total += ServiceAccountAccessPolicyRequests.Count(); + } + + return total; + } } public class AccessPolicyRequest diff --git a/src/Api/SecretsManager/Models/Request/GrantedAccessPolicyRequest.cs b/src/Api/SecretsManager/Models/Request/GrantedAccessPolicyRequest.cs new file mode 100644 index 0000000000..0b8f1633c1 --- /dev/null +++ b/src/Api/SecretsManager/Models/Request/GrantedAccessPolicyRequest.cs @@ -0,0 +1,25 @@ +using System.ComponentModel.DataAnnotations; +using Bit.Core.SecretsManager.Entities; + +namespace Bit.Api.SecretsManager.Models.Request; + +public class GrantedAccessPolicyRequest +{ + [Required] + public Guid GrantedId { get; set; } + + [Required] + public bool Read { get; set; } + + [Required] + public bool Write { get; set; } + + public ServiceAccountProjectAccessPolicy ToServiceAccountProjectAccessPolicy(Guid serviceAccountId) => + new() + { + ServiceAccountId = serviceAccountId, + GrantedProjectId = GrantedId, + Read = Read, + Write = Write, + }; +} diff --git a/src/Api/SecretsManager/Models/Response/AccessPolicyResponseModel.cs b/src/Api/SecretsManager/Models/Response/AccessPolicyResponseModel.cs index 17337ab699..f273e6d57c 100644 --- a/src/Api/SecretsManager/Models/Response/AccessPolicyResponseModel.cs +++ b/src/Api/SecretsManager/Models/Response/AccessPolicyResponseModel.cs @@ -115,6 +115,7 @@ public class ServiceAccountProjectAccessPolicyResponseModel : BaseAccessPolicyRe ServiceAccountId = accessPolicy.ServiceAccountId; GrantedProjectId = accessPolicy.GrantedProjectId; ServiceAccountName = accessPolicy.ServiceAccount?.Name; + GrantedProjectName = accessPolicy.GrantedProject?.Name; } public ServiceAccountProjectAccessPolicyResponseModel() @@ -125,4 +126,5 @@ public class ServiceAccountProjectAccessPolicyResponseModel : BaseAccessPolicyRe public Guid? ServiceAccountId { get; set; } public string? ServiceAccountName { get; set; } public Guid? GrantedProjectId { get; set; } + public string? GrantedProjectName { get; set; } } diff --git a/src/Api/SecretsManager/Models/Response/PotentialGranteeResponseModel.cs b/src/Api/SecretsManager/Models/Response/PotentialGranteeResponseModel.cs index 7b0632a459..b76af966fe 100644 --- a/src/Api/SecretsManager/Models/Response/PotentialGranteeResponseModel.cs +++ b/src/Api/SecretsManager/Models/Response/PotentialGranteeResponseModel.cs @@ -49,6 +49,19 @@ public class PotentialGranteeResponseModel : ResponseModel Type = "serviceAccount"; } + public PotentialGranteeResponseModel(Project project) + : base(_objectName) + { + if (project == null) + { + throw new ArgumentNullException(nameof(project)); + } + + Id = project.Id.ToString(); + Name = project.Name; + Type = "project"; + } + public PotentialGranteeResponseModel() : base(_objectName) { } diff --git a/src/Core/SecretsManager/Commands/AccessPolicies/Interfaces/ICreateAccessPoliciesCommand.cs b/src/Core/SecretsManager/Commands/AccessPolicies/Interfaces/ICreateAccessPoliciesCommand.cs index b1b0bf563f..5baa486e07 100644 --- a/src/Core/SecretsManager/Commands/AccessPolicies/Interfaces/ICreateAccessPoliciesCommand.cs +++ b/src/Core/SecretsManager/Commands/AccessPolicies/Interfaces/ICreateAccessPoliciesCommand.cs @@ -1,9 +1,9 @@ -using Bit.Core.SecretsManager.Entities; +using Bit.Core.Enums; +using Bit.Core.SecretsManager.Entities; namespace Bit.Core.SecretsManager.Commands.AccessPolicies.Interfaces; public interface ICreateAccessPoliciesCommand { - Task> CreateForProjectAsync(Guid projectId, List accessPolicies, Guid userId); - Task> CreateForServiceAccountAsync(Guid serviceAccountId, List accessPolicies, Guid userId); + Task> CreateManyAsync(List accessPolicies, Guid userId, AccessClientType accessType); } diff --git a/src/Core/SecretsManager/Repositories/IAccessPolicyRepository.cs b/src/Core/SecretsManager/Repositories/IAccessPolicyRepository.cs index dbe05074fa..7241c81eb3 100644 --- a/src/Core/SecretsManager/Repositories/IAccessPolicyRepository.cs +++ b/src/Core/SecretsManager/Repositories/IAccessPolicyRepository.cs @@ -1,4 +1,5 @@ #nullable enable +using Bit.Core.Enums; using Bit.Core.SecretsManager.Entities; namespace Bit.Core.SecretsManager.Repositories; @@ -10,6 +11,8 @@ public interface IAccessPolicyRepository Task GetByIdAsync(Guid id); Task> GetManyByGrantedProjectIdAsync(Guid id); Task> GetManyByGrantedServiceAccountIdAsync(Guid id); + Task> GetManyByServiceAccountIdAsync(Guid id, Guid userId, + AccessClientType accessType); Task ReplaceAsync(BaseAccessPolicy baseAccessPolicy); Task DeleteAsync(Guid id); } diff --git a/src/Core/SecretsManager/Repositories/IProjectRepository.cs b/src/Core/SecretsManager/Repositories/IProjectRepository.cs index b742b811c6..3d62d571c3 100644 --- a/src/Core/SecretsManager/Repositories/IProjectRepository.cs +++ b/src/Core/SecretsManager/Repositories/IProjectRepository.cs @@ -6,6 +6,7 @@ namespace Bit.Core.SecretsManager.Repositories; public interface IProjectRepository { Task> GetManyByOrganizationIdAsync(Guid organizationId, Guid userId, AccessClientType accessType); + Task> GetManyByOrganizationIdWriteAccessAsync(Guid organizationId, Guid userId, AccessClientType accessType); Task> GetManyByIds(IEnumerable ids); Task GetByIdAsync(Guid id); Task CreateAsync(Project project); diff --git a/test/Api.IntegrationTest/SecretsManager/Controllers/AccessPoliciesControllerTest.cs b/test/Api.IntegrationTest/SecretsManager/Controllers/AccessPoliciesControllerTest.cs index 33cd4d6e52..305d249738 100644 --- a/test/Api.IntegrationTest/SecretsManager/Controllers/AccessPoliciesControllerTest.cs +++ b/test/Api.IntegrationTest/SecretsManager/Controllers/AccessPoliciesControllerTest.cs @@ -157,7 +157,7 @@ public class AccessPoliciesControllerTest : IClassFixture { // Create a new account as a user var (org, _) = await _organizationHelper.Initialize(true, true); - var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true); + var (email, _) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true); await LoginAsync(email); var project = await _projectRepository.CreateAsync(new Project @@ -207,7 +207,7 @@ public class AccessPoliciesControllerTest : IClassFixture public async Task UpdateAccessPolicy_NoPermission() { // Create a new account as a user - var (org, _) = await _organizationHelper.Initialize(true, true); + await _organizationHelper.Initialize(true, true); var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true); await LoginAsync(email); @@ -284,7 +284,7 @@ public class AccessPoliciesControllerTest : IClassFixture public async Task DeleteAccessPolicy_NoPermission() { // Create a new account as a user - var (org, _) = await _organizationHelper.Initialize(true, true); + await _organizationHelper.Initialize(true, true); var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true); await LoginAsync(email); @@ -344,8 +344,8 @@ public class AccessPoliciesControllerTest : IClassFixture Assert.NotNull(result); Assert.Empty(result!.UserAccessPolicies); - Assert.Empty(result!.GroupAccessPolicies); - Assert.Empty(result!.ServiceAccountAccessPolicies); + Assert.Empty(result.GroupAccessPolicies); + Assert.Empty(result.ServiceAccountAccessPolicies); } [Theory] @@ -356,6 +356,7 @@ public class AccessPoliciesControllerTest : IClassFixture { var (org, _) = await _organizationHelper.Initialize(useSecrets, accessSecrets); await LoginAsync(_email); + var initData = await SetupAccessPolicyRequest(org.Id); var response = await _client.GetAsync($"/projects/{initData.ProjectId}/access-policies"); @@ -366,7 +367,7 @@ public class AccessPoliciesControllerTest : IClassFixture public async Task GetProjectAccessPolicies_NoPermission() { // Create a new account as a user - var (org, _) = await _organizationHelper.Initialize(true, true); + await _organizationHelper.Initialize(true, true); var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true); await LoginAsync(email); @@ -434,7 +435,7 @@ public class AccessPoliciesControllerTest : IClassFixture if (permissionType == PermissionType.RunAsUserWithPermission) { - var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true); + var (email, _) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true); await LoginAsync(email); } @@ -469,10 +470,10 @@ public class AccessPoliciesControllerTest : IClassFixture { // Create a new account as a user var (org, _) = await _organizationHelper.Initialize(true, true); - var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true); + var (email, _) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true); await LoginAsync(email); - var serviceAccount = await _serviceAccountRepository.CreateAsync(new ServiceAccount + await _serviceAccountRepository.CreateAsync(new ServiceAccount { OrganizationId = org.Id, Name = _mockEncryptedString, @@ -531,7 +532,85 @@ public class AccessPoliciesControllerTest : IClassFixture Assert.NotNull(result?.Data); Assert.NotEmpty(result!.Data); - Assert.Equal(serviceAccount.Id.ToString(), result!.Data.First(x => x.Id == serviceAccount.Id.ToString()).Id); + Assert.Equal(serviceAccount.Id.ToString(), result.Data.First(x => x.Id == serviceAccount.Id.ToString()).Id); + } + + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + public async Task GetProjectPotentialGrantees_SmNotEnabled_NotFound(bool useSecrets, bool accessSecrets) + { + var (org, _) = await _organizationHelper.Initialize(useSecrets, accessSecrets); + await LoginAsync(_email); + + var response = + await _client.GetAsync( + $"/organizations/{org.Id}/access-policies/projects/potential-grantees"); + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task GetProjectPotentialGrantees_OnlyReturnsProjectsWithWriteAccess() + { + // Create a new account as a user + var (org, _) = await _organizationHelper.Initialize(true, true); + var (email, _) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true); + await LoginAsync(email); + + await _projectRepository.CreateAsync(new Project { OrganizationId = org.Id, Name = _mockEncryptedString }); + + + var response = + await _client.GetAsync( + $"/organizations/{org.Id}/access-policies/projects/potential-grantees"); + response.EnsureSuccessStatusCode(); + + var result = await response.Content.ReadFromJsonAsync>(); + + Assert.NotNull(result?.Data); + Assert.Empty(result!.Data); + } + + [Theory] + [InlineData(PermissionType.RunAsAdmin)] + [InlineData(PermissionType.RunAsUserWithPermission)] + public async Task GetProjectPotentialGrantees_Success(PermissionType permissionType) + { + var (org, _) = await _organizationHelper.Initialize(true, true); + await LoginAsync(_email); + + var project = await _projectRepository.CreateAsync(new Project + { + OrganizationId = org.Id, + Name = _mockEncryptedString, + }); + + if (permissionType == PermissionType.RunAsUserWithPermission) + { + var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true); + await LoginAsync(email); + + await _accessPolicyRepository.CreateManyAsync( + new List + { + new UserProjectAccessPolicy + { + GrantedProjectId = project.Id, OrganizationUserId = orgUser.Id, Read = true, Write = true, + }, + }); + } + + var response = + await _client.GetAsync( + $"/organizations/{org.Id}/access-policies/projects/potential-grantees"); + response.EnsureSuccessStatusCode(); + + var result = await response.Content.ReadFromJsonAsync>(); + + Assert.NotNull(result?.Data); + Assert.NotEmpty(result!.Data); + Assert.Equal(project.Id.ToString(), result.Data.First(x => x.Id == project.Id.ToString()).Id); } [Theory] @@ -696,14 +775,14 @@ public class AccessPoliciesControllerTest : IClassFixture Assert.NotNull(result); Assert.Empty(result!.UserAccessPolicies); - Assert.Empty(result!.GroupAccessPolicies); + Assert.Empty(result.GroupAccessPolicies); } [Fact] public async Task GetServiceAccountAccessPolicies_NoPermission() { // Create a new account as a user - var (org, _) = await _organizationHelper.Initialize(true, true); + await _organizationHelper.Initialize(true, true); var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true); await LoginAsync(email); @@ -763,6 +842,208 @@ public class AccessPoliciesControllerTest : IClassFixture result.UserAccessPolicies.First(x => x.OrganizationUserId == owerOrgUser.Id).OrganizationUserId); } + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + public async Task CreateServiceAccountGrantedPolicies_SmNotEnabled_NotFound(bool useSecrets, bool accessSecrets) + { + var (org, _) = await _organizationHelper.Initialize(useSecrets, accessSecrets); + await LoginAsync(_email); + + var serviceAccount = await _serviceAccountRepository.CreateAsync(new ServiceAccount + { + OrganizationId = org.Id, + Name = _mockEncryptedString, + }); + + var request = new List { new() { GrantedId = new Guid() } }; + + var response = + await _client.PostAsJsonAsync($"/service-accounts/{serviceAccount.Id}/granted-policies", request); + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Theory] + [InlineData(PermissionType.RunAsAdmin)] + [InlineData(PermissionType.RunAsUserWithPermission)] + public async Task CreateServiceAccountGrantedPolicies(PermissionType permissionType) + { + var (org, orgUser) = await _organizationHelper.Initialize(true, true); + await LoginAsync(_email); + var ownerOrgUserId = orgUser.Id; + + var serviceAccount = await _serviceAccountRepository.CreateAsync(new ServiceAccount + { + OrganizationId = org.Id, + Name = _mockEncryptedString, + }); + + var project = await _projectRepository.CreateAsync(new Project + { + OrganizationId = org.Id, + Name = _mockEncryptedString, + }); + + var request = + new List { new() { GrantedId = project.Id, Read = true, Write = true } }; + + + if (permissionType == PermissionType.RunAsUserWithPermission) + { + var (email, newOrgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true); + await LoginAsync(email); + var accessPolicies = new List + { + new UserProjectAccessPolicy + { + GrantedProjectId = project.Id, OrganizationUserId = newOrgUser.Id, Read = true, Write = true, + }, + }; + await _accessPolicyRepository.CreateManyAsync(accessPolicies); + } + + + var response = + await _client.PostAsJsonAsync($"/service-accounts/{serviceAccount.Id}/granted-policies", request); + response.EnsureSuccessStatusCode(); + + var result = await response.Content + .ReadFromJsonAsync>(); + + Assert.NotNull(result); + Assert.NotEmpty(result!.Data); + Assert.Equal(project.Id, result.Data.First().GrantedProjectId); + + var createdAccessPolicy = + await _accessPolicyRepository.GetByIdAsync(result.Data.First().Id); + Assert.NotNull(createdAccessPolicy); + Assert.Equal(result.Data.First().Read, createdAccessPolicy!.Read); + Assert.Equal(result.Data.First().Write, createdAccessPolicy.Write); + Assert.Equal(result.Data.First().Id, createdAccessPolicy.Id); + AssertHelper.AssertRecent(createdAccessPolicy.CreationDate); + AssertHelper.AssertRecent(createdAccessPolicy.RevisionDate); + } + + [Fact] + public async Task CreateServiceAccountGrantedPolicies_NoPermission() + { + // Create a new account as a user + var (org, _) = await _organizationHelper.Initialize(true, true); + var (email, _) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true); + await LoginAsync(email); + + var serviceAccount = await _serviceAccountRepository.CreateAsync(new ServiceAccount + { + OrganizationId = org.Id, + Name = _mockEncryptedString, + }); + + var project = await _projectRepository.CreateAsync(new Project + { + OrganizationId = org.Id, + Name = _mockEncryptedString, + }); + + var request = + new List { new() { GrantedId = project.Id, Read = true, Write = true } }; + + var response = + await _client.PostAsJsonAsync($"/service-accounts/{serviceAccount.Id}/granted-policies", request); + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + public async Task GetServiceAccountGrantedPolicies_SmNotEnabled_NotFound(bool useSecrets, bool accessSecrets) + { + var (org, _) = await _organizationHelper.Initialize(useSecrets, accessSecrets); + await LoginAsync(_email); + var initData = await SetupAccessPolicyRequest(org.Id); + + var response = await _client.GetAsync($"/service-accounts/{initData.ServiceAccountId}/granted-policies"); + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task GetServiceAccountGrantedPolicies_ReturnsEmpty() + { + var (org, _) = await _organizationHelper.Initialize(true, true); + await LoginAsync(_email); + + var serviceAccount = await _serviceAccountRepository.CreateAsync(new ServiceAccount + { + OrganizationId = org.Id, + Name = _mockEncryptedString, + }); + + var response = await _client.GetAsync($"/service-accounts/{serviceAccount.Id}/granted-policies"); + response.EnsureSuccessStatusCode(); + + var result = await response.Content + .ReadFromJsonAsync>(); + + Assert.NotNull(result); + Assert.Empty(result!.Data); + } + + [Fact] + public async Task GetServiceAccountGrantedPolicies_NoPermission_ReturnsEmpty() + { + // Create a new account as a user + await _organizationHelper.Initialize(true, true); + var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true); + await LoginAsync(email); + + var initData = await SetupAccessPolicyRequest(orgUser.OrganizationId); + + var response = await _client.GetAsync($"/service-accounts/{initData.ServiceAccountId}/granted-policies"); + + var result = await response.Content + .ReadFromJsonAsync>(); + + Assert.NotNull(result); + Assert.Empty(result!.Data); + } + + [Theory] + [InlineData(PermissionType.RunAsAdmin)] + [InlineData(PermissionType.RunAsUserWithPermission)] + public async Task GetServiceAccountGrantedPolicies(PermissionType permissionType) + { + var (org, _) = await _organizationHelper.Initialize(true, true); + await LoginAsync(_email); + var initData = await SetupAccessPolicyRequest(org.Id); + + if (permissionType == PermissionType.RunAsUserWithPermission) + { + var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true); + await LoginAsync(email); + var accessPolicies = new List + { + new UserProjectAccessPolicy + { + GrantedProjectId = initData.ProjectId, OrganizationUserId = orgUser.Id, Read = true, Write = true, + }, + }; + await _accessPolicyRepository.CreateManyAsync(accessPolicies); + } + + var response = await _client.GetAsync($"/service-accounts/{initData.ServiceAccountId}/granted-policies"); + response.EnsureSuccessStatusCode(); + + var result = await response.Content + .ReadFromJsonAsync>(); + + Assert.NotNull(result?.Data); + Assert.NotEmpty(result!.Data); + Assert.Equal(initData.ServiceAccountId, result.Data.First().ServiceAccountId); + Assert.NotNull(result.Data.First().ServiceAccountName); + Assert.NotNull(result.Data.First().GrantedProjectName); + } + private async Task SetupAccessPolicyRequest(Guid organizationId) { var project = await _projectRepository.CreateAsync(new Project diff --git a/test/Api.Test/SecretsManager/Controllers/AccessPoliciesControllerTests.cs b/test/Api.Test/SecretsManager/Controllers/AccessPoliciesControllerTests.cs index 2cd3bf7748..9a3757fb36 100644 --- a/test/Api.Test/SecretsManager/Controllers/AccessPoliciesControllerTests.cs +++ b/test/Api.Test/SecretsManager/Controllers/AccessPoliciesControllerTests.cs @@ -26,6 +26,30 @@ namespace Bit.Api.Test.SecretsManager.Controllers; [JsonDocumentCustomize] public class AccessPoliciesControllerTests { + private const int _overMax = 16; + + private static AccessPoliciesCreateRequest AddRequestsOverMax(AccessPoliciesCreateRequest request) + { + var newRequests = new List(); + for (var i = 0; i < _overMax; i++) + { + newRequests.Add(new AccessPolicyRequest { GranteeId = new Guid(), Read = true, Write = true }); + } + + request.UserAccessPolicyRequests = newRequests; + return request; + } + + private static List AddRequestsOverMax(List request) + { + for (var i = 0; i < _overMax; i++) + { + request.Add(new GrantedAccessPolicyRequest { GrantedId = new Guid() }); + } + + return request; + } + private static void SetupAdmin(SutProvider sutProvider, Guid organizationId) { sutProvider.GetDependency().AccessSecretsManager(default).ReturnsForAnyArgs(true); @@ -50,7 +74,8 @@ public class AccessPoliciesControllerTests sutProvider.GetDependency().OrganizationUser(default).ReturnsForAnyArgs(true); } - private static void SetupPermission(SutProvider sutProvider, PermissionType permissionType, Guid orgId) + private static void SetupPermission(SutProvider sutProvider, + PermissionType permissionType, Guid orgId) { switch (permissionType) { @@ -61,7 +86,6 @@ public class AccessPoliciesControllerTests SetupUserWithPermission(sutProvider, orgId); break; } - } [Theory] @@ -280,22 +304,139 @@ public class AccessPoliciesControllerTests .GetManyByGrantedServiceAccountIdAsync(Arg.Any()); } + [Theory] + [BitAutoData(PermissionType.RunAsAdmin)] + [BitAutoData(PermissionType.RunAsUserWithPermission)] + public async void GetServiceAccountGrantedPolicies_ReturnsEmptyList( + PermissionType permissionType, + SutProvider sutProvider, + Guid id, ServiceAccount data) + { + sutProvider.GetDependency().GetByIdAsync(data.Id).ReturnsForAnyArgs(data); + + switch (permissionType) + { + case PermissionType.RunAsAdmin: + SetupAdmin(sutProvider, data.OrganizationId); + break; + case PermissionType.RunAsUserWithPermission: + SetupUserWithPermission(sutProvider, data.OrganizationId); + sutProvider.GetDependency() + .UserHasWriteAccessToServiceAccount(default, default) + .ReturnsForAnyArgs(true); + break; + } + + var result = await sutProvider.Sut.GetServiceAccountGrantedPoliciesAsync(id); + + await sutProvider.GetDependency().Received(1) + .GetManyByServiceAccountIdAsync(Arg.Is(AssertHelper.AssertPropertyEqual(id)), Arg.Any(), + Arg.Any()); + + Assert.Empty(result.Data); + } + + [Theory] + [BitAutoData(PermissionType.RunAsAdmin)] + [BitAutoData(PermissionType.RunAsUserWithPermission)] + public async void GetServiceAccountGrantedPolicies_Success( + PermissionType permissionType, + SutProvider sutProvider, + Guid id, + ServiceAccount data, + ServiceAccountProjectAccessPolicy resultAccessPolicy) + { + sutProvider.GetDependency().GetByIdAsync(default).ReturnsForAnyArgs(data); + switch (permissionType) + { + case PermissionType.RunAsAdmin: + SetupAdmin(sutProvider, data.OrganizationId); + break; + case PermissionType.RunAsUserWithPermission: + SetupUserWithPermission(sutProvider, data.OrganizationId); + break; + } + + sutProvider.GetDependency().GetManyByServiceAccountIdAsync(default, default, default) + .ReturnsForAnyArgs(new List { resultAccessPolicy }); + + var result = await sutProvider.Sut.GetServiceAccountGrantedPoliciesAsync(id); + + await sutProvider.GetDependency().Received(1) + .GetManyByServiceAccountIdAsync(Arg.Is(AssertHelper.AssertPropertyEqual(id)), Arg.Any(), + Arg.Any()); + + Assert.NotEmpty(result.Data); + } + + [Theory] + [BitAutoData] + public async void CreateProjectAccessPolicies_RequestMoreThanMax_Throws( + SutProvider sutProvider, + Guid id, + Project mockProject, + UserProjectAccessPolicy data, + AccessPoliciesCreateRequest request) + { + sutProvider.GetDependency().GetByIdAsync(default).ReturnsForAnyArgs(mockProject); + sutProvider.GetDependency().AccessSecretsManager(default).ReturnsForAnyArgs(true); + sutProvider.GetDependency().GetProperUserId(default).ReturnsForAnyArgs(Guid.NewGuid()); + sutProvider.GetDependency().CreateManyAsync(default, default, default) + .ReturnsForAnyArgs(new List { data }); + + request = AddRequestsOverMax(request); + + await Assert.ThrowsAsync(() => + sutProvider.Sut.CreateProjectAccessPoliciesAsync(id, request)); + + await sutProvider.GetDependency().DidNotReceiveWithAnyArgs() + .CreateManyAsync(Arg.Any>(), Arg.Any(), Arg.Any()); + } + [Theory] [BitAutoData] public async void CreateProjectAccessPolicies_Success( SutProvider sutProvider, Guid id, + Project mockProject, UserProjectAccessPolicy data, AccessPoliciesCreateRequest request) { + sutProvider.GetDependency().GetByIdAsync(default).ReturnsForAnyArgs(mockProject); + sutProvider.GetDependency().AccessSecretsManager(default).ReturnsForAnyArgs(true); sutProvider.GetDependency().GetProperUserId(default).ReturnsForAnyArgs(Guid.NewGuid()); - sutProvider.GetDependency().CreateForProjectAsync(default, default, default) + sutProvider.GetDependency().CreateManyAsync(default, default, default) .ReturnsForAnyArgs(new List { data }); await sutProvider.Sut.CreateProjectAccessPoliciesAsync(id, request); await sutProvider.GetDependency().Received(1) - .CreateForProjectAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + .CreateManyAsync(Arg.Any>(), Arg.Any(), Arg.Any()); + } + + [Theory] + [BitAutoData] + public async void CreateServiceAccountAccessPolicies_RequestMoreThanMax_Throws( + SutProvider sutProvider, + Guid id, + ServiceAccount serviceAccount, + UserServiceAccountAccessPolicy data, + AccessPoliciesCreateRequest request) + { + sutProvider.GetDependency().GetByIdAsync(default).ReturnsForAnyArgs(serviceAccount); + sutProvider.GetDependency().AccessSecretsManager(default).ReturnsForAnyArgs(true); + sutProvider.GetDependency().GetProperUserId(default).ReturnsForAnyArgs(Guid.NewGuid()); + sutProvider.GetDependency() + .CreateManyAsync(default, default, default) + .ReturnsForAnyArgs(new List { data }); + + request = AddRequestsOverMax(request); + + await Assert.ThrowsAsync(() => + sutProvider.Sut.CreateServiceAccountAccessPoliciesAsync(id, request)); + + await sutProvider.GetDependency().DidNotReceiveWithAnyArgs() + .CreateManyAsync(Arg.Any>(), Arg.Any(), Arg.Any()); } [Theory] @@ -303,18 +444,68 @@ public class AccessPoliciesControllerTests public async void CreateServiceAccountAccessPolicies_Success( SutProvider sutProvider, Guid id, + ServiceAccount serviceAccount, UserServiceAccountAccessPolicy data, AccessPoliciesCreateRequest request) { + sutProvider.GetDependency().GetByIdAsync(default).ReturnsForAnyArgs(serviceAccount); + sutProvider.GetDependency().AccessSecretsManager(default).ReturnsForAnyArgs(true); sutProvider.GetDependency().GetProperUserId(default).ReturnsForAnyArgs(Guid.NewGuid()); sutProvider.GetDependency() - .CreateForServiceAccountAsync(default, default, default) + .CreateManyAsync(default, default, default) .ReturnsForAnyArgs(new List { data }); await sutProvider.Sut.CreateServiceAccountAccessPoliciesAsync(id, request); await sutProvider.GetDependency().Received(1) - .CreateForServiceAccountAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + .CreateManyAsync(Arg.Any>(), Arg.Any(), Arg.Any()); + } + + [Theory] + [BitAutoData] + public async void CreateServiceAccountGrantedPolicies_RequestMoreThanMax_Throws( + SutProvider sutProvider, + Guid id, + ServiceAccount serviceAccount, + ServiceAccountProjectAccessPolicy data, + List request) + { + sutProvider.GetDependency().GetByIdAsync(default).ReturnsForAnyArgs(serviceAccount); + sutProvider.GetDependency().AccessSecretsManager(default).ReturnsForAnyArgs(true); + sutProvider.GetDependency().GetProperUserId(default).ReturnsForAnyArgs(Guid.NewGuid()); + sutProvider.GetDependency() + .CreateManyAsync(default, default, default) + .ReturnsForAnyArgs(new List { data }); + + request = AddRequestsOverMax(request); + + await Assert.ThrowsAsync(() => + sutProvider.Sut.CreateServiceAccountGrantedPoliciesAsync(id, request)); + + await sutProvider.GetDependency().DidNotReceiveWithAnyArgs() + .CreateManyAsync(Arg.Any>(), Arg.Any(), Arg.Any()); + } + + [Theory] + [BitAutoData] + public async void CreateServiceAccountGrantedPolicies_Success( + SutProvider sutProvider, + Guid id, + ServiceAccount serviceAccount, + ServiceAccountProjectAccessPolicy data, + List request) + { + sutProvider.GetDependency().GetByIdAsync(default).ReturnsForAnyArgs(serviceAccount); + sutProvider.GetDependency().AccessSecretsManager(default).ReturnsForAnyArgs(true); + sutProvider.GetDependency().GetProperUserId(default).ReturnsForAnyArgs(Guid.NewGuid()); + sutProvider.GetDependency() + .CreateManyAsync(default, default, default) + .ReturnsForAnyArgs(new List { data }); + + await sutProvider.Sut.CreateServiceAccountGrantedPoliciesAsync(id, request); + + await sutProvider.GetDependency().Received(1) + .CreateManyAsync(Arg.Any>(), Arg.Any(), Arg.Any()); } [Theory] @@ -459,8 +650,9 @@ public class AccessPoliciesControllerTests ServiceAccount mockServiceAccount) { SetupPermission(sutProvider, permissionType, id); - sutProvider.GetDependency().GetManyByOrganizationIdWriteAccessAsync(default, default, default) - .ReturnsForAnyArgs(new List { mockServiceAccount }); + sutProvider.GetDependency() + .GetManyByOrganizationIdWriteAccessAsync(default, default, default) + .ReturnsForAnyArgs(new List { mockServiceAccount }); var result = await sutProvider.Sut.GetServiceAccountsPotentialGranteesAsync(id); @@ -471,4 +663,63 @@ public class AccessPoliciesControllerTests Assert.NotEmpty(result.Data); } + + [Theory] + [BitAutoData(PermissionType.RunAsAdmin)] + [BitAutoData(PermissionType.RunAsUserWithPermission)] + public async void GetProjectPotentialGrantees_ReturnsEmptyList( + PermissionType permissionType, + SutProvider sutProvider, + Guid id) + { + SetupPermission(sutProvider, permissionType, id); + var result = await sutProvider.Sut.GetProjectPotentialGranteesAsync(id); + + await sutProvider.GetDependency().Received(1) + .GetManyByOrganizationIdWriteAccessAsync(Arg.Is(AssertHelper.AssertPropertyEqual(id)), + Arg.Is(AssertHelper.AssertPropertyEqual(id)), + Arg.Any()); + + Assert.Empty(result.Data); + } + + [Theory] + [BitAutoData] + public async void GetProjectPotentialGrantees_UserWithoutPermission_Throws( + SutProvider sutProvider, + Guid id) + { + sutProvider.GetDependency().OrganizationAdmin(id).Returns(false); + sutProvider.GetDependency().AccessSecretsManager(default).ReturnsForAnyArgs(false); + sutProvider.GetDependency().GetProperUserId(default).ReturnsForAnyArgs(Guid.NewGuid()); + + await Assert.ThrowsAsync(() => sutProvider.Sut.GetProjectPotentialGranteesAsync(id)); + + await sutProvider.GetDependency().DidNotReceiveWithAnyArgs() + .GetManyByOrganizationIdWriteAccessAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Theory] + [BitAutoData(PermissionType.RunAsAdmin)] + [BitAutoData(PermissionType.RunAsUserWithPermission)] + public async void GetProjectPotentialGrantees_Success( + PermissionType permissionType, + SutProvider sutProvider, + Guid id, + Project mockProject) + { + SetupPermission(sutProvider, permissionType, id); + sutProvider.GetDependency() + .GetManyByOrganizationIdWriteAccessAsync(default, default, default) + .ReturnsForAnyArgs(new List { mockProject }); + + var result = await sutProvider.Sut.GetProjectPotentialGranteesAsync(id); + + await sutProvider.GetDependency().Received(1) + .GetManyByOrganizationIdWriteAccessAsync(Arg.Is(AssertHelper.AssertPropertyEqual(id)), + Arg.Is(AssertHelper.AssertPropertyEqual(id)), + Arg.Any()); + + Assert.NotEmpty(result.Data); + } }