mirror of
https://github.com/bitwarden/server.git
synced 2024-11-21 12:05:42 +01:00
[SM-788] Extract authorization from secret delete command (#3003)
* Extract authorization from secret delete command
This commit is contained in:
parent
c1723d9e90
commit
d020c49c0e
@ -41,6 +41,9 @@ public class SecretAuthorizationHandler : AuthorizationHandler<SecretOperationRe
|
||||
case not null when requirement == SecretOperations.Update:
|
||||
await CanUpdateSecretAsync(context, requirement, resource);
|
||||
break;
|
||||
case not null when requirement == SecretOperations.Delete:
|
||||
await CanDeleteSecretAsync(context, requirement, resource);
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentException("Unsupported operation requirement type provided.", nameof(requirement));
|
||||
}
|
||||
@ -120,4 +123,22 @@ public class SecretAuthorizationHandler : AuthorizationHandler<SecretOperationRe
|
||||
context.Succeed(requirement);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CanDeleteSecretAsync(AuthorizationHandlerContext context,
|
||||
SecretOperationRequirement requirement, Secret resource)
|
||||
{
|
||||
var (accessClient, userId) = await _accessClientQuery.GetAccessClientAsync(context.User, resource.OrganizationId);
|
||||
|
||||
if (accessClient == AccessClientType.ServiceAccount)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var access = await _secretRepository.AccessToSecretAsync(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.Secrets.Interfaces;
|
||||
using Bit.Core.SecretsManager.Commands.Secrets.Interfaces;
|
||||
using Bit.Core.SecretsManager.Entities;
|
||||
using Bit.Core.SecretsManager.Repositories;
|
||||
|
||||
@ -9,73 +6,16 @@ namespace Bit.Commercial.Core.SecretsManager.Commands.Secrets;
|
||||
|
||||
public class DeleteSecretCommand : IDeleteSecretCommand
|
||||
{
|
||||
private readonly ICurrentContext _currentContext;
|
||||
private readonly ISecretRepository _secretRepository;
|
||||
private readonly IProjectRepository _projectRepository;
|
||||
|
||||
public DeleteSecretCommand(ISecretRepository secretRepository, IProjectRepository projectRepository, ICurrentContext currentContext)
|
||||
public DeleteSecretCommand(ISecretRepository secretRepository)
|
||||
{
|
||||
_currentContext = currentContext;
|
||||
_secretRepository = secretRepository;
|
||||
_projectRepository = projectRepository;
|
||||
}
|
||||
|
||||
public async Task<List<Tuple<Secret, string>>> DeleteSecrets(List<Guid> ids, Guid userId)
|
||||
public async Task DeleteSecrets(IEnumerable<Secret> secrets)
|
||||
{
|
||||
var secrets = (await _secretRepository.GetManyByIds(ids)).ToList();
|
||||
|
||||
if (secrets.Any() != true)
|
||||
{
|
||||
throw new NotFoundException();
|
||||
}
|
||||
|
||||
// Ensure all secrets belongs to the same organization
|
||||
var organizationId = secrets.First().OrganizationId;
|
||||
if (secrets.Any(secret => secret.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<Secret, string>>();
|
||||
var deleteIds = new List<Guid>();
|
||||
|
||||
foreach (var secret in secrets)
|
||||
{
|
||||
var hasAccess = orgAdmin;
|
||||
|
||||
if (secret.Projects != null && secret.Projects?.Count > 0)
|
||||
{
|
||||
var projectId = secret.Projects.First().Id;
|
||||
hasAccess = (await _projectRepository.AccessToProjectAsync(projectId, userId, accessClient)).Write;
|
||||
}
|
||||
|
||||
if (!hasAccess || accessClient == AccessClientType.ServiceAccount)
|
||||
{
|
||||
results.Add(new Tuple<Secret, string>(secret, "access denied"));
|
||||
}
|
||||
else
|
||||
{
|
||||
deleteIds.Add(secret.Id);
|
||||
results.Add(new Tuple<Secret, string>(secret, ""));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
if (deleteIds.Count > 0)
|
||||
{
|
||||
await _secretRepository.SoftDeleteManyByIdAsync(deleteIds);
|
||||
}
|
||||
|
||||
return results;
|
||||
await _secretRepository.SoftDeleteManyByIdAsync(secrets.Select(s => s.Id));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -374,4 +374,83 @@ public class SecretAuthorizationHandlerTests
|
||||
|
||||
Assert.True(authzContext.HasSucceeded);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task CanDeleteSecret_AccessToSecretsManagerFalse_DoesNotSucceed(
|
||||
SutProvider<SecretAuthorizationHandler> sutProvider, Secret secret,
|
||||
ClaimsPrincipal claimsPrincipal)
|
||||
{
|
||||
var requirement = SecretOperations.Delete;
|
||||
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(secret.OrganizationId)
|
||||
.Returns(false);
|
||||
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
|
||||
claimsPrincipal, secret);
|
||||
|
||||
await sutProvider.Sut.HandleAsync(authzContext);
|
||||
|
||||
Assert.False(authzContext.HasSucceeded);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task CanDeleteSecret_NullResource_DoesNotSucceed(
|
||||
SutProvider<SecretAuthorizationHandler> sutProvider, Secret secret,
|
||||
ClaimsPrincipal claimsPrincipal,
|
||||
Guid userId)
|
||||
{
|
||||
var requirement = SecretOperations.Delete;
|
||||
SetupPermission(sutProvider, PermissionType.RunAsAdmin, secret.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 CanDeleteSecret_ServiceAccountClient_DoesNotSucceed(
|
||||
SutProvider<SecretAuthorizationHandler> sutProvider, Secret secret, Guid userId,
|
||||
ClaimsPrincipal claimsPrincipal)
|
||||
{
|
||||
var requirement = SecretOperations.Delete;
|
||||
SetupPermission(sutProvider, PermissionType.RunAsUserWithPermission, secret.OrganizationId, userId,
|
||||
AccessClientType.ServiceAccount);
|
||||
sutProvider.GetDependency<ISecretRepository>()
|
||||
.AccessToSecretAsync(secret.Id, userId, Arg.Any<AccessClientType>())
|
||||
.Returns((true, true));
|
||||
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
|
||||
claimsPrincipal, secret);
|
||||
|
||||
await sutProvider.Sut.HandleAsync(authzContext);
|
||||
|
||||
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)]
|
||||
public async Task CanDeleteProject_AccessCheck(PermissionType permissionType, bool read, bool write,
|
||||
bool expected,
|
||||
SutProvider<SecretAuthorizationHandler> sutProvider, Secret secret,
|
||||
ClaimsPrincipal claimsPrincipal,
|
||||
Guid userId)
|
||||
{
|
||||
var requirement = SecretOperations.Delete;
|
||||
SetupPermission(sutProvider, permissionType, secret.OrganizationId, userId);
|
||||
sutProvider.GetDependency<ISecretRepository>()
|
||||
.AccessToSecretAsync(secret.Id, userId, Arg.Any<AccessClientType>())
|
||||
.Returns((read, write));
|
||||
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
|
||||
claimsPrincipal, secret);
|
||||
|
||||
await sutProvider.Sut.HandleAsync(authzContext);
|
||||
|
||||
Assert.Equal(expected, authzContext.HasSucceeded);
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,4 @@
|
||||
using Bit.Commercial.Core.SecretsManager.Commands.Secrets;
|
||||
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;
|
||||
using Bit.Core.Test.SecretsManager.AutoFixture.ProjectsFixture;
|
||||
@ -20,75 +16,12 @@ public class DeleteSecretCommandTests
|
||||
{
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task DeleteSecrets_Throws_NotFoundException(List<Guid> data,
|
||||
SutProvider<DeleteSecretCommand> sutProvider)
|
||||
public async Task DeleteSecrets_Success(SutProvider<DeleteSecretCommand> sutProvider, List<Secret> data)
|
||||
{
|
||||
sutProvider.GetDependency<ISecretRepository>().GetManyByIds(data).Returns(new List<Secret>());
|
||||
|
||||
var exception = await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.DeleteSecrets(data, default));
|
||||
|
||||
await sutProvider.GetDependency<ISecretRepository>().DidNotReceiveWithAnyArgs().SoftDeleteManyByIdAsync(default);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async Task DeleteSecrets_OneIdNotFound_Throws_NotFoundException(List<Guid> data,
|
||||
SutProvider<DeleteSecretCommand> sutProvider)
|
||||
{
|
||||
var secret = new Secret()
|
||||
{
|
||||
Id = Guid.NewGuid()
|
||||
};
|
||||
sutProvider.GetDependency<ISecretRepository>().GetManyByIds(data).Returns(new List<Secret>() { secret });
|
||||
|
||||
var exception = await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.DeleteSecrets(data, default));
|
||||
|
||||
await sutProvider.GetDependency<ISecretRepository>().DidNotReceiveWithAnyArgs().SoftDeleteManyByIdAsync(default);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData(PermissionType.RunAsAdmin)]
|
||||
[BitAutoData(PermissionType.RunAsUserWithPermission)]
|
||||
public async Task DeleteSecrets_Success(PermissionType permissionType, List<Guid> data,
|
||||
SutProvider<DeleteSecretCommand> sutProvider, Guid userId, Guid organizationId, Project mockProject)
|
||||
{
|
||||
List<Project> projects = null;
|
||||
|
||||
if (permissionType == PermissionType.RunAsAdmin)
|
||||
{
|
||||
sutProvider.GetDependency<ICurrentContext>().OrganizationAdmin(organizationId).Returns(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
sutProvider.GetDependency<ICurrentContext>().OrganizationAdmin(organizationId).Returns(false);
|
||||
sutProvider.GetDependency<IProjectRepository>().AccessToProjectAsync(mockProject.Id, userId, AccessClientType.User)
|
||||
.Returns((true, true));
|
||||
projects = new List<Project>() { mockProject };
|
||||
}
|
||||
|
||||
|
||||
var secrets = new List<Secret>();
|
||||
foreach (Guid id in data)
|
||||
{
|
||||
var secret = new Secret()
|
||||
{
|
||||
Id = id,
|
||||
OrganizationId = organizationId,
|
||||
Projects = projects
|
||||
};
|
||||
secrets.Add(secret);
|
||||
}
|
||||
|
||||
sutProvider.GetDependency<ISecretRepository>().GetManyByIds(data).Returns(secrets);
|
||||
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(default).ReturnsForAnyArgs(true);
|
||||
|
||||
var results = await sutProvider.Sut.DeleteSecrets(data, userId);
|
||||
await sutProvider.GetDependency<ISecretRepository>().Received(1).SoftDeleteManyByIdAsync(Arg.Is(AssertHelper.AssertPropertyEqual(data)));
|
||||
|
||||
foreach (var result in results)
|
||||
{
|
||||
Assert.Equal("", result.Item2);
|
||||
}
|
||||
await sutProvider.Sut.DeleteSecrets(data);
|
||||
await sutProvider.GetDependency<ISecretRepository>()
|
||||
.Received(1)
|
||||
.SoftDeleteManyByIdAsync(Arg.Is(AssertHelper.AssertPropertyEqual(data.Select(d => d.Id))));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -8,6 +8,7 @@ using Bit.Core.Identity;
|
||||
using Bit.Core.Repositories;
|
||||
using Bit.Core.SecretsManager.AuthorizationRequirements;
|
||||
using Bit.Core.SecretsManager.Commands.Secrets.Interfaces;
|
||||
using Bit.Core.SecretsManager.Entities;
|
||||
using Bit.Core.SecretsManager.Repositories;
|
||||
using Bit.Core.Services;
|
||||
using Bit.Core.Tools.Enums;
|
||||
@ -170,9 +171,40 @@ public class SecretsController : Controller
|
||||
[HttpPost("secrets/delete")]
|
||||
public async Task<ListResponseModel<BulkDeleteResponseModel>> BulkDeleteAsync([FromBody] List<Guid> ids)
|
||||
{
|
||||
var userId = _userService.GetProperUserId(User).Value;
|
||||
var results = await _deleteSecretCommand.DeleteSecrets(ids, userId);
|
||||
var responses = results.Select(r => new BulkDeleteResponseModel(r.Item1.Id, r.Item2));
|
||||
var secrets = (await _secretRepository.GetManyByIds(ids)).ToList();
|
||||
if (!secrets.Any() || secrets.Count != ids.Count)
|
||||
{
|
||||
throw new NotFoundException();
|
||||
}
|
||||
|
||||
// Ensure all secrets belong to the same organization.
|
||||
var organizationId = secrets.First().OrganizationId;
|
||||
if (secrets.Any(secret => secret.OrganizationId != organizationId) ||
|
||||
!_currentContext.AccessSecretsManager(organizationId))
|
||||
{
|
||||
throw new NotFoundException();
|
||||
}
|
||||
|
||||
var secretsToDelete = new List<Secret>();
|
||||
var results = new List<(Secret Secret, string Error)>();
|
||||
|
||||
foreach (var secret in secrets)
|
||||
{
|
||||
var authorizationResult =
|
||||
await _authorizationService.AuthorizeAsync(User, secret, SecretOperations.Delete);
|
||||
if (authorizationResult.Succeeded)
|
||||
{
|
||||
secretsToDelete.Add(secret);
|
||||
results.Add((secret, ""));
|
||||
}
|
||||
else
|
||||
{
|
||||
results.Add((secret, "access denied"));
|
||||
}
|
||||
}
|
||||
|
||||
await _deleteSecretCommand.DeleteSecrets(secretsToDelete);
|
||||
var responses = results.Select(r => new BulkDeleteResponseModel(r.Secret.Id, r.Error));
|
||||
return new ListResponseModel<BulkDeleteResponseModel>(responses);
|
||||
}
|
||||
}
|
||||
|
@ -10,4 +10,5 @@ public static class SecretOperations
|
||||
{
|
||||
public static readonly SecretOperationRequirement Create = new() { Name = nameof(Create) };
|
||||
public static readonly SecretOperationRequirement Update = new() { Name = nameof(Update) };
|
||||
public static readonly SecretOperationRequirement Delete = new() { Name = nameof(Delete) };
|
||||
}
|
||||
|
@ -4,6 +4,6 @@ namespace Bit.Core.SecretsManager.Commands.Secrets.Interfaces;
|
||||
|
||||
public interface IDeleteSecretCommand
|
||||
{
|
||||
Task<List<Tuple<Secret, string>>> DeleteSecrets(List<Guid> ids, Guid userId);
|
||||
Task DeleteSecrets(IEnumerable<Secret> secrets);
|
||||
}
|
||||
|
||||
|
@ -644,10 +644,28 @@ public class SecretsControllerTests : IClassFixture<ApiApplicationFactory>, IAsy
|
||||
});
|
||||
var secretIds = new[] { secret.Id };
|
||||
|
||||
var response = await _client.PostAsJsonAsync($"/secrets/{org.Id}/delete", secretIds);
|
||||
var response = await _client.PostAsJsonAsync($"/secrets/delete", secretIds);
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Delete_MissingAccessPolicy_AccessDenied()
|
||||
{
|
||||
var (org, _) = await _organizationHelper.Initialize(true, true);
|
||||
var (email, _) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true);
|
||||
await LoginAsync(email);
|
||||
|
||||
var (_, secretIds) = await CreateSecretsAsync(org.Id, 3);
|
||||
|
||||
var response = await _client.PostAsync("/secrets/delete", JsonContent.Create(secretIds));
|
||||
|
||||
var results = await response.Content.ReadFromJsonAsync<ListResponseModel<BulkDeleteResponseModel>>();
|
||||
Assert.NotNull(results);
|
||||
Assert.Equal(secretIds.OrderBy(x => x),
|
||||
results!.Data.Select(x => x.Id).OrderBy(x => x));
|
||||
Assert.All(results.Data, item => Assert.Equal("access denied", item.Error));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(PermissionType.RunAsAdmin)]
|
||||
[InlineData(PermissionType.RunAsUserWithPermission)]
|
||||
@ -656,12 +674,7 @@ public class SecretsControllerTests : IClassFixture<ApiApplicationFactory>, IAsy
|
||||
var (org, _) = await _organizationHelper.Initialize(true, true);
|
||||
await LoginAsync(_email);
|
||||
|
||||
var project = await _projectRepository.CreateAsync(new Project()
|
||||
{
|
||||
Id = new Guid(),
|
||||
OrganizationId = org.Id,
|
||||
Name = _mockEncryptedString
|
||||
});
|
||||
var (project, secretIds) = await CreateSecretsAsync(org.Id, 3);
|
||||
|
||||
if (permissionType == PermissionType.RunAsUserWithPermission)
|
||||
{
|
||||
@ -678,21 +691,6 @@ public class SecretsControllerTests : IClassFixture<ApiApplicationFactory>, IAsy
|
||||
await _accessPolicyRepository.CreateManyAsync(accessPolicies);
|
||||
}
|
||||
|
||||
|
||||
var secretIds = new List<Guid>();
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
var secret = await _secretRepository.CreateAsync(new Secret
|
||||
{
|
||||
OrganizationId = org.Id,
|
||||
Key = _mockEncryptedString,
|
||||
Value = _mockEncryptedString,
|
||||
Note = _mockEncryptedString,
|
||||
Projects = new List<Project>() { project }
|
||||
});
|
||||
secretIds.Add(secret.Id);
|
||||
}
|
||||
|
||||
var response = await _client.PostAsJsonAsync($"/secrets/delete", secretIds);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
@ -710,4 +708,30 @@ public class SecretsControllerTests : IClassFixture<ApiApplicationFactory>, IAsy
|
||||
var secrets = await _secretRepository.GetManyByIds(secretIds);
|
||||
Assert.Empty(secrets);
|
||||
}
|
||||
|
||||
private async Task<(Project Project, List<Guid> secretIds)> CreateSecretsAsync(Guid orgId, int numberToCreate = 3)
|
||||
{
|
||||
var project = await _projectRepository.CreateAsync(new Project
|
||||
{
|
||||
Id = new Guid(),
|
||||
OrganizationId = orgId,
|
||||
Name = _mockEncryptedString
|
||||
});
|
||||
|
||||
var secretIds = new List<Guid>();
|
||||
for (var i = 0; i < numberToCreate; i++)
|
||||
{
|
||||
var secret = await _secretRepository.CreateAsync(new Secret
|
||||
{
|
||||
OrganizationId = orgId,
|
||||
Key = _mockEncryptedString,
|
||||
Value = _mockEncryptedString,
|
||||
Note = _mockEncryptedString,
|
||||
Projects = new List<Project>() { project }
|
||||
});
|
||||
secretIds.Add(secret.Id);
|
||||
}
|
||||
|
||||
return (project, secretIds);
|
||||
}
|
||||
}
|
||||
|
@ -244,45 +244,106 @@ public class SecretsControllerTests
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData(PermissionType.RunAsAdmin)]
|
||||
[BitAutoData(PermissionType.RunAsUserWithPermission)]
|
||||
public async void BulkDeleteSecret_Success(PermissionType permissionType, SutProvider<SecretsController> sutProvider, List<Secret> data, Guid organizationId, Guid userId, Project mockProject)
|
||||
[BitAutoData]
|
||||
public async void BulkDelete_NoSecretsFound_ThrowsNotFound(SutProvider<SecretsController> sutProvider, List<Secret> data)
|
||||
{
|
||||
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
|
||||
|
||||
if (permissionType == PermissionType.RunAsAdmin)
|
||||
{
|
||||
sutProvider.GetDependency<ICurrentContext>().OrganizationAdmin(organizationId).Returns(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
data.FirstOrDefault().Projects = new List<Project>() { mockProject };
|
||||
sutProvider.GetDependency<ICurrentContext>().OrganizationAdmin(organizationId).Returns(false);
|
||||
sutProvider.GetDependency<IProjectRepository>().AccessToProjectAsync(default, default, default)
|
||||
.Returns((true, true));
|
||||
}
|
||||
|
||||
|
||||
var ids = data.Select(secret => secret.Id).ToList();
|
||||
var mockResult = new List<Tuple<Secret, string>>();
|
||||
|
||||
foreach (var secret in data)
|
||||
{
|
||||
mockResult.Add(new Tuple<Secret, string>(secret, ""));
|
||||
}
|
||||
sutProvider.GetDependency<IDeleteSecretCommand>().DeleteSecrets(ids, userId).ReturnsForAnyArgs(mockResult);
|
||||
|
||||
var results = await sutProvider.Sut.BulkDeleteAsync(ids);
|
||||
await sutProvider.GetDependency<IDeleteSecretCommand>().Received(1)
|
||||
.DeleteSecrets(Arg.Is(ids), userId);
|
||||
Assert.Equal(data.Count, results.Data.Count());
|
||||
var ids = data.Select(s => s.Id).ToList();
|
||||
sutProvider.GetDependency<ISecretRepository>().GetManyByIds(Arg.Is(ids)).ReturnsForAnyArgs(new List<Secret>());
|
||||
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.BulkDeleteAsync(ids));
|
||||
await sutProvider.GetDependency<IDeleteSecretCommand>().DidNotReceiveWithAnyArgs().DeleteSecrets(Arg.Any<List<Secret>>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async void BulkDeleteSecret_NoGuids_ThrowsArgumentNullException(SutProvider<SecretsController> sutProvider)
|
||||
public async void BulkDelete_SecretsFoundMisMatch_ThrowsNotFound(SutProvider<SecretsController> sutProvider, List<Secret> data, Secret mockSecret)
|
||||
{
|
||||
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(new Guid());
|
||||
await Assert.ThrowsAsync<ArgumentNullException>(() => sutProvider.Sut.BulkDeleteAsync(new List<Guid>()));
|
||||
data.Add(mockSecret);
|
||||
var ids = data.Select(s => s.Id).ToList();
|
||||
sutProvider.GetDependency<ISecretRepository>().GetManyByIds(Arg.Is(ids)).ReturnsForAnyArgs(new List<Secret> { mockSecret });
|
||||
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.BulkDeleteAsync(ids));
|
||||
await sutProvider.GetDependency<IDeleteSecretCommand>().DidNotReceiveWithAnyArgs().DeleteSecrets(Arg.Any<List<Secret>>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async void BulkDelete_OrganizationMistMatch_ThrowsNotFound(SutProvider<SecretsController> sutProvider, List<Secret> data)
|
||||
{
|
||||
var ids = data.Select(s => s.Id).ToList();
|
||||
sutProvider.GetDependency<ISecretRepository>().GetManyByIds(Arg.Is(ids)).ReturnsForAnyArgs(data);
|
||||
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.BulkDeleteAsync(ids));
|
||||
await sutProvider.GetDependency<IDeleteSecretCommand>().DidNotReceiveWithAnyArgs().DeleteSecrets(Arg.Any<List<Secret>>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async void BulkDelete_NoAccessToSecretsManager_ThrowsNotFound(SutProvider<SecretsController> sutProvider, List<Secret> data)
|
||||
{
|
||||
var ids = data.Select(s => s.Id).ToList();
|
||||
var organizationId = data.First().OrganizationId;
|
||||
foreach (var s in data)
|
||||
{
|
||||
s.OrganizationId = organizationId;
|
||||
}
|
||||
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(Arg.Is(organizationId)).ReturnsForAnyArgs(false);
|
||||
sutProvider.GetDependency<ISecretRepository>().GetManyByIds(Arg.Is(ids)).ReturnsForAnyArgs(data);
|
||||
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.BulkDeleteAsync(ids));
|
||||
await sutProvider.GetDependency<IDeleteSecretCommand>().DidNotReceiveWithAnyArgs().DeleteSecrets(Arg.Any<List<Secret>>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async void BulkDelete_ReturnsAccessDeniedForSecretsWithoutAccess_Success(SutProvider<SecretsController> sutProvider, List<Secret> data)
|
||||
{
|
||||
var ids = data.Select(s => s.Id).ToList();
|
||||
var organizationId = data.First().OrganizationId;
|
||||
foreach (var secret in data)
|
||||
{
|
||||
secret.OrganizationId = organizationId;
|
||||
sutProvider.GetDependency<IAuthorizationService>()
|
||||
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), secret,
|
||||
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<ISecretRepository>().GetManyByIds(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<IDeleteSecretCommand>().Received(1)
|
||||
.DeleteSecrets(Arg.Is(AssertHelper.AssertPropertyEqual(data)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[BitAutoData]
|
||||
public async void BulkDelete_Success(SutProvider<SecretsController> sutProvider, List<Secret> data)
|
||||
{
|
||||
var ids = data.Select(sa => sa.Id).ToList();
|
||||
var organizationId = data.First().OrganizationId;
|
||||
foreach (var secret in data)
|
||||
{
|
||||
secret.OrganizationId = organizationId;
|
||||
sutProvider.GetDependency<IAuthorizationService>()
|
||||
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), secret,
|
||||
Arg.Any<IEnumerable<IAuthorizationRequirement>>()).ReturnsForAnyArgs(AuthorizationResult.Success());
|
||||
}
|
||||
|
||||
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(Arg.Is(organizationId)).ReturnsForAnyArgs(true);
|
||||
sutProvider.GetDependency<ISecretRepository>().GetManyByIds(Arg.Is(ids)).ReturnsForAnyArgs(data);
|
||||
|
||||
var results = await sutProvider.Sut.BulkDeleteAsync(ids);
|
||||
|
||||
await sutProvider.GetDependency<IDeleteSecretCommand>().Received(1)
|
||||
.DeleteSecrets(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