mirror of
https://github.com/bitwarden/server.git
synced 2024-11-25 12:45:18 +01:00
[SM-787] Extract authorization from project delete command (#2987)
* Extract authorization from project delete command * Support service account write access --------- Co-authored-by: Matt Bishop <mbishop@bitwarden.com>
This commit is contained in:
parent
4dea376aa3
commit
b629c31de9
@ -39,6 +39,9 @@ public class ProjectAuthorizationHandler : AuthorizationHandler<ProjectOperation
|
||||
case not null when requirement == ProjectOperations.Update:
|
||||
await CanUpdateProjectAsync(context, requirement, resource);
|
||||
break;
|
||||
case not null when requirement == ProjectOperations.Delete:
|
||||
await CanDeleteProjectAsync(context, requirement, resource);
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentException("Unsupported operation requirement type provided.", nameof(requirement));
|
||||
}
|
||||
@ -75,4 +78,18 @@ public class ProjectAuthorizationHandler : AuthorizationHandler<ProjectOperation
|
||||
context.Succeed(requirement);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CanDeleteProjectAsync(AuthorizationHandlerContext context,
|
||||
ProjectOperationRequirement requirement, Project resource)
|
||||
{
|
||||
var (accessClient, userId) =
|
||||
await _accessClientQuery.GetAccessClientAsync(context.User, resource.OrganizationId);
|
||||
|
||||
var access = await _projectRepository.AccessToProjectAsync(resource.Id, userId, accessClient);
|
||||
|
||||
if (access.Write)
|
||||
{
|
||||
context.Succeed(requirement);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,7 +1,4 @@
|
||||
using Bit.Core.Context;
|
||||
using Bit.Core.Enums;
|
||||
using Bit.Core.Exceptions;
|
||||
using Bit.Core.SecretsManager.Commands.Projects.Interfaces;
|
||||
using Bit.Core.SecretsManager.Commands.Projects.Interfaces;
|
||||
using Bit.Core.SecretsManager.Entities;
|
||||
using Bit.Core.SecretsManager.Repositories;
|
||||
|
||||
@ -10,74 +7,14 @@ namespace Bit.Commercial.Core.SecretsManager.Commands.Projects;
|
||||
public class DeleteProjectCommand : IDeleteProjectCommand
|
||||
{
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
private readonly ICurrentContext _currentContext;
|
||||
private readonly ISecretRepository _secretRepository;
|
||||
|
||||
public DeleteProjectCommand(IProjectRepository projectRepository, ICurrentContext currentContext, ISecretRepository secretRepository)
|
||||
public DeleteProjectCommand(IProjectRepository projectRepository)
|
||||
{
|
||||
_projectRepository = projectRepository;
|
||||
_currentContext = currentContext;
|
||||
_secretRepository = secretRepository;
|
||||
}
|
||||
|
||||
public async Task<List<Tuple<Project, string>>> DeleteProjects(List<Guid> ids, Guid userId)
|
||||
public async Task DeleteProjects(IEnumerable<Project> projects)
|
||||
{
|
||||
if (ids.Any() != true || userId == new Guid())
|
||||
{
|
||||
throw new ArgumentNullException();
|
||||
}
|
||||
|
||||
var projects = (await _projectRepository.GetManyWithSecretsByIds(ids))?.ToList();
|
||||
|
||||
if (projects?.Any() != true || projects.Count != ids.Count)
|
||||
{
|
||||
throw new NotFoundException();
|
||||
}
|
||||
|
||||
// Ensure all projects belongs to the same organization
|
||||
var organizationId = projects.First().OrganizationId;
|
||||
if (projects.Any(p => p.OrganizationId != organizationId))
|
||||
{
|
||||
throw new BadRequestException();
|
||||
}
|
||||
|
||||
if (!_currentContext.AccessSecretsManager(organizationId))
|
||||
{
|
||||
throw new NotFoundException();
|
||||
}
|
||||
|
||||
var orgAdmin = await _currentContext.OrganizationAdmin(organizationId);
|
||||
var accessClient = AccessClientHelper.ToAccessClient(_currentContext.ClientType, orgAdmin);
|
||||
|
||||
var results = new List<Tuple<Project, string>>(projects.Count);
|
||||
var deleteIds = new List<Guid>();
|
||||
|
||||
foreach (var project in projects)
|
||||
{
|
||||
var access = await _projectRepository.AccessToProjectAsync(project.Id, userId, accessClient);
|
||||
if (!access.Write)
|
||||
{
|
||||
results.Add(new Tuple<Project, string>(project, "access denied"));
|
||||
}
|
||||
else
|
||||
{
|
||||
results.Add(new Tuple<Project, string>(project, ""));
|
||||
deleteIds.Add(project.Id);
|
||||
}
|
||||
}
|
||||
|
||||
if (deleteIds.Count > 0)
|
||||
{
|
||||
var secretIds = results.SelectMany(projTuple => projTuple.Item1?.Secrets?.Select(s => s.Id) ?? Array.Empty<Guid>()).ToList();
|
||||
|
||||
if (secretIds.Count > 0)
|
||||
{
|
||||
await _secretRepository.UpdateRevisionDates(secretIds);
|
||||
}
|
||||
|
||||
await _projectRepository.DeleteManyByIdAsync(deleteIds);
|
||||
}
|
||||
|
||||
return results;
|
||||
await _projectRepository.DeleteManyByIdAsync(projects.Select(p => p.Id));
|
||||
}
|
||||
}
|
||||
|
@ -60,16 +60,23 @@ public class ProjectRepository : Repository<Core.SecretsManager.Entities.Project
|
||||
|
||||
public async Task DeleteManyByIdAsync(IEnumerable<Guid> ids)
|
||||
{
|
||||
using (var scope = ServiceScopeFactory.CreateScope())
|
||||
using var scope = ServiceScopeFactory.CreateScope();
|
||||
var utcNow = DateTime.UtcNow;
|
||||
var dbContext = GetDatabaseContext(scope);
|
||||
var projects = dbContext.Project
|
||||
.Where(c => ids.Contains(c.Id))
|
||||
.Include(p => p.Secrets);
|
||||
await projects.ForEachAsync(project =>
|
||||
{
|
||||
var dbContext = GetDatabaseContext(scope);
|
||||
var projects = dbContext.Project.Where(c => ids.Contains(c.Id));
|
||||
await projects.ForEachAsync(project =>
|
||||
foreach (var projectSecret in project.Secrets)
|
||||
{
|
||||
dbContext.Remove(project);
|
||||
});
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
projectSecret.RevisionDate = utcNow;
|
||||
}
|
||||
|
||||
dbContext.Remove(project);
|
||||
});
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<Core.SecretsManager.Entities.Project>> GetManyWithSecretsByIds(IEnumerable<Guid> ids)
|
||||
|
@ -191,7 +191,7 @@ public class ProjectAuthorizationHandlerTests
|
||||
sutProvider.GetDependency<ICurrentContext>().OrganizationAdmin(project.OrganizationId).Returns(false);
|
||||
sutProvider.GetDependency<IAccessClientQuery>().GetAccessClientAsync(default, project.OrganizationId)
|
||||
.ReturnsForAnyArgs(
|
||||
(AccessClientType.ServiceAccount, new Guid()));
|
||||
(AccessClientType.Organization, new Guid()));
|
||||
var requirement = ProjectOperations.Update;
|
||||
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
|
||||
claimsPrincipal, project);
|
||||
@ -202,19 +202,43 @@ public class ProjectAuthorizationHandlerTests
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData(PermissionType.RunAsUserWithPermission, true, false)]
|
||||
[BitAutoData(PermissionType.RunAsUserWithPermission, false, false)]
|
||||
[BitAutoData(PermissionType.RunAsServiceAccountWithPermission, true, false)]
|
||||
[BitAutoData(PermissionType.RunAsServiceAccountWithPermission, false, false)]
|
||||
public async Task CanUpdateProject_ShouldNotSucceed(PermissionType permissionType, bool read, bool write,
|
||||
SutProvider<ProjectAuthorizationHandler> sutProvider, Project project, ClaimsPrincipal claimsPrincipal,
|
||||
[BitAutoData(PermissionType.RunAsAdmin, true, true, true)]
|
||||
[BitAutoData(PermissionType.RunAsUserWithPermission, false, false, false)]
|
||||
[BitAutoData(PermissionType.RunAsUserWithPermission, false, true, true)]
|
||||
[BitAutoData(PermissionType.RunAsUserWithPermission, true, false, false)]
|
||||
[BitAutoData(PermissionType.RunAsUserWithPermission, true, true, true)]
|
||||
[BitAutoData(PermissionType.RunAsServiceAccountWithPermission, false, false, false)]
|
||||
[BitAutoData(PermissionType.RunAsServiceAccountWithPermission, false, true, true)]
|
||||
[BitAutoData(PermissionType.RunAsServiceAccountWithPermission, true, false, false)]
|
||||
[BitAutoData(PermissionType.RunAsServiceAccountWithPermission, true, true, true)]
|
||||
public async Task CanUpdateProject_AccessCheck(PermissionType permissionType, bool read, bool write,
|
||||
bool expected,
|
||||
SutProvider<ProjectAuthorizationHandler> sutProvider, Project project,
|
||||
ClaimsPrincipal claimsPrincipal,
|
||||
Guid userId)
|
||||
{
|
||||
var requirement = ProjectOperations.Update;
|
||||
SetupPermission(sutProvider, permissionType, project.OrganizationId, userId);
|
||||
sutProvider.GetDependency<IProjectRepository>()
|
||||
.AccessToProjectAsync(project.Id, userId, Arg.Any<AccessClientType>())
|
||||
.Returns((read, write));
|
||||
var requirement = ProjectOperations.Update;
|
||||
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
|
||||
claimsPrincipal, project);
|
||||
|
||||
await sutProvider.Sut.HandleAsync(authzContext);
|
||||
|
||||
Assert.Equal(expected, authzContext.HasSucceeded);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task CanDeleteProject_AccessToSecretsManagerFalse_DoesNotSucceed(
|
||||
SutProvider<ProjectAuthorizationHandler> sutProvider, Project project,
|
||||
ClaimsPrincipal claimsPrincipal)
|
||||
{
|
||||
var requirement = ProjectOperations.Delete;
|
||||
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(project.OrganizationId)
|
||||
.Returns(false);
|
||||
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
|
||||
claimsPrincipal, project);
|
||||
|
||||
@ -224,26 +248,68 @@ public class ProjectAuthorizationHandlerTests
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData(PermissionType.RunAsAdmin, true, true)]
|
||||
[BitAutoData(PermissionType.RunAsAdmin, false, true)]
|
||||
[BitAutoData(PermissionType.RunAsUserWithPermission, true, true)]
|
||||
[BitAutoData(PermissionType.RunAsUserWithPermission, false, true)]
|
||||
[BitAutoData(PermissionType.RunAsServiceAccountWithPermission, true, true)]
|
||||
[BitAutoData(PermissionType.RunAsServiceAccountWithPermission, false, true)]
|
||||
public async Task CanUpdateProject_Success(PermissionType permissionType, bool read, bool write,
|
||||
SutProvider<ProjectAuthorizationHandler> sutProvider, Project project, ClaimsPrincipal claimsPrincipal,
|
||||
[BitAutoData]
|
||||
public async Task CanDeleteProject_NullResource_DoesNotSucceed(
|
||||
SutProvider<ProjectAuthorizationHandler> sutProvider, Project project,
|
||||
ClaimsPrincipal claimsPrincipal,
|
||||
Guid userId)
|
||||
{
|
||||
SetupPermission(sutProvider, permissionType, project.OrganizationId, userId);
|
||||
sutProvider.GetDependency<IProjectRepository>()
|
||||
.AccessToProjectAsync(project.Id, userId, Arg.Any<AccessClientType>())
|
||||
.Returns((read, write));
|
||||
var requirement = ProjectOperations.Update;
|
||||
var requirement = ProjectOperations.Delete;
|
||||
SetupPermission(sutProvider, PermissionType.RunAsAdmin, project.OrganizationId, userId);
|
||||
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
|
||||
claimsPrincipal, null);
|
||||
|
||||
await sutProvider.Sut.HandleAsync(authzContext);
|
||||
|
||||
Assert.False(authzContext.HasSucceeded);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task CanDeleteProject_NotSupportedClientType_DoesNotSucceed(
|
||||
SutProvider<ProjectAuthorizationHandler> sutProvider, Project project, ClaimsPrincipal claimsPrincipal)
|
||||
{
|
||||
var requirement = ProjectOperations.Delete;
|
||||
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(project.OrganizationId)
|
||||
.Returns(true);
|
||||
sutProvider.GetDependency<ICurrentContext>().OrganizationAdmin(project.OrganizationId).Returns(false);
|
||||
sutProvider.GetDependency<IAccessClientQuery>().GetAccessClientAsync(default, project.OrganizationId)
|
||||
.ReturnsForAnyArgs(
|
||||
(AccessClientType.Organization, new Guid()));
|
||||
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
|
||||
claimsPrincipal, project);
|
||||
|
||||
await sutProvider.Sut.HandleAsync(authzContext);
|
||||
|
||||
Assert.True(authzContext.HasSucceeded);
|
||||
Assert.False(authzContext.HasSucceeded);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData(PermissionType.RunAsAdmin, true, true, true)]
|
||||
[BitAutoData(PermissionType.RunAsUserWithPermission, false, false, false)]
|
||||
[BitAutoData(PermissionType.RunAsUserWithPermission, false, true, true)]
|
||||
[BitAutoData(PermissionType.RunAsUserWithPermission, true, false, false)]
|
||||
[BitAutoData(PermissionType.RunAsUserWithPermission, true, true, true)]
|
||||
[BitAutoData(PermissionType.RunAsServiceAccountWithPermission, false, false, false)]
|
||||
[BitAutoData(PermissionType.RunAsServiceAccountWithPermission, false, true, true)]
|
||||
[BitAutoData(PermissionType.RunAsServiceAccountWithPermission, true, false, false)]
|
||||
[BitAutoData(PermissionType.RunAsServiceAccountWithPermission, true, true, true)]
|
||||
public async Task CanDeleteProject_AccessCheck(PermissionType permissionType, bool read, bool write,
|
||||
bool expected,
|
||||
SutProvider<ProjectAuthorizationHandler> sutProvider, Project project,
|
||||
ClaimsPrincipal claimsPrincipal,
|
||||
Guid userId)
|
||||
{
|
||||
var requirement = ProjectOperations.Delete;
|
||||
SetupPermission(sutProvider, permissionType, project.OrganizationId, userId);
|
||||
sutProvider.GetDependency<IProjectRepository>()
|
||||
.AccessToProjectAsync(project.Id, userId, Arg.Any<AccessClientType>())
|
||||
.Returns((read, write));
|
||||
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
|
||||
claimsPrincipal, project);
|
||||
|
||||
await sutProvider.Sut.HandleAsync(authzContext);
|
||||
|
||||
Assert.Equal(expected, authzContext.HasSucceeded);
|
||||
}
|
||||
}
|
||||
|
@ -436,7 +436,7 @@ public class SecretAuthorizationHandlerTests
|
||||
[BitAutoData(PermissionType.RunAsServiceAccountWithPermission, false, true, true)]
|
||||
[BitAutoData(PermissionType.RunAsServiceAccountWithPermission, true, false, false)]
|
||||
[BitAutoData(PermissionType.RunAsServiceAccountWithPermission, true, true, true)]
|
||||
public async Task CanDeleteProject_AccessCheck(PermissionType permissionType, bool read, bool write,
|
||||
public async Task CanDeleteSecret_AccessCheck(PermissionType permissionType, bool read, bool write,
|
||||
bool expected,
|
||||
SutProvider<SecretAuthorizationHandler> sutProvider, Secret secret,
|
||||
ClaimsPrincipal claimsPrincipal,
|
||||
|
@ -1,114 +1,27 @@
|
||||
using Bit.Commercial.Core.SecretsManager.Commands.Projects;
|
||||
using Bit.Core.Context;
|
||||
using Bit.Core.Enums;
|
||||
using Bit.Core.Exceptions;
|
||||
using Bit.Core.Identity;
|
||||
using Bit.Core.SecretsManager.Entities;
|
||||
using Bit.Core.SecretsManager.Repositories;
|
||||
using Bit.Core.Test.SecretsManager.AutoFixture.ProjectsFixture;
|
||||
using Bit.Test.Common.AutoFixture;
|
||||
using Bit.Test.Common.AutoFixture.Attributes;
|
||||
using Bit.Test.Common.Helpers;
|
||||
using NSubstitute;
|
||||
using Xunit;
|
||||
|
||||
namespace Bit.Commercial.Core.Test.SecretsManager.Commands.Projects;
|
||||
|
||||
[SutProviderCustomize]
|
||||
[ProjectCustomize]
|
||||
public class DeleteProjectCommandTests
|
||||
{
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task DeleteProjects_Throws_NotFoundException(List<Guid> data, Guid userId,
|
||||
public async Task DeleteProjects_Success(List<Project> data,
|
||||
SutProvider<DeleteProjectCommand> sutProvider)
|
||||
{
|
||||
sutProvider.GetDependency<IProjectRepository>().GetManyWithSecretsByIds(data).Returns(new List<Project>());
|
||||
|
||||
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.DeleteProjects(data, userId));
|
||||
|
||||
await sutProvider.GetDependency<IProjectRepository>().DidNotReceiveWithAnyArgs().DeleteManyByIdAsync(default);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task Delete_OneIdNotFound_Throws_NotFoundException(List<Guid> data, Guid userId,
|
||||
SutProvider<DeleteProjectCommand> sutProvider)
|
||||
{
|
||||
var project = new Project()
|
||||
{
|
||||
Id = Guid.NewGuid()
|
||||
};
|
||||
sutProvider.GetDependency<IProjectRepository>().GetManyWithSecretsByIds(data).Returns(new List<Project>() { project });
|
||||
|
||||
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.DeleteProjects(data, userId));
|
||||
|
||||
await sutProvider.GetDependency<IProjectRepository>().DidNotReceiveWithAnyArgs().DeleteManyByIdAsync(default);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task DeleteSecrets_User_Success(List<Guid> data, Guid userId, Guid organizationId,
|
||||
SutProvider<DeleteProjectCommand> sutProvider)
|
||||
{
|
||||
var projects = data.Select(id => new Project { Id = id, OrganizationId = organizationId }).ToList();
|
||||
|
||||
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(organizationId).Returns(true);
|
||||
sutProvider.GetDependency<ICurrentContext>().ClientType = ClientType.User;
|
||||
sutProvider.GetDependency<IProjectRepository>().GetManyWithSecretsByIds(data).Returns(projects);
|
||||
sutProvider.GetDependency<IProjectRepository>().AccessToProjectAsync(Arg.Any<Guid>(), userId, AccessClientType.User)
|
||||
.Returns((true, true));
|
||||
|
||||
var results = await sutProvider.Sut.DeleteProjects(data, userId);
|
||||
|
||||
foreach (var result in results)
|
||||
{
|
||||
Assert.Equal("", result.Item2);
|
||||
}
|
||||
|
||||
await sutProvider.GetDependency<IProjectRepository>().Received(1).DeleteManyByIdAsync(Arg.Is<List<Guid>>(d => d.SequenceEqual(data)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task Delete_User_No_Permission(List<Guid> data, Guid userId, Guid organizationId,
|
||||
SutProvider<DeleteProjectCommand> sutProvider)
|
||||
{
|
||||
var projects = data.Select(id => new Project { Id = id, OrganizationId = organizationId }).ToList();
|
||||
|
||||
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(organizationId).Returns(true);
|
||||
sutProvider.GetDependency<ICurrentContext>().ClientType = ClientType.User;
|
||||
sutProvider.GetDependency<IProjectRepository>().GetManyWithSecretsByIds(data).Returns(projects);
|
||||
sutProvider.GetDependency<IProjectRepository>().AccessToProjectAsync(Arg.Any<Guid>(), userId, AccessClientType.User)
|
||||
.Returns((false, false));
|
||||
|
||||
var results = await sutProvider.Sut.DeleteProjects(data, userId);
|
||||
|
||||
foreach (var result in results)
|
||||
{
|
||||
Assert.Equal("access denied", result.Item2);
|
||||
}
|
||||
|
||||
await sutProvider.GetDependency<IProjectRepository>().DidNotReceiveWithAnyArgs().DeleteManyByIdAsync(default);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task Delete_OrganizationAdmin_Success(List<Guid> data, Guid userId, Guid organizationId,
|
||||
SutProvider<DeleteProjectCommand> sutProvider)
|
||||
{
|
||||
var projects = data.Select(id => new Project { Id = id, OrganizationId = organizationId }).ToList();
|
||||
|
||||
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(organizationId).Returns(true);
|
||||
sutProvider.GetDependency<ICurrentContext>().OrganizationAdmin(organizationId).Returns(true);
|
||||
sutProvider.GetDependency<IProjectRepository>().GetManyWithSecretsByIds(data).Returns(projects);
|
||||
sutProvider.GetDependency<IProjectRepository>().AccessToProjectAsync(Arg.Any<Guid>(), userId, AccessClientType.NoAccessCheck)
|
||||
.Returns((true, true));
|
||||
|
||||
|
||||
var results = await sutProvider.Sut.DeleteProjects(data, userId);
|
||||
|
||||
await sutProvider.GetDependency<IProjectRepository>().Received(1).DeleteManyByIdAsync(Arg.Is<List<Guid>>(d => d.SequenceEqual(data)));
|
||||
foreach (var result in results)
|
||||
{
|
||||
Assert.Equal("", result.Item2);
|
||||
}
|
||||
await sutProvider.Sut.DeleteProjects(data);
|
||||
await sutProvider.GetDependency<IProjectRepository>()
|
||||
.Received(1)
|
||||
.DeleteManyByIdAsync(Arg.Is(AssertHelper.AssertPropertyEqual(data.Select(d => d.Id))));
|
||||
}
|
||||
}
|
||||
|
@ -4,5 +4,5 @@ public enum PermissionType
|
||||
{
|
||||
RunAsAdmin,
|
||||
RunAsUserWithPermission,
|
||||
RunAsServiceAccountWithPermission
|
||||
RunAsServiceAccountWithPermission,
|
||||
}
|
||||
|
@ -6,6 +6,7 @@ using Bit.Core.Enums;
|
||||
using Bit.Core.Exceptions;
|
||||
using Bit.Core.SecretsManager.AuthorizationRequirements;
|
||||
using Bit.Core.SecretsManager.Commands.Projects.Interfaces;
|
||||
using Bit.Core.SecretsManager.Entities;
|
||||
using Bit.Core.SecretsManager.Repositories;
|
||||
using Bit.Core.Services;
|
||||
using Bit.Core.Utilities;
|
||||
@ -127,11 +128,44 @@ public class ProjectsController : Controller
|
||||
}
|
||||
|
||||
[HttpPost("projects/delete")]
|
||||
public async Task<ListResponseModel<BulkDeleteResponseModel>> BulkDeleteAsync([FromBody] List<Guid> ids)
|
||||
public async Task<ListResponseModel<BulkDeleteResponseModel>> BulkDeleteAsync(
|
||||
[FromBody] List<Guid> ids)
|
||||
{
|
||||
var userId = _userService.GetProperUserId(User).Value;
|
||||
var results = await _deleteProjectCommand.DeleteProjects(ids, userId);
|
||||
var responses = results.Select(r => new BulkDeleteResponseModel(r.Item1.Id, r.Item2));
|
||||
var projects = (await _projectRepository.GetManyWithSecretsByIds(ids)).ToList();
|
||||
if (!projects.Any() || projects.Count != ids.Count)
|
||||
{
|
||||
throw new NotFoundException();
|
||||
}
|
||||
|
||||
// Ensure all projects belongs to the same organization
|
||||
var organizationId = projects.First().OrganizationId;
|
||||
if (projects.Any(p => p.OrganizationId != organizationId) ||
|
||||
!_currentContext.AccessSecretsManager(organizationId))
|
||||
{
|
||||
throw new NotFoundException();
|
||||
}
|
||||
|
||||
var projectsToDelete = new List<Project>();
|
||||
var results = new List<(Project Project, string Error)>();
|
||||
|
||||
foreach (var project in projects)
|
||||
{
|
||||
var authorizationResult =
|
||||
await _authorizationService.AuthorizeAsync(User, project, ProjectOperations.Delete);
|
||||
if (authorizationResult.Succeeded)
|
||||
{
|
||||
projectsToDelete.Add(project);
|
||||
results.Add((project, ""));
|
||||
}
|
||||
else
|
||||
{
|
||||
results.Add((project, "access denied"));
|
||||
}
|
||||
}
|
||||
|
||||
await _deleteProjectCommand.DeleteProjects(projectsToDelete);
|
||||
|
||||
var responses = results.Select(r => new BulkDeleteResponseModel(r.Project.Id, r.Error));
|
||||
return new ListResponseModel<BulkDeleteResponseModel>(responses);
|
||||
}
|
||||
}
|
||||
|
@ -10,4 +10,5 @@ public static class ProjectOperations
|
||||
{
|
||||
public static readonly ProjectOperationRequirement Create = new() { Name = nameof(Create) };
|
||||
public static readonly ProjectOperationRequirement Update = new() { Name = nameof(Update) };
|
||||
public static readonly ProjectOperationRequirement Delete = new() { Name = nameof(Delete) };
|
||||
}
|
||||
|
@ -4,6 +4,6 @@ namespace Bit.Core.SecretsManager.Commands.Projects.Interfaces;
|
||||
|
||||
public interface IDeleteProjectCommand
|
||||
{
|
||||
Task<List<Tuple<Project, string>>> DeleteProjects(List<Guid> ids, Guid userId);
|
||||
Task DeleteProjects(IEnumerable<Project> projects);
|
||||
}
|
||||
|
||||
|
@ -248,26 +248,107 @@ public class ProjectsControllerTests
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async void BulkDeleteProjects_Success(SutProvider<ProjectsController> sutProvider, List<Project> data)
|
||||
public async void BulkDeleteProjects_NoProjectsFound_ThrowsNotFound(
|
||||
SutProvider<ProjectsController> sutProvider, List<Project> data)
|
||||
{
|
||||
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(Guid.NewGuid());
|
||||
var ids = data.Select(project => project.Id).ToList();
|
||||
var mockResult = data.Select(project => new Tuple<Project, string>(project, "")).ToList();
|
||||
|
||||
sutProvider.GetDependency<IDeleteProjectCommand>().DeleteProjects(ids, default).ReturnsForAnyArgs(mockResult);
|
||||
|
||||
var results = await sutProvider.Sut.BulkDeleteAsync(ids);
|
||||
await sutProvider.GetDependency<IDeleteProjectCommand>().Received(1)
|
||||
.DeleteProjects(Arg.Is(ids), Arg.Any<Guid>());
|
||||
Assert.Equal(data.Count, results.Data.Count());
|
||||
sutProvider.GetDependency<IProjectRepository>().GetManyWithSecretsByIds(Arg.Is(ids)).ReturnsForAnyArgs(new List<Project>());
|
||||
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.BulkDeleteAsync(ids));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async void BulkDeleteProjects_NoGuids_ThrowsArgumentNullException(
|
||||
SutProvider<ProjectsController> sutProvider)
|
||||
public async void BulkDeleteProjects_ProjectsFoundMisMatch_ThrowsNotFound(
|
||||
SutProvider<ProjectsController> sutProvider, List<Project> data, Project mockProject)
|
||||
{
|
||||
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(Guid.NewGuid());
|
||||
await Assert.ThrowsAsync<ArgumentNullException>(() => sutProvider.Sut.BulkDeleteAsync(new List<Guid>()));
|
||||
data.Add(mockProject);
|
||||
var ids = data.Select(project => project.Id).ToList();
|
||||
sutProvider.GetDependency<IProjectRepository>().GetManyWithSecretsByIds(Arg.Is(ids)).ReturnsForAnyArgs(new List<Project> { mockProject });
|
||||
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.BulkDeleteAsync(ids));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async void BulkDeleteProjects_OrganizationMistMatch_ThrowsNotFound(
|
||||
SutProvider<ProjectsController> sutProvider, List<Project> data)
|
||||
{
|
||||
|
||||
var ids = data.Select(project => project.Id).ToList();
|
||||
sutProvider.GetDependency<IProjectRepository>().GetManyWithSecretsByIds(Arg.Is(ids)).ReturnsForAnyArgs(data);
|
||||
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.BulkDeleteAsync(ids));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async void BulkDeleteProjects_NoAccessToSecretsManager_ThrowsNotFound(
|
||||
SutProvider<ProjectsController> sutProvider, List<Project> data)
|
||||
{
|
||||
|
||||
var ids = data.Select(project => project.Id).ToList();
|
||||
var organizationId = data.First().OrganizationId;
|
||||
foreach (var project in data)
|
||||
{
|
||||
project.OrganizationId = organizationId;
|
||||
}
|
||||
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(Arg.Is(organizationId)).ReturnsForAnyArgs(false);
|
||||
sutProvider.GetDependency<IProjectRepository>().GetManyWithSecretsByIds(Arg.Is(ids)).ReturnsForAnyArgs(data);
|
||||
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.BulkDeleteAsync(ids));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async void BulkDeleteProjects_ReturnsAccessDeniedForProjectsWithoutAccess_Success(
|
||||
SutProvider<ProjectsController> sutProvider, List<Project> data)
|
||||
{
|
||||
|
||||
var ids = data.Select(project => project.Id).ToList();
|
||||
var organizationId = data.First().OrganizationId;
|
||||
foreach (var project in data)
|
||||
{
|
||||
project.OrganizationId = organizationId;
|
||||
sutProvider.GetDependency<IAuthorizationService>()
|
||||
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), project,
|
||||
Arg.Any<IEnumerable<IAuthorizationRequirement>>()).ReturnsForAnyArgs(AuthorizationResult.Success());
|
||||
}
|
||||
sutProvider.GetDependency<IAuthorizationService>()
|
||||
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), data.First(),
|
||||
Arg.Any<IEnumerable<IAuthorizationRequirement>>()).Returns(AuthorizationResult.Failed());
|
||||
|
||||
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(Arg.Is(organizationId)).ReturnsForAnyArgs(true);
|
||||
sutProvider.GetDependency<IProjectRepository>().GetManyWithSecretsByIds(Arg.Is(ids)).ReturnsForAnyArgs(data);
|
||||
var results = await sutProvider.Sut.BulkDeleteAsync(ids);
|
||||
Assert.Equal(data.Count, results.Data.Count());
|
||||
Assert.Equal("access denied", results.Data.First().Error);
|
||||
|
||||
data.Remove(data.First());
|
||||
await sutProvider.GetDependency<IDeleteProjectCommand>().Received(1)
|
||||
.DeleteProjects(Arg.Is(AssertHelper.AssertPropertyEqual(data)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async void BulkDeleteProjects_Success(SutProvider<ProjectsController> sutProvider, List<Project> data)
|
||||
{
|
||||
var ids = data.Select(project => project.Id).ToList();
|
||||
var organizationId = data.First().OrganizationId;
|
||||
foreach (var project in data)
|
||||
{
|
||||
project.OrganizationId = organizationId;
|
||||
sutProvider.GetDependency<IAuthorizationService>()
|
||||
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), project,
|
||||
Arg.Any<IEnumerable<IAuthorizationRequirement>>()).ReturnsForAnyArgs(AuthorizationResult.Success());
|
||||
}
|
||||
|
||||
sutProvider.GetDependency<IProjectRepository>().GetManyWithSecretsByIds(Arg.Is(ids)).ReturnsForAnyArgs(data);
|
||||
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(Arg.Is(organizationId)).ReturnsForAnyArgs(true);
|
||||
|
||||
var results = await sutProvider.Sut.BulkDeleteAsync(ids);
|
||||
await sutProvider.GetDependency<IDeleteProjectCommand>().Received(1)
|
||||
.DeleteProjects(Arg.Is(AssertHelper.AssertPropertyEqual(data)));
|
||||
Assert.Equal(data.Count, results.Data.Count());
|
||||
foreach (var result in results.Data)
|
||||
{
|
||||
Assert.Null(result.Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user