1
0
mirror of https://github.com/bitwarden/server.git synced 2024-11-21 12:05:42 +01:00

[SM-1030] Cleanup old access policy management code (#4015)

* Remove access selector code

* Cleanup integration tests
This commit is contained in:
Thomas Avery 2024-05-06 14:56:58 -05:00 committed by GitHub
parent 3715d7d426
commit cd3a45c8c6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
26 changed files with 500 additions and 3026 deletions

View File

@ -1,267 +0,0 @@
using Bit.Core.AdminConsole.Repositories;
using Bit.Core.Context;
using Bit.Core.Enums;
using Bit.Core.Repositories;
using Bit.Core.SecretsManager.AuthorizationRequirements;
using Bit.Core.SecretsManager.Entities;
using Bit.Core.SecretsManager.Queries.Interfaces;
using Bit.Core.SecretsManager.Repositories;
using Microsoft.AspNetCore.Authorization;
namespace Bit.Commercial.Core.SecretsManager.AuthorizationHandlers.AccessPolicies;
public class AccessPolicyAuthorizationHandler : AuthorizationHandler<AccessPolicyOperationRequirement, BaseAccessPolicy>
{
private readonly ICurrentContext _currentContext;
private readonly IAccessClientQuery _accessClientQuery;
private readonly IGroupRepository _groupRepository;
private readonly IOrganizationUserRepository _organizationUserRepository;
private readonly IProjectRepository _projectRepository;
private readonly IServiceAccountRepository _serviceAccountRepository;
public AccessPolicyAuthorizationHandler(ICurrentContext currentContext,
IAccessClientQuery accessClientQuery,
IGroupRepository groupRepository,
IOrganizationUserRepository organizationUserRepository,
IProjectRepository projectRepository,
IServiceAccountRepository serviceAccountRepository)
{
_currentContext = currentContext;
_accessClientQuery = accessClientQuery;
_groupRepository = groupRepository;
_organizationUserRepository = organizationUserRepository;
_projectRepository = projectRepository;
_serviceAccountRepository = serviceAccountRepository;
}
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context,
AccessPolicyOperationRequirement requirement,
BaseAccessPolicy resource)
{
switch (requirement)
{
case not null when requirement == AccessPolicyOperations.Create:
await CanCreateAccessPolicyAsync(context, requirement, resource);
break;
case not null when requirement == AccessPolicyOperations.Update:
await CanUpdateAccessPolicyAsync(context, requirement, resource);
break;
case not null when requirement == AccessPolicyOperations.Delete:
await CanDeleteAccessPolicyAsync(context, requirement, resource);
break;
default:
throw new ArgumentException("Unsupported operation requirement type provided.",
nameof(requirement));
}
}
private async Task CanCreateAccessPolicyAsync(AuthorizationHandlerContext context,
AccessPolicyOperationRequirement requirement, BaseAccessPolicy resource)
{
switch (resource)
{
case UserProjectAccessPolicy ap:
await CanCreateAsync(context, requirement, ap);
break;
case GroupProjectAccessPolicy ap:
await CanCreateAsync(context, requirement, ap);
break;
case ServiceAccountProjectAccessPolicy ap:
await CanCreateAsync(context, requirement, ap);
break;
case UserServiceAccountAccessPolicy ap:
await CanCreateAsync(context, requirement, ap);
break;
case GroupServiceAccountAccessPolicy ap:
await CanCreateAsync(context, requirement, ap);
break;
default:
throw new ArgumentException("Unsupported access policy type provided.");
}
}
private async Task CanUpdateAccessPolicyAsync(AuthorizationHandlerContext context,
AccessPolicyOperationRequirement requirement, BaseAccessPolicy resource)
{
var access = await GetAccessPolicyAccessAsync(context, resource);
if (access.Write)
{
context.Succeed(requirement);
}
}
private async Task CanDeleteAccessPolicyAsync(AuthorizationHandlerContext context,
AccessPolicyOperationRequirement requirement, BaseAccessPolicy resource)
{
var access = await GetAccessPolicyAccessAsync(context, resource);
if (access.Write)
{
context.Succeed(requirement);
}
}
private async Task CanCreateAsync(AuthorizationHandlerContext context,
AccessPolicyOperationRequirement requirement, UserProjectAccessPolicy resource)
{
var user = await _organizationUserRepository.GetByIdAsync(resource.OrganizationUserId!.Value);
if (user.OrganizationId != resource.GrantedProject?.OrganizationId)
{
return;
}
var access = await GetAccessAsync(context, resource.GrantedProject!.OrganizationId, resource.GrantedProjectId);
if (access.Write)
{
context.Succeed(requirement);
}
}
private async Task CanCreateAsync(AuthorizationHandlerContext context,
AccessPolicyOperationRequirement requirement, GroupProjectAccessPolicy resource)
{
var group = await _groupRepository.GetByIdAsync(resource.GroupId!.Value);
if (group.OrganizationId != resource.GrantedProject?.OrganizationId)
{
return;
}
var access = await GetAccessAsync(context, resource.GrantedProject!.OrganizationId, resource.GrantedProjectId);
if (access.Write)
{
context.Succeed(requirement);
}
}
private async Task CanCreateAsync(AuthorizationHandlerContext context,
AccessPolicyOperationRequirement requirement, ServiceAccountProjectAccessPolicy resource)
{
var projectOrganizationId = resource.GrantedProject?.OrganizationId;
var serviceAccountOrgId = resource.ServiceAccount?.OrganizationId;
if (projectOrganizationId == null)
{
var project = await _projectRepository.GetByIdAsync(resource.GrantedProjectId!.Value);
projectOrganizationId = project?.OrganizationId;
}
if (serviceAccountOrgId == null)
{
var serviceAccount = await _serviceAccountRepository.GetByIdAsync(resource.ServiceAccountId!.Value);
serviceAccountOrgId = serviceAccount?.OrganizationId;
}
if (!serviceAccountOrgId.HasValue || !projectOrganizationId.HasValue ||
serviceAccountOrgId != projectOrganizationId)
{
return;
}
var access = await GetAccessAsync(context, projectOrganizationId.Value, resource.GrantedProjectId,
resource.ServiceAccountId);
if (access.Write)
{
context.Succeed(requirement);
}
}
private async Task CanCreateAsync(AuthorizationHandlerContext context,
AccessPolicyOperationRequirement requirement, UserServiceAccountAccessPolicy resource)
{
var user = await _organizationUserRepository.GetByIdAsync(resource.OrganizationUserId!.Value);
if (user.OrganizationId != resource.GrantedServiceAccount!.OrganizationId)
{
return;
}
var access = await GetAccessAsync(context, resource.GrantedServiceAccount!.OrganizationId,
serviceAccountIdToCheck: resource.GrantedServiceAccountId);
if (access.Write)
{
context.Succeed(requirement);
}
}
private async Task CanCreateAsync(AuthorizationHandlerContext context,
AccessPolicyOperationRequirement requirement, GroupServiceAccountAccessPolicy resource)
{
var group = await _groupRepository.GetByIdAsync(resource.GroupId!.Value);
if (group.OrganizationId != resource.GrantedServiceAccount!.OrganizationId)
{
return;
}
var access = await GetAccessAsync(context, resource.GrantedServiceAccount!.OrganizationId,
serviceAccountIdToCheck: resource.GrantedServiceAccountId);
if (access.Write)
{
context.Succeed(requirement);
}
}
private async Task<(bool Read, bool Write)> GetAccessPolicyAccessAsync(AuthorizationHandlerContext context,
BaseAccessPolicy resource) =>
resource switch
{
UserProjectAccessPolicy ap => await GetAccessAsync(context, ap.GrantedProject!.OrganizationId,
ap.GrantedProjectId),
GroupProjectAccessPolicy ap => await GetAccessAsync(context, ap.GrantedProject!.OrganizationId,
ap.GrantedProjectId),
ServiceAccountProjectAccessPolicy ap => await GetAccessAsync(context, ap.GrantedProject!.OrganizationId,
ap.GrantedProjectId),
UserServiceAccountAccessPolicy ap => await GetAccessAsync(context, ap.GrantedServiceAccount!.OrganizationId,
serviceAccountIdToCheck: ap.GrantedServiceAccountId),
GroupServiceAccountAccessPolicy ap => await GetAccessAsync(context,
ap.GrantedServiceAccount!.OrganizationId, serviceAccountIdToCheck: ap.GrantedServiceAccountId),
_ => throw new ArgumentException("Unsupported access policy type provided."),
};
private async Task<(bool Read, bool Write)> GetAccessAsync(AuthorizationHandlerContext context,
Guid organizationId, Guid? projectIdToCheck = null,
Guid? serviceAccountIdToCheck = null)
{
if (!_currentContext.AccessSecretsManager(organizationId))
{
return (false, false);
}
var (accessClient, userId) = await _accessClientQuery.GetAccessClientAsync(context.User, organizationId);
// Only users and admins should be able to manipulate access policies
if (accessClient != AccessClientType.User && accessClient != AccessClientType.NoAccessCheck)
{
return (false, false);
}
if (projectIdToCheck.HasValue && serviceAccountIdToCheck.HasValue)
{
var projectAccess =
await _projectRepository.AccessToProjectAsync(projectIdToCheck.Value, userId, accessClient);
var serviceAccountAccess =
await _serviceAccountRepository.AccessToServiceAccountAsync(serviceAccountIdToCheck.Value, userId,
accessClient);
return (
projectAccess.Read && serviceAccountAccess.Read,
projectAccess.Write && serviceAccountAccess.Write);
}
if (projectIdToCheck.HasValue)
{
return await _projectRepository.AccessToProjectAsync(projectIdToCheck.Value, userId, accessClient);
}
if (serviceAccountIdToCheck.HasValue)
{
return await _serviceAccountRepository.AccessToServiceAccountAsync(serviceAccountIdToCheck.Value, userId,
accessClient);
}
throw new ArgumentException("No ID to check provided.");
}
}

View File

@ -1,33 +0,0 @@
using Bit.Core.Exceptions;
using Bit.Core.SecretsManager.Commands.AccessPolicies.Interfaces;
using Bit.Core.SecretsManager.Entities;
using Bit.Core.SecretsManager.Repositories;
namespace Bit.Commercial.Core.SecretsManager.Commands.AccessPolicies;
public class CreateAccessPoliciesCommand : ICreateAccessPoliciesCommand
{
private readonly IAccessPolicyRepository _accessPolicyRepository;
public CreateAccessPoliciesCommand(IAccessPolicyRepository accessPolicyRepository)
{
_accessPolicyRepository = accessPolicyRepository;
}
public async Task<IEnumerable<BaseAccessPolicy>> CreateManyAsync(List<BaseAccessPolicy> accessPolicies)
{
await CheckAccessPoliciesDoNotExistAsync(accessPolicies);
return await _accessPolicyRepository.CreateManyAsync(accessPolicies);
}
private async Task CheckAccessPoliciesDoNotExistAsync(List<BaseAccessPolicy> accessPolicies)
{
foreach (var accessPolicy in accessPolicies)
{
if (await _accessPolicyRepository.AccessPolicyExists(accessPolicy))
{
throw new BadRequestException("Resource already exists");
}
}
}
}

View File

@ -1,19 +0,0 @@
using Bit.Core.SecretsManager.Commands.AccessPolicies.Interfaces;
using Bit.Core.SecretsManager.Repositories;
namespace Bit.Commercial.Core.SecretsManager.Commands.AccessPolicies;
public class DeleteAccessPolicyCommand : IDeleteAccessPolicyCommand
{
private readonly IAccessPolicyRepository _accessPolicyRepository;
public DeleteAccessPolicyCommand(IAccessPolicyRepository accessPolicyRepository)
{
_accessPolicyRepository = accessPolicyRepository;
}
public async Task DeleteAsync(Guid id)
{
await _accessPolicyRepository.DeleteAsync(id);
}
}

View File

@ -1,31 +0,0 @@
using Bit.Core.Exceptions;
using Bit.Core.SecretsManager.Commands.AccessPolicies.Interfaces;
using Bit.Core.SecretsManager.Entities;
using Bit.Core.SecretsManager.Repositories;
namespace Bit.Commercial.Core.SecretsManager.Commands.AccessPolicies;
public class UpdateAccessPolicyCommand : IUpdateAccessPolicyCommand
{
private readonly IAccessPolicyRepository _accessPolicyRepository;
public UpdateAccessPolicyCommand(IAccessPolicyRepository accessPolicyRepository)
{
_accessPolicyRepository = accessPolicyRepository;
}
public async Task<BaseAccessPolicy> UpdateAsync(Guid id, bool read, bool write)
{
var accessPolicy = await _accessPolicyRepository.GetByIdAsync(id);
if (accessPolicy == null)
{
throw new NotFoundException();
}
accessPolicy.Read = read;
accessPolicy.Write = write;
accessPolicy.RevisionDate = DateTime.UtcNow;
await _accessPolicyRepository.ReplaceAsync(accessPolicy);
return accessPolicy;
}
}

View File

@ -38,7 +38,6 @@ public static class SecretsManagerCollectionExtensions
services.AddScoped<IAuthorizationHandler, ProjectAuthorizationHandler>();
services.AddScoped<IAuthorizationHandler, SecretAuthorizationHandler>();
services.AddScoped<IAuthorizationHandler, ServiceAccountAuthorizationHandler>();
services.AddScoped<IAuthorizationHandler, AccessPolicyAuthorizationHandler>();
services.AddScoped<IAuthorizationHandler, ProjectPeopleAccessPoliciesAuthorizationHandler>();
services.AddScoped<IAuthorizationHandler, ServiceAccountPeopleAccessPoliciesAuthorizationHandler>();
services.AddScoped<IAuthorizationHandler, ServiceAccountGrantedPoliciesAuthorizationHandler>();
@ -62,9 +61,6 @@ public static class SecretsManagerCollectionExtensions
services.AddScoped<ICountNewServiceAccountSlotsRequiredQuery, CountNewServiceAccountSlotsRequiredQuery>();
services.AddScoped<IRevokeAccessTokensCommand, RevokeAccessTokensCommand>();
services.AddScoped<ICreateAccessTokenCommand, CreateAccessTokenCommand>();
services.AddScoped<ICreateAccessPoliciesCommand, CreateAccessPoliciesCommand>();
services.AddScoped<IUpdateAccessPolicyCommand, UpdateAccessPolicyCommand>();
services.AddScoped<IDeleteAccessPolicyCommand, DeleteAccessPolicyCommand>();
services.AddScoped<IImportCommand, ImportCommand>();
services.AddScoped<IEmptyTrashCommand, EmptyTrashCommand>();
services.AddScoped<IRestoreTrashCommand, RestoreTrashCommand>();

View File

@ -81,138 +81,6 @@ public class AccessPolicyRepository : BaseEntityFrameworkRepository, IAccessPoli
return baseAccessPolicies;
}
public async Task<bool> AccessPolicyExists(Core.SecretsManager.Entities.BaseAccessPolicy baseAccessPolicy)
{
using var scope = ServiceScopeFactory.CreateScope();
var dbContext = GetDatabaseContext(scope);
switch (baseAccessPolicy)
{
case Core.SecretsManager.Entities.UserProjectAccessPolicy accessPolicy:
{
var policy = await dbContext.UserProjectAccessPolicy
.Where(c => c.OrganizationUserId == accessPolicy.OrganizationUserId &&
c.GrantedProjectId == accessPolicy.GrantedProjectId)
.FirstOrDefaultAsync();
return policy != null;
}
case Core.SecretsManager.Entities.GroupProjectAccessPolicy accessPolicy:
{
var policy = await dbContext.GroupProjectAccessPolicy
.Where(c => c.GroupId == accessPolicy.GroupId &&
c.GrantedProjectId == accessPolicy.GrantedProjectId)
.FirstOrDefaultAsync();
return policy != null;
}
case Core.SecretsManager.Entities.ServiceAccountProjectAccessPolicy accessPolicy:
{
var policy = await dbContext.ServiceAccountProjectAccessPolicy
.Where(c => c.ServiceAccountId == accessPolicy.ServiceAccountId &&
c.GrantedProjectId == accessPolicy.GrantedProjectId)
.FirstOrDefaultAsync();
return policy != null;
}
case Core.SecretsManager.Entities.UserServiceAccountAccessPolicy accessPolicy:
{
var policy = await dbContext.UserServiceAccountAccessPolicy
.Where(c => c.OrganizationUserId == accessPolicy.OrganizationUserId &&
c.GrantedServiceAccountId == accessPolicy.GrantedServiceAccountId)
.FirstOrDefaultAsync();
return policy != null;
}
case Core.SecretsManager.Entities.GroupServiceAccountAccessPolicy accessPolicy:
{
var policy = await dbContext.GroupServiceAccountAccessPolicy
.Where(c => c.GroupId == accessPolicy.GroupId &&
c.GrantedServiceAccountId == accessPolicy.GrantedServiceAccountId)
.FirstOrDefaultAsync();
return policy != null;
}
default:
throw new ArgumentException("Unsupported access policy type provided.", nameof(baseAccessPolicy));
}
}
public async Task<Core.SecretsManager.Entities.BaseAccessPolicy?> GetByIdAsync(Guid id)
{
using var scope = ServiceScopeFactory.CreateScope();
var dbContext = GetDatabaseContext(scope);
var entity = await dbContext.AccessPolicies.Where(ap => ap.Id == id)
.Include(ap => ((UserProjectAccessPolicy)ap).OrganizationUser.User)
.Include(ap => ((UserProjectAccessPolicy)ap).GrantedProject)
.Include(ap => ((GroupProjectAccessPolicy)ap).Group)
.Include(ap => ((GroupProjectAccessPolicy)ap).GrantedProject)
.Include(ap => ((ServiceAccountProjectAccessPolicy)ap).ServiceAccount)
.Include(ap => ((ServiceAccountProjectAccessPolicy)ap).GrantedProject)
.Include(ap => ((UserServiceAccountAccessPolicy)ap).OrganizationUser.User)
.Include(ap => ((UserServiceAccountAccessPolicy)ap).GrantedServiceAccount)
.Include(ap => ((GroupServiceAccountAccessPolicy)ap).Group)
.Include(ap => ((GroupServiceAccountAccessPolicy)ap).GrantedServiceAccount)
.FirstOrDefaultAsync();
return entity == null ? null : MapToCore(entity);
}
public async Task ReplaceAsync(Core.SecretsManager.Entities.BaseAccessPolicy baseAccessPolicy)
{
using var scope = ServiceScopeFactory.CreateScope();
var dbContext = GetDatabaseContext(scope);
var entity = await dbContext.AccessPolicies.FindAsync(baseAccessPolicy.Id);
if (entity != null)
{
dbContext.AccessPolicies.Attach(entity);
entity.Write = baseAccessPolicy.Write;
entity.Read = baseAccessPolicy.Read;
entity.RevisionDate = baseAccessPolicy.RevisionDate;
await dbContext.SaveChangesAsync();
}
}
public async Task<IEnumerable<Core.SecretsManager.Entities.BaseAccessPolicy>> GetManyByGrantedProjectIdAsync(Guid id, Guid userId)
{
using var scope = ServiceScopeFactory.CreateScope();
var dbContext = GetDatabaseContext(scope);
var entities = await dbContext.AccessPolicies.Where(ap =>
((UserProjectAccessPolicy)ap).GrantedProjectId == id ||
((GroupProjectAccessPolicy)ap).GrantedProjectId == id ||
((ServiceAccountProjectAccessPolicy)ap).GrantedProjectId == id)
.Include(ap => ((UserProjectAccessPolicy)ap).OrganizationUser.User)
.Include(ap => ((GroupProjectAccessPolicy)ap).Group)
.Include(ap => ((ServiceAccountProjectAccessPolicy)ap).ServiceAccount)
.Select(ap => new
{
ap,
CurrentUserInGroup = ap is GroupProjectAccessPolicy &&
((GroupProjectAccessPolicy)ap).Group.GroupUsers.Any(g =>
g.OrganizationUser.User.Id == userId),
})
.ToListAsync();
return entities.Select(e => MapToCore(e.ap, e.CurrentUserInGroup));
}
public async Task DeleteAsync(Guid id)
{
using var scope = ServiceScopeFactory.CreateScope();
var dbContext = GetDatabaseContext(scope);
var entity = await dbContext.AccessPolicies.FindAsync(id);
if (entity != null)
{
if (entity is ServiceAccountProjectAccessPolicy serviceAccountProjectAccessPolicy)
{
var serviceAccount =
await dbContext.ServiceAccount.FindAsync(serviceAccountProjectAccessPolicy.ServiceAccountId);
if (serviceAccount != null)
{
serviceAccount.RevisionDate = DateTime.UtcNow;
}
}
dbContext.Remove(entity);
await dbContext.SaveChangesAsync();
}
}
public async Task<PeopleGrantees> GetPeopleGranteesAsync(Guid organizationId, Guid currentUserId)
{
using var scope = ServiceScopeFactory.CreateScope();

View File

@ -43,28 +43,6 @@ public class ServiceAccountRepository : Repository<Core.SecretsManager.Entities.
return Mapper.Map<List<Core.SecretsManager.Entities.ServiceAccount>>(serviceAccounts);
}
public async Task<bool> UserHasReadAccessToServiceAccount(Guid id, Guid userId)
{
using var scope = ServiceScopeFactory.CreateScope();
var dbContext = GetDatabaseContext(scope);
var query = dbContext.ServiceAccount
.Where(sa => sa.Id == id)
.Where(UserHasReadAccessToServiceAccount(userId));
return await query.AnyAsync();
}
public async Task<bool> UserHasWriteAccessToServiceAccount(Guid id, Guid userId)
{
using var scope = ServiceScopeFactory.CreateScope();
var dbContext = GetDatabaseContext(scope);
var query = dbContext.ServiceAccount
.Where(sa => sa.Id == id)
.Where(UserHasWriteAccessToServiceAccount(userId));
return await query.AnyAsync();
}
public async Task<IEnumerable<Core.SecretsManager.Entities.ServiceAccount>> GetManyByOrganizationIdWriteAccessAsync(Guid organizationId, Guid userId, AccessClientType accessType)
{
using var scope = ServiceScopeFactory.CreateScope();

View File

@ -1,763 +0,0 @@
using System.Reflection;
using System.Security.Claims;
using Bit.Commercial.Core.SecretsManager.AuthorizationHandlers.AccessPolicies;
using Bit.Commercial.Core.Test.SecretsManager.Enums;
using Bit.Core.AdminConsole.Entities;
using Bit.Core.AdminConsole.Repositories;
using Bit.Core.Context;
using Bit.Core.Entities;
using Bit.Core.Enums;
using Bit.Core.Repositories;
using Bit.Core.SecretsManager.AuthorizationRequirements;
using Bit.Core.SecretsManager.Entities;
using Bit.Core.SecretsManager.Queries.Interfaces;
using Bit.Core.SecretsManager.Repositories;
using Bit.Core.Test.SecretsManager.AutoFixture.ProjectsFixture;
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
using Microsoft.AspNetCore.Authorization;
using NSubstitute;
using Xunit;
namespace Bit.Commercial.Core.Test.SecretsManager.AuthorizationHandlers.AccessPolicies;
[SutProviderCustomize]
[ProjectCustomize]
public class AccessPolicyAuthorizationHandlerTests
{
private static void SetupCurrentUserPermission(SutProvider<AccessPolicyAuthorizationHandler> sutProvider,
PermissionType permissionType, Guid organizationId, Guid userId = new())
{
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(organizationId)
.Returns(true);
switch (permissionType)
{
case PermissionType.RunAsAdmin:
sutProvider.GetDependency<IAccessClientQuery>().GetAccessClientAsync(default, organizationId).ReturnsForAnyArgs(
(AccessClientType.NoAccessCheck, userId));
break;
case PermissionType.RunAsUserWithPermission:
sutProvider.GetDependency<IAccessClientQuery>().GetAccessClientAsync(default, organizationId).ReturnsForAnyArgs(
(AccessClientType.User, userId));
break;
default:
throw new ArgumentOutOfRangeException(nameof(permissionType), permissionType, null);
}
}
private static BaseAccessPolicy CreatePolicy(AccessPolicyType accessPolicyType, Project grantedProject,
ServiceAccount grantedServiceAccount, Guid? serviceAccountId = null)
{
switch (accessPolicyType)
{
case AccessPolicyType.UserProjectAccessPolicy:
return
new UserProjectAccessPolicy
{
Id = Guid.NewGuid(),
OrganizationUserId = Guid.NewGuid(),
Read = true,
Write = true,
GrantedProjectId = grantedProject.Id,
GrantedProject = grantedProject,
};
case AccessPolicyType.GroupProjectAccessPolicy:
return
new GroupProjectAccessPolicy
{
Id = Guid.NewGuid(),
GroupId = Guid.NewGuid(),
GrantedProjectId = grantedProject.Id,
Read = true,
Write = true,
GrantedProject = grantedProject,
};
case AccessPolicyType.ServiceAccountProjectAccessPolicy:
return new ServiceAccountProjectAccessPolicy
{
Id = Guid.NewGuid(),
ServiceAccountId = serviceAccountId,
GrantedProjectId = grantedProject.Id,
Read = true,
Write = true,
GrantedProject = grantedProject,
};
case AccessPolicyType.UserServiceAccountAccessPolicy:
return
new UserServiceAccountAccessPolicy
{
Id = Guid.NewGuid(),
OrganizationUserId = Guid.NewGuid(),
Read = true,
Write = true,
GrantedServiceAccountId = grantedServiceAccount.Id,
GrantedServiceAccount = grantedServiceAccount,
};
case AccessPolicyType.GroupServiceAccountAccessPolicy:
return new GroupServiceAccountAccessPolicy
{
Id = Guid.NewGuid(),
GroupId = Guid.NewGuid(),
GrantedServiceAccountId = grantedServiceAccount.Id,
GrantedServiceAccount = grantedServiceAccount,
Read = true,
Write = true,
};
default:
throw new ArgumentOutOfRangeException(nameof(accessPolicyType), accessPolicyType, null);
}
}
private static void SetupMockAccess(SutProvider<AccessPolicyAuthorizationHandler> sutProvider,
Guid userId, BaseAccessPolicy accessPolicy, bool read, bool write)
{
switch (accessPolicy)
{
case UserProjectAccessPolicy ap:
sutProvider.GetDependency<IProjectRepository>()
.AccessToProjectAsync(ap.GrantedProjectId!.Value, userId, Arg.Any<AccessClientType>())
.Returns((read, write));
break;
case GroupProjectAccessPolicy ap:
sutProvider.GetDependency<IProjectRepository>()
.AccessToProjectAsync(ap.GrantedProjectId!.Value, userId, Arg.Any<AccessClientType>())
.Returns((read, write));
break;
case UserServiceAccountAccessPolicy ap:
sutProvider.GetDependency<IServiceAccountRepository>()
.AccessToServiceAccountAsync(ap.GrantedServiceAccountId!.Value, userId, Arg.Any<AccessClientType>())
.Returns((read, write));
break;
case GroupServiceAccountAccessPolicy ap:
sutProvider.GetDependency<IServiceAccountRepository>()
.AccessToServiceAccountAsync(ap.GrantedServiceAccountId!.Value, userId, Arg.Any<AccessClientType>())
.Returns((read, write));
break;
case ServiceAccountProjectAccessPolicy ap:
sutProvider.GetDependency<IProjectRepository>()
.AccessToProjectAsync(ap.GrantedProjectId!.Value, userId, Arg.Any<AccessClientType>())
.Returns((read, write));
sutProvider.GetDependency<IServiceAccountRepository>()
.AccessToServiceAccountAsync(ap.ServiceAccountId!.Value, userId, Arg.Any<AccessClientType>())
.Returns((read, write));
break;
}
}
private static void SetupOrganizationMismatch(SutProvider<AccessPolicyAuthorizationHandler> sutProvider,
BaseAccessPolicy accessPolicy)
{
switch (accessPolicy)
{
case UserProjectAccessPolicy resource:
sutProvider.GetDependency<IOrganizationUserRepository>()
.GetByIdAsync(resource.OrganizationUserId!.Value)
.Returns(new OrganizationUser
{
Id = resource.OrganizationUserId!.Value,
OrganizationId = Guid.NewGuid()
});
break;
case GroupProjectAccessPolicy resource:
sutProvider.GetDependency<IGroupRepository>().GetByIdAsync(resource.GroupId!.Value)
.Returns(new Group { Id = resource.GroupId!.Value, OrganizationId = Guid.NewGuid() });
break;
case UserServiceAccountAccessPolicy resource:
sutProvider.GetDependency<IOrganizationUserRepository>()
.GetByIdAsync(resource.OrganizationUserId!.Value)
.Returns(new OrganizationUser
{
Id = resource.OrganizationUserId!.Value,
OrganizationId = Guid.NewGuid()
});
break;
case GroupServiceAccountAccessPolicy resource:
sutProvider.GetDependency<IGroupRepository>().GetByIdAsync(resource.GroupId!.Value)
.Returns(new Group { Id = resource.GroupId!.Value, OrganizationId = Guid.NewGuid() });
break;
default:
throw new ArgumentOutOfRangeException(nameof(accessPolicy), accessPolicy, null);
}
}
private static void SetupOrganizationMatch(SutProvider<AccessPolicyAuthorizationHandler> sutProvider,
BaseAccessPolicy accessPolicy, Guid organizationId)
{
switch (accessPolicy)
{
case UserProjectAccessPolicy resource:
sutProvider.GetDependency<IOrganizationUserRepository>()
.GetByIdAsync(resource.OrganizationUserId!.Value)
.Returns(new OrganizationUser
{
Id = resource.OrganizationUserId!.Value,
OrganizationId = organizationId
});
break;
case GroupProjectAccessPolicy resource:
sutProvider.GetDependency<IGroupRepository>().GetByIdAsync(resource.GroupId!.Value)
.Returns(new Group { Id = resource.GroupId!.Value, OrganizationId = organizationId });
break;
case UserServiceAccountAccessPolicy resource:
sutProvider.GetDependency<IOrganizationUserRepository>()
.GetByIdAsync(resource.OrganizationUserId!.Value)
.Returns(new OrganizationUser
{
Id = resource.OrganizationUserId!.Value,
OrganizationId = organizationId
});
break;
case GroupServiceAccountAccessPolicy resource:
sutProvider.GetDependency<IGroupRepository>().GetByIdAsync(resource.GroupId!.Value)
.Returns(new Group { Id = resource.GroupId!.Value, OrganizationId = organizationId });
break;
default:
throw new ArgumentOutOfRangeException(nameof(accessPolicy), accessPolicy, null);
}
}
[Fact]
public void AccessPolicyOperations_OnlyPublicStatic()
{
var publicStaticFields = typeof(AccessPolicyOperations).GetFields(BindingFlags.Public | BindingFlags.Static);
var allFields = typeof(AccessPolicyOperations).GetFields();
Assert.Equal(publicStaticFields.Length, allFields.Length);
}
[Theory]
[BitAutoData]
public async Task Handler_UnsupportedAccessPolicyOperationRequirement_Throws(
SutProvider<AccessPolicyAuthorizationHandler> sutProvider, UserProjectAccessPolicy resource,
ClaimsPrincipal claimsPrincipal)
{
var requirement = new AccessPolicyOperationRequirement();
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, resource);
await Assert.ThrowsAsync<ArgumentException>(() => sutProvider.Sut.HandleAsync(authzContext));
}
[Theory]
[BitAutoData(AccessPolicyType.UserProjectAccessPolicy)]
[BitAutoData(AccessPolicyType.GroupProjectAccessPolicy)]
[BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy)]
[BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy)]
public async Task CanCreate_OrgMismatch_DoesNotSucceed(
AccessPolicyType accessPolicyType,
SutProvider<AccessPolicyAuthorizationHandler> sutProvider,
Project mockGrantedProject,
ServiceAccount mockGrantedServiceAccount,
ClaimsPrincipal claimsPrincipal)
{
var requirement = AccessPolicyOperations.Create;
var resource = CreatePolicy(accessPolicyType, mockGrantedProject, mockGrantedServiceAccount);
SetupOrganizationMismatch(sutProvider, resource);
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, resource);
await sutProvider.Sut.HandleAsync(authzContext);
Assert.False(authzContext.HasSucceeded);
}
[Theory]
[BitAutoData(AccessPolicyType.UserProjectAccessPolicy)]
[BitAutoData(AccessPolicyType.GroupProjectAccessPolicy)]
[BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy)]
[BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy)]
public async Task CanCreate_AccessToSecretsManagerFalse_DoesNotSucceed(
AccessPolicyType accessPolicyType,
SutProvider<AccessPolicyAuthorizationHandler> sutProvider,
Guid organizationId,
Project mockGrantedProject,
ServiceAccount mockGrantedServiceAccount,
ClaimsPrincipal claimsPrincipal)
{
var requirement = AccessPolicyOperations.Create;
mockGrantedProject.OrganizationId = organizationId;
mockGrantedServiceAccount.OrganizationId = organizationId;
var resource = CreatePolicy(accessPolicyType, mockGrantedProject, mockGrantedServiceAccount);
SetupOrganizationMatch(sutProvider, resource, organizationId);
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(organizationId)
.Returns(false);
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, resource);
await sutProvider.Sut.HandleAsync(authzContext);
Assert.False(authzContext.HasSucceeded);
}
[Theory]
[BitAutoData(AccessClientType.ServiceAccount, AccessPolicyType.UserProjectAccessPolicy)]
[BitAutoData(AccessClientType.ServiceAccount, AccessPolicyType.GroupProjectAccessPolicy)]
[BitAutoData(AccessClientType.ServiceAccount, AccessPolicyType.UserServiceAccountAccessPolicy)]
[BitAutoData(AccessClientType.ServiceAccount, AccessPolicyType.GroupServiceAccountAccessPolicy)]
[BitAutoData(AccessClientType.Organization, AccessPolicyType.UserProjectAccessPolicy)]
[BitAutoData(AccessClientType.Organization, AccessPolicyType.GroupProjectAccessPolicy)]
[BitAutoData(AccessClientType.Organization, AccessPolicyType.UserServiceAccountAccessPolicy)]
[BitAutoData(AccessClientType.Organization, AccessPolicyType.GroupServiceAccountAccessPolicy)]
public async Task CanCreate_UnsupportedClientTypes_DoesNotSucceed(
AccessClientType clientType,
AccessPolicyType accessPolicyType,
SutProvider<AccessPolicyAuthorizationHandler> sutProvider,
Guid organizationId,
Project mockGrantedProject,
ServiceAccount mockGrantedServiceAccount,
ClaimsPrincipal claimsPrincipal)
{
var requirement = AccessPolicyOperations.Create;
mockGrantedProject.OrganizationId = organizationId;
mockGrantedServiceAccount.OrganizationId = organizationId;
var resource = CreatePolicy(accessPolicyType, mockGrantedProject, mockGrantedServiceAccount);
SetupOrganizationMatch(sutProvider, resource, organizationId);
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(organizationId)
.Returns(true);
sutProvider.GetDependency<IAccessClientQuery>().GetAccessClientAsync(default, organizationId).ReturnsForAnyArgs(
(clientType, Guid.NewGuid()));
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, resource);
await sutProvider.Sut.HandleAsync(authzContext);
Assert.False(authzContext.HasSucceeded);
}
[Theory]
[BitAutoData(AccessPolicyType.UserProjectAccessPolicy, PermissionType.RunAsAdmin, true, true, true)]
[BitAutoData(AccessPolicyType.UserProjectAccessPolicy, PermissionType.RunAsUserWithPermission, false, false, false)]
[BitAutoData(AccessPolicyType.UserProjectAccessPolicy, PermissionType.RunAsUserWithPermission, false, true, true)]
[BitAutoData(AccessPolicyType.UserProjectAccessPolicy, PermissionType.RunAsUserWithPermission, true, false, false)]
[BitAutoData(AccessPolicyType.UserProjectAccessPolicy, PermissionType.RunAsUserWithPermission, true, true, true)]
[BitAutoData(AccessPolicyType.GroupProjectAccessPolicy, PermissionType.RunAsAdmin, true, true, true)]
[BitAutoData(AccessPolicyType.GroupProjectAccessPolicy, PermissionType.RunAsUserWithPermission, false, false, false)]
[BitAutoData(AccessPolicyType.GroupProjectAccessPolicy, PermissionType.RunAsUserWithPermission, false, true, true)]
[BitAutoData(AccessPolicyType.GroupProjectAccessPolicy, PermissionType.RunAsUserWithPermission, true, false, false)]
[BitAutoData(AccessPolicyType.GroupProjectAccessPolicy, PermissionType.RunAsUserWithPermission, true, true, true)]
[BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy, PermissionType.RunAsAdmin, true, true, true)]
[BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, false, false, false)]
[BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, false, true, true)]
[BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, true, false, false)]
[BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, true, true, true)]
[BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy, PermissionType.RunAsAdmin, true, true, true)]
[BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, false, false, false)]
[BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, false, true, true)]
[BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, true, false, false)]
[BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, true, true, true)]
public async Task CanCreate_AccessCheck(
AccessPolicyType accessPolicyType,
PermissionType permissionType,
bool read, bool write, bool expected,
SutProvider<AccessPolicyAuthorizationHandler> sutProvider,
Guid organizationId,
Guid userId,
Guid serviceAccountId,
Project mockGrantedProject,
ServiceAccount mockGrantedServiceAccount,
ClaimsPrincipal claimsPrincipal)
{
var requirement = AccessPolicyOperations.Create;
mockGrantedProject.OrganizationId = organizationId;
mockGrantedServiceAccount.OrganizationId = organizationId;
var resource = CreatePolicy(accessPolicyType, mockGrantedProject, mockGrantedServiceAccount, serviceAccountId);
SetupCurrentUserPermission(sutProvider, permissionType, organizationId, userId);
SetupOrganizationMatch(sutProvider, resource, organizationId);
SetupMockAccess(sutProvider, userId, resource, read, write);
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, resource);
await sutProvider.Sut.HandleAsync(authzContext);
Assert.Equal(expected, authzContext.HasSucceeded);
}
[Theory]
[BitAutoData(false, false)]
[BitAutoData(false, true)]
[BitAutoData(true, false)]
public async Task CanCreate_ServiceAccountProjectAccessPolicy_TargetsDontExist_DoesNotSucceed(bool projectExists,
bool serviceAccountExists,
SutProvider<AccessPolicyAuthorizationHandler> sutProvider, ServiceAccountProjectAccessPolicy resource,
Project mockProject, ServiceAccount mockServiceAccount,
ClaimsPrincipal claimsPrincipal)
{
var requirement = AccessPolicyOperations.Create;
resource.GrantedProject = null;
resource.ServiceAccount = null;
if (projectExists)
{
resource.GrantedProject = null;
mockProject.Id = resource.GrantedProjectId!.Value;
sutProvider.GetDependency<IProjectRepository>().GetByIdAsync(resource.GrantedProjectId!.Value)
.Returns(mockProject);
}
if (serviceAccountExists)
{
resource.ServiceAccount = null;
sutProvider.GetDependency<IServiceAccountRepository>().GetByIdAsync(resource.ServiceAccountId!.Value)
.Returns(mockServiceAccount);
}
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, resource);
await sutProvider.Sut.HandleAsync(authzContext);
Assert.False(authzContext.HasSucceeded);
}
[Theory]
[BitAutoData(false, false)]
[BitAutoData(false, true)]
[BitAutoData(true, false)]
[BitAutoData(true, true)]
public async Task CanCreate_ServiceAccountProjectAccessPolicy_OrgMismatch_DoesNotSucceed(bool fetchProject,
bool fetchSa,
SutProvider<AccessPolicyAuthorizationHandler> sutProvider, ServiceAccountProjectAccessPolicy resource,
Project mockProject, ServiceAccount mockServiceAccount,
ClaimsPrincipal claimsPrincipal)
{
var requirement = AccessPolicyOperations.Create;
if (fetchProject)
{
resource.GrantedProject = null;
mockProject.Id = resource.GrantedProjectId!.Value;
sutProvider.GetDependency<IProjectRepository>().GetByIdAsync(resource.GrantedProjectId!.Value)
.Returns(mockProject);
}
if (fetchSa)
{
resource.ServiceAccount = null;
mockServiceAccount.Id = resource.ServiceAccountId!.Value;
sutProvider.GetDependency<IServiceAccountRepository>().GetByIdAsync(resource.ServiceAccountId!.Value)
.Returns(mockServiceAccount);
}
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, resource);
await sutProvider.Sut.HandleAsync(authzContext);
Assert.False(authzContext.HasSucceeded);
}
[Theory]
[BitAutoData]
public async Task CanCreate_ServiceAccountProjectAccessPolicy_AccessToSecretsManagerFalse_DoesNotSucceed(
SutProvider<AccessPolicyAuthorizationHandler> sutProvider, ServiceAccountProjectAccessPolicy resource,
ClaimsPrincipal claimsPrincipal)
{
var requirement = AccessPolicyOperations.Create;
resource.ServiceAccount!.OrganizationId = resource.GrantedProject!.OrganizationId;
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(resource.GrantedProject!.OrganizationId)
.Returns(false);
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, resource);
await sutProvider.Sut.HandleAsync(authzContext);
Assert.False(authzContext.HasSucceeded);
}
[Theory]
[BitAutoData(AccessClientType.ServiceAccount)]
[BitAutoData(AccessClientType.Organization)]
public async Task CanCreate_ServiceAccountProjectAccessPolicy_UnsupportedClientTypes_DoesNotSucceed(
AccessClientType clientType,
SutProvider<AccessPolicyAuthorizationHandler> sutProvider, ServiceAccountProjectAccessPolicy resource,
ClaimsPrincipal claimsPrincipal)
{
var requirement = AccessPolicyOperations.Create;
resource.ServiceAccount!.OrganizationId = resource.GrantedProject!.OrganizationId;
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(resource.GrantedProject!.OrganizationId)
.Returns(true);
sutProvider.GetDependency<IAccessClientQuery>().GetAccessClientAsync(default, resource.ServiceAccount!.OrganizationId).ReturnsForAnyArgs(
(clientType, new Guid()));
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, resource);
await sutProvider.Sut.HandleAsync(authzContext);
Assert.False(authzContext.HasSucceeded);
}
[Theory]
[BitAutoData(PermissionType.RunAsAdmin, true, true, true, true, true)]
[BitAutoData(PermissionType.RunAsUserWithPermission, false, false, false, false, false)]
[BitAutoData(PermissionType.RunAsUserWithPermission, false, false, false, true, false)]
[BitAutoData(PermissionType.RunAsUserWithPermission, false, false, true, false, false)]
[BitAutoData(PermissionType.RunAsUserWithPermission, false, false, true, true, false)]
[BitAutoData(PermissionType.RunAsUserWithPermission, false, true, false, false, false)]
[BitAutoData(PermissionType.RunAsUserWithPermission, false, true, false, true, true)]
[BitAutoData(PermissionType.RunAsUserWithPermission, false, true, true, false, false)]
[BitAutoData(PermissionType.RunAsUserWithPermission, false, true, true, true, true)]
[BitAutoData(PermissionType.RunAsUserWithPermission, true, false, false, false, false)]
[BitAutoData(PermissionType.RunAsUserWithPermission, true, false, false, true, false)]
[BitAutoData(PermissionType.RunAsUserWithPermission, true, false, true, false, false)]
[BitAutoData(PermissionType.RunAsUserWithPermission, true, false, true, true, false)]
[BitAutoData(PermissionType.RunAsUserWithPermission, true, true, false, false, false)]
[BitAutoData(PermissionType.RunAsUserWithPermission, true, true, false, true, true)]
[BitAutoData(PermissionType.RunAsUserWithPermission, true, true, true, false, false)]
[BitAutoData(PermissionType.RunAsUserWithPermission, true, true, true, true, true)]
public async Task CanCreate_ServiceAccountProjectAccessPolicy_AccessCheck(PermissionType permissionType,
bool projectRead,
bool projectWrite, bool saRead, bool saWrite, bool expected,
SutProvider<AccessPolicyAuthorizationHandler> sutProvider, ServiceAccountProjectAccessPolicy resource,
ClaimsPrincipal claimsPrincipal, Guid userId)
{
var requirement = AccessPolicyOperations.Create;
resource.ServiceAccount!.OrganizationId = resource.GrantedProject!.OrganizationId;
SetupCurrentUserPermission(sutProvider, permissionType, resource.GrantedProject!.OrganizationId, userId);
sutProvider.GetDependency<IProjectRepository>()
.AccessToProjectAsync(resource.GrantedProjectId!.Value, userId, Arg.Any<AccessClientType>())
.Returns((projectRead, projectWrite));
sutProvider.GetDependency<IServiceAccountRepository>()
.AccessToServiceAccountAsync(resource.ServiceAccountId!.Value, userId, Arg.Any<AccessClientType>())
.Returns((saRead, saWrite));
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, resource);
await sutProvider.Sut.HandleAsync(authzContext);
Assert.Equal(expected, authzContext.HasSucceeded);
}
[Theory]
[BitAutoData(AccessPolicyType.UserProjectAccessPolicy)]
[BitAutoData(AccessPolicyType.GroupProjectAccessPolicy)]
[BitAutoData(AccessPolicyType.ServiceAccountProjectAccessPolicy)]
[BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy)]
[BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy)]
public async Task CanUpdate_AccessToSecretsManagerFalse_DoesNotSucceed(AccessPolicyType accessPolicyType,
SutProvider<AccessPolicyAuthorizationHandler> sutProvider,
Guid organizationId,
Project mockGrantedProject,
ServiceAccount mockGrantedServiceAccount,
ClaimsPrincipal claimsPrincipal)
{
var requirement = AccessPolicyOperations.Update;
mockGrantedProject.OrganizationId = organizationId;
mockGrantedServiceAccount.OrganizationId = organizationId;
var resource = CreatePolicy(accessPolicyType, mockGrantedProject, mockGrantedServiceAccount);
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(organizationId).Returns(false);
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, resource);
await sutProvider.Sut.HandleAsync(authzContext);
Assert.False(authzContext.HasSucceeded);
}
[Theory]
[BitAutoData(AccessClientType.ServiceAccount, AccessPolicyType.UserProjectAccessPolicy)]
[BitAutoData(AccessClientType.ServiceAccount, AccessPolicyType.GroupProjectAccessPolicy)]
[BitAutoData(AccessClientType.ServiceAccount, AccessPolicyType.ServiceAccountProjectAccessPolicy)]
[BitAutoData(AccessClientType.ServiceAccount, AccessPolicyType.UserServiceAccountAccessPolicy)]
[BitAutoData(AccessClientType.ServiceAccount, AccessPolicyType.GroupServiceAccountAccessPolicy)]
[BitAutoData(AccessClientType.Organization, AccessPolicyType.UserProjectAccessPolicy)]
[BitAutoData(AccessClientType.Organization, AccessPolicyType.GroupProjectAccessPolicy)]
[BitAutoData(AccessClientType.Organization, AccessPolicyType.ServiceAccountProjectAccessPolicy)]
[BitAutoData(AccessClientType.Organization, AccessPolicyType.UserServiceAccountAccessPolicy)]
[BitAutoData(AccessClientType.Organization, AccessPolicyType.GroupServiceAccountAccessPolicy)]
public async Task CanUpdate_UnsupportedClientTypes_DoesNotSucceed(
AccessClientType clientType,
AccessPolicyType accessPolicyType,
SutProvider<AccessPolicyAuthorizationHandler> sutProvider,
Guid organizationId,
Project mockGrantedProject,
ServiceAccount mockGrantedServiceAccount,
ClaimsPrincipal claimsPrincipal)
{
var requirement = AccessPolicyOperations.Update;
mockGrantedProject.OrganizationId = organizationId;
mockGrantedServiceAccount.OrganizationId = organizationId;
var resource = CreatePolicy(accessPolicyType, mockGrantedProject, mockGrantedServiceAccount);
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(organizationId).Returns(true);
sutProvider.GetDependency<IAccessClientQuery>().GetAccessClientAsync(default, organizationId).ReturnsForAnyArgs(
(clientType, new Guid()));
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, resource);
await sutProvider.Sut.HandleAsync(authzContext);
Assert.False(authzContext.HasSucceeded);
}
[Theory]
[BitAutoData(AccessPolicyType.UserProjectAccessPolicy, PermissionType.RunAsAdmin, true, true, true)]
[BitAutoData(AccessPolicyType.UserProjectAccessPolicy, PermissionType.RunAsUserWithPermission, false, false, false)]
[BitAutoData(AccessPolicyType.UserProjectAccessPolicy, PermissionType.RunAsUserWithPermission, false, true, true)]
[BitAutoData(AccessPolicyType.UserProjectAccessPolicy, PermissionType.RunAsUserWithPermission, true, false, false)]
[BitAutoData(AccessPolicyType.UserProjectAccessPolicy, PermissionType.RunAsUserWithPermission, true, true, true)]
[BitAutoData(AccessPolicyType.GroupProjectAccessPolicy, PermissionType.RunAsAdmin, true, true, true)]
[BitAutoData(AccessPolicyType.GroupProjectAccessPolicy, PermissionType.RunAsUserWithPermission, false, false, false)]
[BitAutoData(AccessPolicyType.GroupProjectAccessPolicy, PermissionType.RunAsUserWithPermission, false, true, true)]
[BitAutoData(AccessPolicyType.GroupProjectAccessPolicy, PermissionType.RunAsUserWithPermission, true, false, false)]
[BitAutoData(AccessPolicyType.GroupProjectAccessPolicy, PermissionType.RunAsUserWithPermission, true, true, true)]
[BitAutoData(AccessPolicyType.ServiceAccountProjectAccessPolicy, PermissionType.RunAsAdmin, true, true, true)]
[BitAutoData(AccessPolicyType.ServiceAccountProjectAccessPolicy, PermissionType.RunAsUserWithPermission, false, false, false)]
[BitAutoData(AccessPolicyType.ServiceAccountProjectAccessPolicy, PermissionType.RunAsUserWithPermission, false, true, true)]
[BitAutoData(AccessPolicyType.ServiceAccountProjectAccessPolicy, PermissionType.RunAsUserWithPermission, true, false, false)]
[BitAutoData(AccessPolicyType.ServiceAccountProjectAccessPolicy, PermissionType.RunAsUserWithPermission, true, true, true)]
[BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy, PermissionType.RunAsAdmin, true, true, true)]
[BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, false, false, false)]
[BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, false, true, true)]
[BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, true, false, false)]
[BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, true, true, true)]
[BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy, PermissionType.RunAsAdmin, true, true, true)]
[BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, false, false, false)]
[BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, false, true, true)]
[BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, true, false, false)]
[BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, true, true, true)]
public async Task CanUpdate_AccessCheck(
AccessPolicyType accessPolicyType,
PermissionType permissionType, bool read,
bool write, bool expected,
SutProvider<AccessPolicyAuthorizationHandler> sutProvider,
Guid organizationId,
Project mockGrantedProject,
ServiceAccount mockGrantedServiceAccount,
ClaimsPrincipal claimsPrincipal, Guid userId, Guid serviceAccountId)
{
var requirement = AccessPolicyOperations.Update;
mockGrantedProject.OrganizationId = organizationId;
mockGrantedServiceAccount.OrganizationId = organizationId;
var resource = CreatePolicy(accessPolicyType, mockGrantedProject, mockGrantedServiceAccount,
serviceAccountId);
SetupCurrentUserPermission(sutProvider, permissionType, organizationId, userId);
SetupMockAccess(sutProvider, userId, resource, read, write);
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, resource);
await sutProvider.Sut.HandleAsync(authzContext);
Assert.Equal(expected, authzContext.HasSucceeded);
}
[Theory]
[BitAutoData(AccessPolicyType.UserProjectAccessPolicy)]
[BitAutoData(AccessPolicyType.GroupProjectAccessPolicy)]
[BitAutoData(AccessPolicyType.ServiceAccountProjectAccessPolicy)]
[BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy)]
[BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy)]
public async Task CanDelete_AccessToSecretsManagerFalse_DoesNotSucceed(AccessPolicyType accessPolicyType,
SutProvider<AccessPolicyAuthorizationHandler> sutProvider,
Guid organizationId,
Project mockGrantedProject,
ServiceAccount mockGrantedServiceAccount,
ClaimsPrincipal claimsPrincipal)
{
var requirement = AccessPolicyOperations.Delete;
mockGrantedProject.OrganizationId = organizationId;
mockGrantedServiceAccount.OrganizationId = organizationId;
var resource = CreatePolicy(accessPolicyType, mockGrantedProject, mockGrantedServiceAccount);
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(organizationId).Returns(false);
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, resource);
await sutProvider.Sut.HandleAsync(authzContext);
Assert.False(authzContext.HasSucceeded);
}
[Theory]
[BitAutoData(AccessClientType.ServiceAccount, AccessPolicyType.UserProjectAccessPolicy)]
[BitAutoData(AccessClientType.ServiceAccount, AccessPolicyType.GroupProjectAccessPolicy)]
[BitAutoData(AccessClientType.ServiceAccount, AccessPolicyType.ServiceAccountProjectAccessPolicy)]
[BitAutoData(AccessClientType.ServiceAccount, AccessPolicyType.UserServiceAccountAccessPolicy)]
[BitAutoData(AccessClientType.ServiceAccount, AccessPolicyType.GroupServiceAccountAccessPolicy)]
[BitAutoData(AccessClientType.Organization, AccessPolicyType.UserProjectAccessPolicy)]
[BitAutoData(AccessClientType.Organization, AccessPolicyType.GroupProjectAccessPolicy)]
[BitAutoData(AccessClientType.Organization, AccessPolicyType.ServiceAccountProjectAccessPolicy)]
[BitAutoData(AccessClientType.Organization, AccessPolicyType.UserServiceAccountAccessPolicy)]
[BitAutoData(AccessClientType.Organization, AccessPolicyType.GroupServiceAccountAccessPolicy)]
public async Task CanDelete_UnsupportedClientTypes_DoesNotSucceed(
AccessClientType clientType,
AccessPolicyType accessPolicyType,
SutProvider<AccessPolicyAuthorizationHandler> sutProvider,
Guid organizationId,
Project mockGrantedProject,
ServiceAccount mockGrantedServiceAccount,
ClaimsPrincipal claimsPrincipal)
{
var requirement = AccessPolicyOperations.Delete;
mockGrantedProject.OrganizationId = organizationId;
mockGrantedServiceAccount.OrganizationId = organizationId;
var resource = CreatePolicy(accessPolicyType, mockGrantedProject, mockGrantedServiceAccount);
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(organizationId).Returns(true);
sutProvider.GetDependency<IAccessClientQuery>().GetAccessClientAsync(default, organizationId).ReturnsForAnyArgs(
(clientType, new Guid()));
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, resource);
await sutProvider.Sut.HandleAsync(authzContext);
Assert.False(authzContext.HasSucceeded);
}
[Theory]
[BitAutoData(AccessPolicyType.UserProjectAccessPolicy, PermissionType.RunAsAdmin, true, true, true)]
[BitAutoData(AccessPolicyType.UserProjectAccessPolicy, PermissionType.RunAsUserWithPermission, false, false, false)]
[BitAutoData(AccessPolicyType.UserProjectAccessPolicy, PermissionType.RunAsUserWithPermission, false, true, true)]
[BitAutoData(AccessPolicyType.UserProjectAccessPolicy, PermissionType.RunAsUserWithPermission, true, false, false)]
[BitAutoData(AccessPolicyType.UserProjectAccessPolicy, PermissionType.RunAsUserWithPermission, true, true, true)]
[BitAutoData(AccessPolicyType.GroupProjectAccessPolicy, PermissionType.RunAsAdmin, true, true, true)]
[BitAutoData(AccessPolicyType.GroupProjectAccessPolicy, PermissionType.RunAsUserWithPermission, false, false, false)]
[BitAutoData(AccessPolicyType.GroupProjectAccessPolicy, PermissionType.RunAsUserWithPermission, false, true, true)]
[BitAutoData(AccessPolicyType.GroupProjectAccessPolicy, PermissionType.RunAsUserWithPermission, true, false, false)]
[BitAutoData(AccessPolicyType.GroupProjectAccessPolicy, PermissionType.RunAsUserWithPermission, true, true, true)]
[BitAutoData(AccessPolicyType.ServiceAccountProjectAccessPolicy, PermissionType.RunAsAdmin, true, true, true)]
[BitAutoData(AccessPolicyType.ServiceAccountProjectAccessPolicy, PermissionType.RunAsUserWithPermission, false, false, false)]
[BitAutoData(AccessPolicyType.ServiceAccountProjectAccessPolicy, PermissionType.RunAsUserWithPermission, false, true, true)]
[BitAutoData(AccessPolicyType.ServiceAccountProjectAccessPolicy, PermissionType.RunAsUserWithPermission, true, false, false)]
[BitAutoData(AccessPolicyType.ServiceAccountProjectAccessPolicy, PermissionType.RunAsUserWithPermission, true, true, true)]
[BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy, PermissionType.RunAsAdmin, true, true, true)]
[BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, false, false, false)]
[BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, false, true, true)]
[BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, true, false, false)]
[BitAutoData(AccessPolicyType.UserServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, true, true, true)]
[BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy, PermissionType.RunAsAdmin, true, true, true)]
[BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, false, false, false)]
[BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, false, true, true)]
[BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, true, false, false)]
[BitAutoData(AccessPolicyType.GroupServiceAccountAccessPolicy, PermissionType.RunAsUserWithPermission, true, true, true)]
public async Task CanDelete_AccessCheck(
AccessPolicyType accessPolicyType,
PermissionType permissionType,
bool read, bool write, bool expected,
SutProvider<AccessPolicyAuthorizationHandler> sutProvider,
Guid organizationId,
Project mockGrantedProject,
ServiceAccount mockGrantedServiceAccount,
ClaimsPrincipal claimsPrincipal, Guid userId, Guid serviceAccountId)
{
var requirement = AccessPolicyOperations.Delete;
mockGrantedProject.OrganizationId = organizationId;
mockGrantedServiceAccount.OrganizationId = organizationId;
var resource = CreatePolicy(accessPolicyType, mockGrantedProject, mockGrantedServiceAccount,
serviceAccountId);
SetupCurrentUserPermission(sutProvider, permissionType, organizationId, userId);
SetupMockAccess(sutProvider, userId, resource, read, write);
var authzContext = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, resource);
await sutProvider.Sut.HandleAsync(authzContext);
Assert.Equal(expected, authzContext.HasSucceeded);
}
}

View File

@ -1,136 +0,0 @@
using Bit.Commercial.Core.SecretsManager.Commands.AccessPolicies;
using Bit.Core.Exceptions;
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.AccessPolicies;
[SutProviderCustomize]
[ProjectCustomize]
public class CreateAccessPoliciesCommandTests
{
private static List<BaseAccessPolicy> MakeGrantedProjectAccessPolicies(Guid grantedProjectId, List<UserProjectAccessPolicy> userProjectAccessPolicies,
List<GroupProjectAccessPolicy> groupProjectAccessPolicies,
List<ServiceAccountProjectAccessPolicy> serviceAccountProjectAccessPolicies)
{
var data = new List<BaseAccessPolicy>();
foreach (var ap in userProjectAccessPolicies)
{
ap.GrantedProjectId = grantedProjectId;
ap.GrantedProject = null;
ap.User = null;
}
foreach (var ap in groupProjectAccessPolicies)
{
ap.GrantedProjectId = grantedProjectId;
ap.GrantedProject = null;
ap.Group = null;
}
foreach (var ap in serviceAccountProjectAccessPolicies)
{
ap.GrantedProjectId = grantedProjectId;
ap.GrantedProject = null;
ap.ServiceAccount = null;
}
data.AddRange(userProjectAccessPolicies);
data.AddRange(groupProjectAccessPolicies);
data.AddRange(serviceAccountProjectAccessPolicies);
return data;
}
private static List<BaseAccessPolicy> MakeGrantedServiceAccountAccessPolicies(Guid grantedServiceAccountId, List<UserServiceAccountAccessPolicy> userServiceAccountAccessPolicies,
List<GroupServiceAccountAccessPolicy> groupServiceAccountAccessPolicies)
{
var data = new List<BaseAccessPolicy>();
foreach (var ap in userServiceAccountAccessPolicies)
{
ap.GrantedServiceAccountId = grantedServiceAccountId;
ap.GrantedServiceAccount = null;
ap.User = null;
}
foreach (var ap in groupServiceAccountAccessPolicies)
{
ap.GrantedServiceAccountId = grantedServiceAccountId;
ap.GrantedServiceAccount = null;
ap.Group = null;
}
data.AddRange(userServiceAccountAccessPolicies);
data.AddRange(groupServiceAccountAccessPolicies);
return data;
}
[Theory]
[BitAutoData]
public async Task CreateMany_AlreadyExists_Throws_BadRequestException(
Project project,
ServiceAccount serviceAccount,
List<UserProjectAccessPolicy> userProjectAccessPolicies,
List<GroupProjectAccessPolicy> groupProjectAccessPolicies,
List<ServiceAccountProjectAccessPolicy> serviceAccountProjectAccessPolicies,
List<UserServiceAccountAccessPolicy> userServiceAccountAccessPolicies,
List<GroupServiceAccountAccessPolicy> groupServiceAccountAccessPolicies,
SutProvider<CreateAccessPoliciesCommand> sutProvider)
{
var data = MakeGrantedProjectAccessPolicies(project.Id, userProjectAccessPolicies, groupProjectAccessPolicies,
serviceAccountProjectAccessPolicies);
var saData = MakeGrantedServiceAccountAccessPolicies(serviceAccount.Id, userServiceAccountAccessPolicies, groupServiceAccountAccessPolicies);
data = data.Concat(saData).ToList();
sutProvider.GetDependency<IAccessPolicyRepository>().AccessPolicyExists(Arg.Any<BaseAccessPolicy>())
.Returns(true);
await Assert.ThrowsAsync<BadRequestException>(() =>
sutProvider.Sut.CreateManyAsync(data));
await sutProvider.GetDependency<IAccessPolicyRepository>().DidNotReceiveWithAnyArgs().CreateManyAsync(default!);
}
[Theory]
[BitAutoData]
public async Task CreateMany_ClearsReferences(SutProvider<CreateAccessPoliciesCommand> sutProvider, Guid projectId)
{
var userProjectAp = new UserProjectAccessPolicy
{
GrantedProjectId = projectId,
OrganizationUserId = new Guid(),
};
var data = new List<BaseAccessPolicy>() { userProjectAp, };
userProjectAp.GrantedProject = new Project() { Id = new Guid() };
var expectedCall = new List<BaseAccessPolicy>() { userProjectAp, };
await sutProvider.Sut.CreateManyAsync(data);
await sutProvider.GetDependency<IAccessPolicyRepository>().Received(1)
.CreateManyAsync(Arg.Is(AssertHelper.AssertPropertyEqual(expectedCall)));
}
[Theory]
[BitAutoData]
public async Task CreateMany_Success(
Project project,
ServiceAccount serviceAccount,
List<UserProjectAccessPolicy> userProjectAccessPolicies,
List<GroupProjectAccessPolicy> groupProjectAccessPolicies,
List<ServiceAccountProjectAccessPolicy> serviceAccountProjectAccessPolicies,
List<UserServiceAccountAccessPolicy> userServiceAccountAccessPolicies,
List<GroupServiceAccountAccessPolicy> groupServiceAccountAccessPolicies,
SutProvider<CreateAccessPoliciesCommand> sutProvider)
{
var data = MakeGrantedProjectAccessPolicies(project.Id, userProjectAccessPolicies, groupProjectAccessPolicies,
serviceAccountProjectAccessPolicies);
var saData = MakeGrantedServiceAccountAccessPolicies(serviceAccount.Id, userServiceAccountAccessPolicies, groupServiceAccountAccessPolicies);
data = data.Concat(saData).ToList();
await sutProvider.Sut.CreateManyAsync(data);
await sutProvider.GetDependency<IAccessPolicyRepository>().Received(1)
.CreateManyAsync(Arg.Is(AssertHelper.AssertPropertyEqual(data)));
}
}

View File

@ -1,25 +0,0 @@
using Bit.Commercial.Core.SecretsManager.Commands.AccessPolicies;
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.AccessPolicies;
[SutProviderCustomize]
[ProjectCustomize]
public class DeleteAccessPolicyCommandTests
{
[Theory]
[BitAutoData]
public async Task DeleteAsync_Success(SutProvider<DeleteAccessPolicyCommand> sutProvider, Guid data)
{
await sutProvider.Sut.DeleteAsync(data);
await sutProvider.GetDependency<IAccessPolicyRepository>().Received(1)
.DeleteAsync(Arg.Is(AssertHelper.AssertPropertyEqual(data)));
}
}

View File

@ -1,44 +0,0 @@
using Bit.Commercial.Core.SecretsManager.Commands.AccessPolicies;
using Bit.Core.Exceptions;
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.AccessPolicies;
[SutProviderCustomize]
[ProjectCustomize]
public class UpdateAccessPolicyCommandTests
{
[Theory]
[BitAutoData]
public async Task UpdateAsync_DoesNotExist_ThrowsNotFound(Guid data, bool read, bool write,
SutProvider<UpdateAccessPolicyCommand> sutProvider)
{
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.UpdateAsync(data, read, write));
await sutProvider.GetDependency<IAccessPolicyRepository>().DidNotReceiveWithAnyArgs().ReplaceAsync(Arg.Any<BaseAccessPolicy>());
}
[Theory]
[BitAutoData]
public async Task UpdateAsync_Success(Guid data, bool read, bool write, UserProjectAccessPolicy accessPolicy,
SutProvider<UpdateAccessPolicyCommand> sutProvider)
{
accessPolicy.Id = data;
sutProvider.GetDependency<IAccessPolicyRepository>().GetByIdAsync(data).Returns(accessPolicy);
var result = await sutProvider.Sut.UpdateAsync(data, read, write);
await sutProvider.GetDependency<IAccessPolicyRepository>().Received(1)
.ReplaceAsync(Arg.Any<BaseAccessPolicy>());
AssertHelper.AssertRecent(result.RevisionDate);
Assert.Equal(read, result.Read);
Assert.Equal(write, result.Write);
}
}

View File

@ -17,24 +17,22 @@ using Microsoft.AspNetCore.Mvc;
namespace Bit.Api.SecretsManager.Controllers;
[Authorize("secrets")]
[Route("access-policies")]
public class AccessPoliciesController : Controller
{
private const int _maxBulkCreation = 15;
private readonly IAccessPolicyRepository _accessPolicyRepository;
private readonly ICreateAccessPoliciesCommand _createAccessPoliciesCommand;
private readonly ICurrentContext _currentContext;
private readonly IDeleteAccessPolicyCommand _deleteAccessPolicyCommand;
private readonly IProjectRepository _projectRepository;
private readonly IServiceAccountRepository _serviceAccountRepository;
private readonly IUpdateAccessPolicyCommand _updateAccessPolicyCommand;
private readonly IUpdateServiceAccountGrantedPoliciesCommand _updateServiceAccountGrantedPoliciesCommand;
private readonly IUpdateProjectServiceAccountsAccessPoliciesCommand _updateProjectServiceAccountsAccessPoliciesCommand;
private readonly IAccessClientQuery _accessClientQuery;
private readonly IServiceAccountGrantedPolicyUpdatesQuery _serviceAccountGrantedPolicyUpdatesQuery;
private readonly IProjectServiceAccountsAccessPoliciesUpdatesQuery _projectServiceAccountsAccessPoliciesUpdatesQuery;
private readonly IUserService _userService;
private readonly IAccessPolicyRepository _accessPolicyRepository;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentContext _currentContext;
private readonly IProjectRepository _projectRepository;
private readonly IServiceAccountGrantedPolicyUpdatesQuery _serviceAccountGrantedPolicyUpdatesQuery;
private readonly IServiceAccountRepository _serviceAccountRepository;
private readonly IUpdateServiceAccountGrantedPoliciesCommand _updateServiceAccountGrantedPoliciesCommand;
private readonly IUserService _userService;
private readonly IProjectServiceAccountsAccessPoliciesUpdatesQuery
_projectServiceAccountsAccessPoliciesUpdatesQuery;
private readonly IUpdateProjectServiceAccountsAccessPoliciesCommand
_updateProjectServiceAccountsAccessPoliciesCommand;
public AccessPoliciesController(
IAuthorizationService authorizationService,
@ -47,10 +45,7 @@ public class AccessPoliciesController : Controller
IServiceAccountGrantedPolicyUpdatesQuery serviceAccountGrantedPolicyUpdatesQuery,
IProjectServiceAccountsAccessPoliciesUpdatesQuery projectServiceAccountsAccessPoliciesUpdatesQuery,
IUpdateServiceAccountGrantedPoliciesCommand updateServiceAccountGrantedPoliciesCommand,
ICreateAccessPoliciesCommand createAccessPoliciesCommand,
IDeleteAccessPolicyCommand deleteAccessPolicyCommand,
IUpdateProjectServiceAccountsAccessPoliciesCommand updateProjectServiceAccountsAccessPoliciesCommand,
IUpdateAccessPolicyCommand updateAccessPolicyCommand)
IUpdateProjectServiceAccountsAccessPoliciesCommand updateProjectServiceAccountsAccessPoliciesCommand)
{
_authorizationService = authorizationService;
_userService = userService;
@ -58,9 +53,6 @@ public class AccessPoliciesController : Controller
_serviceAccountRepository = serviceAccountRepository;
_projectRepository = projectRepository;
_accessPolicyRepository = accessPolicyRepository;
_createAccessPoliciesCommand = createAccessPoliciesCommand;
_deleteAccessPolicyCommand = deleteAccessPolicyCommand;
_updateAccessPolicyCommand = updateAccessPolicyCommand;
_updateServiceAccountGrantedPoliciesCommand = updateServiceAccountGrantedPoliciesCommand;
_accessClientQuery = accessClientQuery;
_serviceAccountGrantedPolicyUpdatesQuery = serviceAccountGrantedPolicyUpdatesQuery;
@ -68,86 +60,6 @@ public class AccessPoliciesController : Controller
_updateProjectServiceAccountsAccessPoliciesCommand = updateProjectServiceAccountsAccessPoliciesCommand;
}
[HttpPost("/projects/{id}/access-policies")]
public async Task<ProjectAccessPoliciesResponseModel> CreateProjectAccessPoliciesAsync([FromRoute] Guid id,
[FromBody] AccessPoliciesCreateRequest request)
{
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 policies = request.ToBaseAccessPoliciesForProject(id, project.OrganizationId);
foreach (var policy in policies)
{
var authorizationResult = await _authorizationService.AuthorizeAsync(User, policy, AccessPolicyOperations.Create);
if (!authorizationResult.Succeeded)
{
throw new NotFoundException();
}
}
var results = await _createAccessPoliciesCommand.CreateManyAsync(policies);
return new ProjectAccessPoliciesResponseModel(results);
}
[HttpGet("/projects/{id}/access-policies")]
public async Task<ProjectAccessPoliciesResponseModel> GetProjectAccessPoliciesAsync([FromRoute] Guid id)
{
var project = await _projectRepository.GetByIdAsync(id);
var (_, userId) = await CheckUserHasWriteAccessToProjectAsync(project);
var results = await _accessPolicyRepository.GetManyByGrantedProjectIdAsync(id, userId);
return new ProjectAccessPoliciesResponseModel(results);
}
[HttpPut("{id}")]
public async Task<BaseAccessPolicyResponseModel> UpdateAccessPolicyAsync([FromRoute] Guid id,
[FromBody] AccessPolicyUpdateRequest request)
{
var ap = await _accessPolicyRepository.GetByIdAsync(id);
var authorizationResult =
await _authorizationService.AuthorizeAsync(User, ap, AccessPolicyOperations.Update);
if (!authorizationResult.Succeeded)
{
throw new NotFoundException();
}
var result = await _updateAccessPolicyCommand.UpdateAsync(id, request.Read, request.Write);
return result switch
{
UserProjectAccessPolicy accessPolicy => new UserProjectAccessPolicyResponseModel(accessPolicy),
UserServiceAccountAccessPolicy accessPolicy =>
new UserServiceAccountAccessPolicyResponseModel(accessPolicy),
GroupProjectAccessPolicy accessPolicy => new GroupProjectAccessPolicyResponseModel(accessPolicy),
GroupServiceAccountAccessPolicy accessPolicy => new GroupServiceAccountAccessPolicyResponseModel(
accessPolicy),
ServiceAccountProjectAccessPolicy accessPolicy => new ServiceAccountProjectAccessPolicyResponseModel(
accessPolicy),
_ => throw new ArgumentException("Unsupported access policy type provided."),
};
}
[HttpDelete("{id}")]
public async Task DeleteAccessPolicyAsync([FromRoute] Guid id)
{
var ap = await _accessPolicyRepository.GetByIdAsync(id);
var authorizationResult =
await _authorizationService.AuthorizeAsync(User, ap, AccessPolicyOperations.Delete);
if (!authorizationResult.Succeeded)
{
throw new NotFoundException();
}
await _deleteAccessPolicyCommand.DeleteAsync(id);
}
[HttpGet("/organizations/{id}/access-policies/people/potential-grantees")]
public async Task<ListResponseModel<PotentialGranteeResponseModel>> GetPeoplePotentialGranteesAsync(
[FromRoute] Guid id)
@ -157,7 +69,7 @@ public class AccessPoliciesController : Controller
throw new NotFoundException();
}
var userId = _userService.GetProperUserId(User).Value;
var userId = _userService.GetProperUserId(User)!.Value;
var peopleGrantees = await _accessPolicyRepository.GetPeopleGranteesAsync(id, userId);
var userResponses = peopleGrantees.UserGrantees.Select(ug => new PotentialGranteeResponseModel(ug));
@ -169,7 +81,12 @@ public class AccessPoliciesController : Controller
public async Task<ListResponseModel<PotentialGranteeResponseModel>> GetServiceAccountsPotentialGranteesAsync(
[FromRoute] Guid id)
{
var (accessClient, userId) = await GetAccessClientTypeAsync(id);
if (!_currentContext.AccessSecretsManager(id))
{
throw new NotFoundException();
}
var (accessClient, userId) = await _accessClientQuery.GetAccessClientAsync(User, id);
var serviceAccounts =
await _serviceAccountRepository.GetManyByOrganizationIdWriteAccessAsync(id,
@ -185,7 +102,12 @@ public class AccessPoliciesController : Controller
public async Task<ListResponseModel<PotentialGranteeResponseModel>> GetProjectPotentialGranteesAsync(
[FromRoute] Guid id)
{
var (accessClient, userId) = await GetAccessClientTypeAsync(id);
if (!_currentContext.AccessSecretsManager(id))
{
throw new NotFoundException();
}
var (accessClient, userId) = await _accessClientQuery.GetAccessClientAsync(User, id);
var projects =
await _projectRepository.GetManyByOrganizationIdWriteAccessAsync(id,
@ -225,7 +147,7 @@ public class AccessPoliciesController : Controller
throw new NotFoundException();
}
var userId = _userService.GetProperUserId(User).Value;
var userId = _userService.GetProperUserId(User)!.Value;
var results = await _accessPolicyRepository.ReplaceProjectPeopleAsync(peopleAccessPolicies, userId);
return new ProjectPeopleAccessPoliciesResponseModel(results, userId);
}
@ -337,39 +259,48 @@ public class AccessPoliciesController : Controller
return new ProjectServiceAccountsAccessPoliciesResponseModel(results);
}
private async Task<(AccessClientType AccessClientType, Guid UserId)> CheckUserHasWriteAccessToProjectAsync(Project project)
private async Task<(AccessClientType AccessClientType, Guid UserId)> CheckUserHasWriteAccessToProjectAsync(
Project project)
{
if (project == null)
{
throw new NotFoundException();
}
var (accessClient, userId) = await GetAccessClientTypeAsync(project.OrganizationId);
if (!_currentContext.AccessSecretsManager(project.OrganizationId))
{
throw new NotFoundException();
}
var (accessClient, userId) = await _accessClientQuery.GetAccessClientAsync(User, project.OrganizationId);
var access = await _projectRepository.AccessToProjectAsync(project.Id, userId, accessClient);
if (!access.Write || accessClient == AccessClientType.ServiceAccount)
{
throw new NotFoundException();
}
return (accessClient, userId);
}
private async Task<(AccessClientType AccessClientType, Guid UserId)> CheckUserHasWriteAccessToServiceAccountAsync(ServiceAccount serviceAccount)
private async Task<(AccessClientType AccessClientType, Guid UserId)> CheckUserHasWriteAccessToServiceAccountAsync(
ServiceAccount serviceAccount)
{
if (serviceAccount == null)
{
throw new NotFoundException();
}
var (accessClient, userId) = await GetAccessClientTypeAsync(serviceAccount.OrganizationId);
var hasAccess = accessClient switch
if (!_currentContext.AccessSecretsManager(serviceAccount.OrganizationId))
{
AccessClientType.NoAccessCheck => true,
AccessClientType.User => await _serviceAccountRepository.UserHasWriteAccessToServiceAccount(
serviceAccount.Id, userId),
_ => false,
};
throw new NotFoundException();
}
if (!hasAccess)
var (accessClient, userId) = await _accessClientQuery.GetAccessClientAsync(User, serviceAccount.OrganizationId);
var access =
await _serviceAccountRepository.AccessToServiceAccountAsync(serviceAccount.Id, userId, accessClient);
if (!access.Write)
{
throw new NotFoundException();
}
@ -377,23 +308,13 @@ public class AccessPoliciesController : Controller
return (accessClient, userId);
}
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);
}
private async Task<ServiceAccountGrantedPoliciesPermissionDetailsResponseModel> GetServiceAccountGrantedPoliciesAsync(ServiceAccount serviceAccount)
private async Task<ServiceAccountGrantedPoliciesPermissionDetailsResponseModel>
GetServiceAccountGrantedPoliciesAsync(ServiceAccount serviceAccount)
{
var (accessClient, userId) = await _accessClientQuery.GetAccessClientAsync(User, serviceAccount.OrganizationId);
var results = await _accessPolicyRepository.GetServiceAccountGrantedPoliciesPermissionDetailsAsync(serviceAccount.Id, userId, accessClient);
var results =
await _accessPolicyRepository.GetServiceAccountGrantedPoliciesPermissionDetailsAsync(serviceAccount.Id,
userId, accessClient);
return new ServiceAccountGrantedPoliciesPermissionDetailsResponseModel(results);
}
}

View File

@ -1,184 +0,0 @@
#nullable enable
using System.ComponentModel.DataAnnotations;
using Bit.Core.Exceptions;
using Bit.Core.SecretsManager.Entities;
namespace Bit.Api.SecretsManager.Models.Request;
public class AccessPoliciesCreateRequest
{
private static void CheckForDistinctAccessPolicies(IReadOnlyCollection<BaseAccessPolicy> accessPolicies)
{
var distinctAccessPolicies = accessPolicies.DistinctBy(baseAccessPolicy =>
{
return baseAccessPolicy switch
{
UserProjectAccessPolicy ap => new Tuple<Guid?, Guid?>(ap.OrganizationUserId, ap.GrantedProjectId),
GroupProjectAccessPolicy ap => new Tuple<Guid?, Guid?>(ap.GroupId, ap.GrantedProjectId),
ServiceAccountProjectAccessPolicy ap => new Tuple<Guid?, Guid?>(ap.ServiceAccountId,
ap.GrantedProjectId),
UserServiceAccountAccessPolicy ap => new Tuple<Guid?, Guid?>(ap.OrganizationUserId,
ap.GrantedServiceAccountId),
GroupServiceAccountAccessPolicy ap => new Tuple<Guid?, Guid?>(ap.GroupId, ap.GrantedServiceAccountId),
_ => throw new ArgumentException("Unsupported access policy type provided.", nameof(baseAccessPolicy)),
};
}).ToList();
if (accessPolicies.Count != distinctAccessPolicies.Count)
{
throw new BadRequestException("Resources must be unique");
}
}
public IEnumerable<AccessPolicyRequest>? UserAccessPolicyRequests { get; set; }
public IEnumerable<AccessPolicyRequest>? GroupAccessPolicyRequests { get; set; }
public IEnumerable<AccessPolicyRequest>? ServiceAccountAccessPolicyRequests { get; set; }
public List<BaseAccessPolicy> ToBaseAccessPoliciesForProject(Guid grantedProjectId, Guid organizationId)
{
if (UserAccessPolicyRequests == null && GroupAccessPolicyRequests == null && ServiceAccountAccessPolicyRequests == null)
{
throw new BadRequestException("No creation requests provided.");
}
var userAccessPolicies = UserAccessPolicyRequests?
.Select(x => x.ToUserProjectAccessPolicy(grantedProjectId, organizationId)).ToList();
var groupAccessPolicies = GroupAccessPolicyRequests?
.Select(x => x.ToGroupProjectAccessPolicy(grantedProjectId, organizationId)).ToList();
var serviceAccountAccessPolicies = ServiceAccountAccessPolicyRequests?
.Select(x => x.ToServiceAccountProjectAccessPolicy(grantedProjectId, organizationId)).ToList();
var policies = new List<BaseAccessPolicy>();
if (userAccessPolicies != null)
{
policies.AddRange(userAccessPolicies);
}
if (groupAccessPolicies != null)
{
policies.AddRange(groupAccessPolicies);
}
if (serviceAccountAccessPolicies != null)
{
policies.AddRange(serviceAccountAccessPolicies);
}
CheckForDistinctAccessPolicies(policies);
return policies;
}
public List<BaseAccessPolicy> ToBaseAccessPoliciesForServiceAccount(Guid grantedServiceAccountId, Guid organizationId)
{
if (UserAccessPolicyRequests == null && GroupAccessPolicyRequests == null)
{
throw new BadRequestException("No creation requests provided.");
}
var userAccessPolicies = UserAccessPolicyRequests?
.Select(x => x.ToUserServiceAccountAccessPolicy(grantedServiceAccountId, organizationId)).ToList();
var groupAccessPolicies = GroupAccessPolicyRequests?
.Select(x => x.ToGroupServiceAccountAccessPolicy(grantedServiceAccountId, organizationId)).ToList();
var policies = new List<BaseAccessPolicy>();
if (userAccessPolicies != null)
{
policies.AddRange(userAccessPolicies);
}
if (groupAccessPolicies != null)
{
policies.AddRange(groupAccessPolicies);
}
CheckForDistinctAccessPolicies(policies);
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
{
[Required]
public Guid GranteeId { get; set; }
[Required]
public bool Read { get; set; }
[Required]
public bool Write { get; set; }
public UserProjectAccessPolicy ToUserProjectAccessPolicy(Guid projectId, Guid organizationId) =>
new()
{
OrganizationUserId = GranteeId,
GrantedProjectId = projectId,
GrantedProject = new Project { OrganizationId = organizationId, Id = projectId },
Read = Read,
Write = Write
};
public GroupProjectAccessPolicy ToGroupProjectAccessPolicy(Guid projectId, Guid organizationId) =>
new()
{
GroupId = GranteeId,
GrantedProjectId = projectId,
GrantedProject = new Project { OrganizationId = organizationId, Id = projectId },
Read = Read,
Write = Write
};
public ServiceAccountProjectAccessPolicy ToServiceAccountProjectAccessPolicy(Guid projectId, Guid organizationId) =>
new()
{
ServiceAccountId = GranteeId,
GrantedProjectId = projectId,
GrantedProject = new Project { OrganizationId = organizationId, Id = projectId },
Read = Read,
Write = Write
};
public UserServiceAccountAccessPolicy ToUserServiceAccountAccessPolicy(Guid id, Guid organizationId) =>
new()
{
OrganizationUserId = GranteeId,
GrantedServiceAccountId = id,
GrantedServiceAccount = new ServiceAccount() { OrganizationId = organizationId, Id = id },
Read = Read,
Write = Write
};
public GroupServiceAccountAccessPolicy ToGroupServiceAccountAccessPolicy(Guid id, Guid organizationId) =>
new()
{
GroupId = GranteeId,
GrantedServiceAccountId = id,
GrantedServiceAccount = new ServiceAccount() { OrganizationId = organizationId, Id = id },
Read = Read,
Write = Write
};
}

View File

@ -0,0 +1,67 @@
#nullable enable
using System.ComponentModel.DataAnnotations;
using Bit.Core.SecretsManager.Entities;
namespace Bit.Api.SecretsManager.Models.Request;
public class AccessPolicyRequest
{
[Required]
public Guid GranteeId { get; set; }
[Required]
public bool Read { get; set; }
[Required]
public bool Write { get; set; }
public UserProjectAccessPolicy ToUserProjectAccessPolicy(Guid projectId, Guid organizationId) =>
new()
{
OrganizationUserId = GranteeId,
GrantedProjectId = projectId,
GrantedProject = new Project { OrganizationId = organizationId, Id = projectId },
Read = Read,
Write = Write
};
public GroupProjectAccessPolicy ToGroupProjectAccessPolicy(Guid projectId, Guid organizationId) =>
new()
{
GroupId = GranteeId,
GrantedProjectId = projectId,
GrantedProject = new Project { OrganizationId = organizationId, Id = projectId },
Read = Read,
Write = Write
};
public ServiceAccountProjectAccessPolicy ToServiceAccountProjectAccessPolicy(Guid projectId, Guid organizationId) =>
new()
{
ServiceAccountId = GranteeId,
GrantedProjectId = projectId,
GrantedProject = new Project { OrganizationId = organizationId, Id = projectId },
Read = Read,
Write = Write
};
public UserServiceAccountAccessPolicy ToUserServiceAccountAccessPolicy(Guid id, Guid organizationId) =>
new()
{
OrganizationUserId = GranteeId,
GrantedServiceAccountId = id,
GrantedServiceAccount = new ServiceAccount() { OrganizationId = organizationId, Id = id },
Read = Read,
Write = Write
};
public GroupServiceAccountAccessPolicy ToGroupServiceAccountAccessPolicy(Guid id, Guid organizationId) =>
new()
{
GroupId = GranteeId,
GrantedServiceAccountId = id,
GrantedServiceAccount = new ServiceAccount() { OrganizationId = organizationId, Id = id },
Read = Read,
Write = Write
};
}

View File

@ -1,12 +0,0 @@
using System.ComponentModel.DataAnnotations;
namespace Bit.Api.SecretsManager.Models.Request;
public class AccessPolicyUpdateRequest
{
[Required]
public bool Read { get; set; }
[Required]
public bool Write { get; set; }
}

View File

@ -1,4 +1,5 @@
using Bit.Core.Exceptions;
using Bit.Api.SecretsManager.Utilities;
using Bit.Core.Exceptions;
using Bit.Core.SecretsManager.Entities;
using Bit.Core.SecretsManager.Models.Data;
@ -10,29 +11,6 @@ public class PeopleAccessPoliciesRequestModel
public IEnumerable<AccessPolicyRequest> GroupAccessPolicyRequests { get; set; }
private static void CheckForDistinctAccessPolicies(IReadOnlyCollection<BaseAccessPolicy> accessPolicies)
{
var distinctAccessPolicies = accessPolicies.DistinctBy(baseAccessPolicy =>
{
return baseAccessPolicy switch
{
UserProjectAccessPolicy ap => new Tuple<Guid?, Guid?>(ap.OrganizationUserId, ap.GrantedProjectId),
GroupProjectAccessPolicy ap => new Tuple<Guid?, Guid?>(ap.GroupId, ap.GrantedProjectId),
ServiceAccountProjectAccessPolicy ap => new Tuple<Guid?, Guid?>(ap.ServiceAccountId,
ap.GrantedProjectId),
UserServiceAccountAccessPolicy ap => new Tuple<Guid?, Guid?>(ap.OrganizationUserId,
ap.GrantedServiceAccountId),
GroupServiceAccountAccessPolicy ap => new Tuple<Guid?, Guid?>(ap.GroupId, ap.GrantedServiceAccountId),
_ => throw new ArgumentException("Unsupported access policy type provided.", nameof(baseAccessPolicy))
};
}).ToList();
if (accessPolicies.Count != distinctAccessPolicies.Count)
{
throw new BadRequestException("Resources must be unique");
}
}
public ProjectPeopleAccessPolicies ToProjectPeopleAccessPolicies(Guid grantedProjectId, Guid organizationId)
{
var userAccessPolicies = UserAccessPolicyRequests?
@ -51,7 +29,8 @@ public class PeopleAccessPoliciesRequestModel
policies.AddRange(groupAccessPolicies);
}
CheckForDistinctAccessPolicies(policies);
AccessPolicyHelpers.CheckForDistinctAccessPolicies(policies);
AccessPolicyHelpers.CheckAccessPoliciesHaveReadPermission(policies);
return new ProjectPeopleAccessPolicies
{
@ -62,7 +41,8 @@ public class PeopleAccessPoliciesRequestModel
};
}
public ServiceAccountPeopleAccessPolicies ToServiceAccountPeopleAccessPolicies(Guid grantedServiceAccountId, Guid organizationId)
public ServiceAccountPeopleAccessPolicies ToServiceAccountPeopleAccessPolicies(Guid grantedServiceAccountId,
Guid organizationId)
{
var userAccessPolicies = UserAccessPolicyRequests?
.Select(x => x.ToUserServiceAccountAccessPolicy(grantedServiceAccountId, organizationId)).ToList();
@ -81,7 +61,7 @@ public class PeopleAccessPoliciesRequestModel
policies.AddRange(groupAccessPolicies);
}
CheckForDistinctAccessPolicies(policies);
AccessPolicyHelpers.CheckForDistinctAccessPolicies(policies);
if (!policies.All(ap => ap.Read && ap.Write))
{

View File

@ -1,40 +0,0 @@
using Bit.Core.Models.Api;
using Bit.Core.SecretsManager.Entities;
namespace Bit.Api.SecretsManager.Models.Response;
public class ProjectAccessPoliciesResponseModel : ResponseModel
{
private const string _objectName = "projectAccessPolicies";
public ProjectAccessPoliciesResponseModel(IEnumerable<BaseAccessPolicy> baseAccessPolicies)
: base(_objectName)
{
foreach (var baseAccessPolicy in baseAccessPolicies)
{
switch (baseAccessPolicy)
{
case UserProjectAccessPolicy accessPolicy:
UserAccessPolicies.Add(new UserProjectAccessPolicyResponseModel(accessPolicy));
break;
case GroupProjectAccessPolicy accessPolicy:
GroupAccessPolicies.Add(new GroupProjectAccessPolicyResponseModel(accessPolicy));
break;
case ServiceAccountProjectAccessPolicy accessPolicy:
ServiceAccountAccessPolicies.Add(
new ServiceAccountProjectAccessPolicyResponseModel(accessPolicy));
break;
}
}
}
public ProjectAccessPoliciesResponseModel() : base(_objectName)
{
}
public List<UserProjectAccessPolicyResponseModel> UserAccessPolicies { get; set; } = new();
public List<GroupProjectAccessPolicyResponseModel> GroupAccessPolicies { get; set; } = new();
public List<ServiceAccountProjectAccessPolicyResponseModel> ServiceAccountAccessPolicies { get; set; } = new();
}

View File

@ -1,14 +0,0 @@
using Microsoft.AspNetCore.Authorization.Infrastructure;
namespace Bit.Core.SecretsManager.AuthorizationRequirements;
public class AccessPolicyOperationRequirement : OperationAuthorizationRequirement
{
}
public static class AccessPolicyOperations
{
public static readonly AccessPolicyOperationRequirement Create = new() { Name = nameof(Create) };
public static readonly AccessPolicyOperationRequirement Update = new() { Name = nameof(Update) };
public static readonly AccessPolicyOperationRequirement Delete = new() { Name = nameof(Delete) };
}

View File

@ -1,8 +0,0 @@
using Bit.Core.SecretsManager.Entities;
namespace Bit.Core.SecretsManager.Commands.AccessPolicies.Interfaces;
public interface ICreateAccessPoliciesCommand
{
Task<IEnumerable<BaseAccessPolicy>> CreateManyAsync(List<BaseAccessPolicy> accessPolicies);
}

View File

@ -1,6 +0,0 @@
namespace Bit.Core.SecretsManager.Commands.AccessPolicies.Interfaces;
public interface IDeleteAccessPolicyCommand
{
Task DeleteAsync(Guid id);
}

View File

@ -1,8 +0,0 @@
using Bit.Core.SecretsManager.Entities;
namespace Bit.Core.SecretsManager.Commands.AccessPolicies.Interfaces;
public interface IUpdateAccessPolicyCommand
{
public Task<BaseAccessPolicy> UpdateAsync(Guid id, bool read, bool write);
}

View File

@ -9,11 +9,6 @@ namespace Bit.Core.SecretsManager.Repositories;
public interface IAccessPolicyRepository
{
Task<List<BaseAccessPolicy>> CreateManyAsync(List<BaseAccessPolicy> baseAccessPolicies);
Task<bool> AccessPolicyExists(BaseAccessPolicy baseAccessPolicy);
Task<BaseAccessPolicy?> GetByIdAsync(Guid id);
Task<IEnumerable<BaseAccessPolicy>> GetManyByGrantedProjectIdAsync(Guid id, Guid userId);
Task ReplaceAsync(BaseAccessPolicy baseAccessPolicy);
Task DeleteAsync(Guid id);
Task<IEnumerable<BaseAccessPolicy>> GetPeoplePoliciesByGrantedProjectIdAsync(Guid id, Guid userId);
Task<IEnumerable<BaseAccessPolicy>> ReplaceProjectPeopleAsync(ProjectPeopleAccessPolicies peopleAccessPolicies, Guid userId);
Task<PeopleGrantees> GetPeopleGranteesAsync(Guid organizationId, Guid currentUserId);

View File

@ -12,8 +12,6 @@ public interface IServiceAccountRepository
Task<ServiceAccount> CreateAsync(ServiceAccount serviceAccount);
Task ReplaceAsync(ServiceAccount serviceAccount);
Task DeleteManyByIdAsync(IEnumerable<Guid> ids);
Task<bool> UserHasReadAccessToServiceAccount(Guid id, Guid userId);
Task<bool> UserHasWriteAccessToServiceAccount(Guid id, Guid userId);
Task<IEnumerable<ServiceAccount>> GetManyByOrganizationIdWriteAccessAsync(Guid organizationId, Guid userId, AccessClientType accessType);
Task<(bool Read, bool Write)> AccessToServiceAccountAsync(Guid id, Guid userId, AccessClientType accessType);
Task<Dictionary<Guid, (bool Read, bool Write)>> AccessToServiceAccountsAsync(IEnumerable<Guid> ids, Guid userId,

View File

@ -11,7 +11,6 @@ using Bit.Core.Entities;
using Bit.Core.Enums;
using Bit.Core.SecretsManager.Entities;
using Bit.Core.SecretsManager.Repositories;
using Bit.Test.Common.Helpers;
using Xunit;
namespace Bit.Api.IntegrationTest.SecretsManager.Controllers;
@ -25,10 +24,10 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
private readonly HttpClient _client;
private readonly ApiApplicationFactory _factory;
private readonly IProjectRepository _projectRepository;
private readonly IServiceAccountRepository _serviceAccountRepository;
private readonly IGroupRepository _groupRepository;
private readonly LoginHelper _loginHelper;
private readonly IProjectRepository _projectRepository;
private readonly IServiceAccountRepository _serviceAccountRepository;
private string _email = null!;
private SecretsManagerOrganizationHelper _organizationHelper = null!;
@ -64,359 +63,8 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
[InlineData(true, false, false)]
[InlineData(true, false, true)]
[InlineData(true, true, false)]
public async Task CreateProjectAccessPolicies_SmAccessDenied_NotFound(bool useSecrets, bool accessSecrets, bool organizationEnabled)
{
var (org, _) = await _organizationHelper.Initialize(useSecrets, accessSecrets, organizationEnabled);
await _loginHelper.LoginAsync(_email);
var (projectId, serviceAccountId) = await CreateProjectAndServiceAccountAsync(org.Id);
var request = new AccessPoliciesCreateRequest
{
ServiceAccountAccessPolicyRequests = new List<AccessPolicyRequest>
{
new() { GranteeId = serviceAccountId, Read = true, Write = true },
},
};
var response = await _client.PostAsJsonAsync($"/projects/{projectId}/access-policies", request);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task CreateProjectAccessPolicies_NoPermission()
{
// Create a new account as a user
var (org, _) = await _organizationHelper.Initialize(true, true, true);
var (email, _) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true);
await _loginHelper.LoginAsync(email);
var (projectId, serviceAccountId) = await CreateProjectAndServiceAccountAsync(org.Id);
var request = new AccessPoliciesCreateRequest
{
ServiceAccountAccessPolicyRequests = new List<AccessPolicyRequest>
{
new() { GranteeId = serviceAccountId, Read = true, Write = true },
},
};
var response = await _client.PostAsJsonAsync($"/projects/{projectId}/access-policies", request);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Theory]
[InlineData(PermissionType.RunAsAdmin)]
[InlineData(PermissionType.RunAsUserWithPermission)]
public async Task CreateProjectAccessPolicies_MismatchedOrgIds_NotFound(PermissionType permissionType)
{
var (org, _) = await _organizationHelper.Initialize(true, true, true);
await _loginHelper.LoginAsync(_email);
var (projectId, serviceAccountId) = await CreateProjectAndServiceAccountAsync(org.Id, true);
await SetupProjectAndServiceAccountPermissionAsync(permissionType, projectId, serviceAccountId);
var request = new AccessPoliciesCreateRequest
{
ServiceAccountAccessPolicyRequests = new List<AccessPolicyRequest>
{
new() { GranteeId = serviceAccountId, Read = true, Write = true },
},
};
var response = await _client.PostAsJsonAsync($"/projects/{projectId}/access-policies", request);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Theory]
[InlineData(PermissionType.RunAsAdmin)]
[InlineData(PermissionType.RunAsUserWithPermission)]
public async Task CreateProjectAccessPolicies_Success(PermissionType permissionType)
{
var (org, _) = await _organizationHelper.Initialize(true, true, true);
await _loginHelper.LoginAsync(_email);
var (projectId, serviceAccountId) = await CreateProjectAndServiceAccountAsync(org.Id);
await SetupProjectAndServiceAccountPermissionAsync(permissionType, projectId, serviceAccountId);
var request = new AccessPoliciesCreateRequest
{
ServiceAccountAccessPolicyRequests = new List<AccessPolicyRequest>
{
new() { GranteeId = serviceAccountId, Read = true, Write = true },
},
};
var response = await _client.PostAsJsonAsync($"/projects/{projectId}/access-policies", request);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<ProjectAccessPoliciesResponseModel>();
Assert.NotNull(result);
Assert.Equal(serviceAccountId, result.ServiceAccountAccessPolicies.First().ServiceAccountId);
Assert.True(result.ServiceAccountAccessPolicies.First().Read);
Assert.True(result.ServiceAccountAccessPolicies.First().Write);
AssertHelper.AssertRecent(result.ServiceAccountAccessPolicies.First().RevisionDate);
AssertHelper.AssertRecent(result.ServiceAccountAccessPolicies.First().CreationDate);
var createdAccessPolicy =
await _accessPolicyRepository.GetByIdAsync(result.ServiceAccountAccessPolicies.First().Id);
Assert.NotNull(createdAccessPolicy);
Assert.Equal(result.ServiceAccountAccessPolicies.First().Read, createdAccessPolicy.Read);
Assert.Equal(result.ServiceAccountAccessPolicies.First().Write, createdAccessPolicy.Write);
Assert.Equal(result.ServiceAccountAccessPolicies.First().Id, createdAccessPolicy.Id);
AssertHelper.AssertRecent(createdAccessPolicy.CreationDate);
AssertHelper.AssertRecent(createdAccessPolicy.RevisionDate);
}
[Theory]
[InlineData(false, false, false)]
[InlineData(false, false, true)]
[InlineData(false, true, false)]
[InlineData(false, true, true)]
[InlineData(true, false, false)]
[InlineData(true, false, true)]
[InlineData(true, true, false)]
public async Task UpdateAccessPolicy_SmAccessDenied_NotFound(bool useSecrets, bool accessSecrets, bool organizationEnabled)
{
var (org, _) = await _organizationHelper.Initialize(useSecrets, accessSecrets, organizationEnabled);
await _loginHelper.LoginAsync(_email);
var initData = await SetupAccessPolicyRequest(org.Id);
const bool expectedRead = true;
const bool expectedWrite = false;
var request = new AccessPolicyUpdateRequest { Read = expectedRead, Write = expectedWrite };
var response = await _client.PutAsJsonAsync($"/access-policies/{initData.AccessPolicyId}", request);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task UpdateAccessPolicy_NoPermission()
{
// Create a new account as a user
await _organizationHelper.Initialize(true, true, true);
var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true);
await _loginHelper.LoginAsync(email);
var initData = await SetupAccessPolicyRequest(orgUser.OrganizationId);
const bool expectedRead = true;
const bool expectedWrite = false;
var request = new AccessPolicyUpdateRequest { Read = expectedRead, Write = expectedWrite };
var response = await _client.PutAsJsonAsync($"/access-policies/{initData.AccessPolicyId}", request);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Theory]
[InlineData(PermissionType.RunAsAdmin)]
[InlineData(PermissionType.RunAsUserWithPermission)]
public async Task UpdateAccessPolicy_Success(PermissionType permissionType)
{
var (org, _) = await _organizationHelper.Initialize(true, true, true);
await _loginHelper.LoginAsync(_email);
var initData = await SetupAccessPolicyRequest(org.Id);
if (permissionType == PermissionType.RunAsUserWithPermission)
{
var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true);
await _loginHelper.LoginAsync(email);
var accessPolicies = new List<BaseAccessPolicy>
{
new UserProjectAccessPolicy
{
GrantedProjectId = initData.ProjectId, OrganizationUserId = orgUser.Id, Read = true, Write = true,
},
};
await _accessPolicyRepository.CreateManyAsync(accessPolicies);
}
const bool expectedRead = true;
const bool expectedWrite = false;
var request = new AccessPolicyUpdateRequest { Read = expectedRead, Write = expectedWrite };
var response = await _client.PutAsJsonAsync($"/access-policies/{initData.AccessPolicyId}", request);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<ServiceAccountProjectAccessPolicyResponseModel>();
Assert.NotNull(result);
Assert.Equal(expectedRead, result.Read);
Assert.Equal(expectedWrite, result.Write);
AssertHelper.AssertRecent(result.RevisionDate);
var updatedAccessPolicy = await _accessPolicyRepository.GetByIdAsync(result.Id);
Assert.NotNull(updatedAccessPolicy);
Assert.Equal(expectedRead, updatedAccessPolicy.Read);
Assert.Equal(expectedWrite, updatedAccessPolicy.Write);
AssertHelper.AssertRecent(updatedAccessPolicy.RevisionDate);
}
[Theory]
[InlineData(false, false, false)]
[InlineData(false, false, true)]
[InlineData(false, true, false)]
[InlineData(false, true, true)]
[InlineData(true, false, false)]
[InlineData(true, false, true)]
[InlineData(true, true, false)]
public async Task DeleteAccessPolicy_SmAccessDenied_NotFound(bool useSecrets, bool accessSecrets, bool organizationEnabled)
{
var (org, _) = await _organizationHelper.Initialize(useSecrets, accessSecrets, organizationEnabled);
await _loginHelper.LoginAsync(_email);
var initData = await SetupAccessPolicyRequest(org.Id);
var response = await _client.DeleteAsync($"/access-policies/{initData.AccessPolicyId}");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task DeleteAccessPolicy_NoPermission()
{
// Create a new account as a user
await _organizationHelper.Initialize(true, true, true);
var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true);
await _loginHelper.LoginAsync(email);
var initData = await SetupAccessPolicyRequest(orgUser.OrganizationId);
var response = await _client.DeleteAsync($"/access-policies/{initData.AccessPolicyId}");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Theory]
[InlineData(PermissionType.RunAsAdmin)]
[InlineData(PermissionType.RunAsUserWithPermission)]
public async Task DeleteAccessPolicy_Success(PermissionType permissionType)
{
var (org, _) = await _organizationHelper.Initialize(true, true, true);
await _loginHelper.LoginAsync(_email);
var initData = await SetupAccessPolicyRequest(org.Id);
if (permissionType == PermissionType.RunAsUserWithPermission)
{
var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true);
await _loginHelper.LoginAsync(email);
var accessPolicies = new List<BaseAccessPolicy>
{
new UserProjectAccessPolicy
{
GrantedProjectId = initData.ProjectId, OrganizationUserId = orgUser.Id, Read = true, Write = true,
},
};
await _accessPolicyRepository.CreateManyAsync(accessPolicies);
}
var response = await _client.DeleteAsync($"/access-policies/{initData.AccessPolicyId}");
response.EnsureSuccessStatusCode();
var test = await _accessPolicyRepository.GetByIdAsync(initData.AccessPolicyId);
Assert.Null(test);
}
[Fact]
public async Task GetProjectAccessPolicies_ReturnsEmpty()
{
var (org, _) = await _organizationHelper.Initialize(true, true, true);
await _loginHelper.LoginAsync(_email);
var project = await _projectRepository.CreateAsync(new Project
{
OrganizationId = org.Id,
Name = _mockEncryptedString,
});
var response = await _client.GetAsync($"/projects/{project.Id}/access-policies");
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<ProjectAccessPoliciesResponseModel>();
Assert.NotNull(result);
Assert.Empty(result.UserAccessPolicies);
Assert.Empty(result.GroupAccessPolicies);
Assert.Empty(result.ServiceAccountAccessPolicies);
}
[Theory]
[InlineData(false, false, false)]
[InlineData(false, false, true)]
[InlineData(false, true, false)]
[InlineData(false, true, true)]
[InlineData(true, false, false)]
[InlineData(true, false, true)]
[InlineData(true, true, false)]
public async Task GetProjectAccessPolicies_SmAccessDenied_NotFound(bool useSecrets, bool accessSecrets, bool organizationEnabled)
{
var (org, _) = await _organizationHelper.Initialize(useSecrets, accessSecrets, organizationEnabled);
await _loginHelper.LoginAsync(_email);
var initData = await SetupAccessPolicyRequest(org.Id);
var response = await _client.GetAsync($"/projects/{initData.ProjectId}/access-policies");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task GetProjectAccessPolicies_NoPermission()
{
// Create a new account as a user
await _organizationHelper.Initialize(true, true, true);
var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true);
await _loginHelper.LoginAsync(email);
var initData = await SetupAccessPolicyRequest(orgUser.OrganizationId);
var response = await _client.GetAsync($"/projects/{initData.ProjectId}/access-policies");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Theory]
[InlineData(PermissionType.RunAsAdmin)]
[InlineData(PermissionType.RunAsUserWithPermission)]
public async Task GetProjectAccessPolicies(PermissionType permissionType)
{
var (org, _) = await _organizationHelper.Initialize(true, true, true);
await _loginHelper.LoginAsync(_email);
var initData = await SetupAccessPolicyRequest(org.Id);
if (permissionType == PermissionType.RunAsUserWithPermission)
{
var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true);
await _loginHelper.LoginAsync(email);
var accessPolicies = new List<BaseAccessPolicy>
{
new UserProjectAccessPolicy
{
GrantedProjectId = initData.ProjectId, OrganizationUserId = orgUser.Id, Read = true, Write = true,
},
};
await _accessPolicyRepository.CreateManyAsync(accessPolicies);
}
var response = await _client.GetAsync($"/projects/{initData.ProjectId}/access-policies");
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<ProjectAccessPoliciesResponseModel>();
Assert.NotNull(result?.ServiceAccountAccessPolicies);
Assert.Single(result.ServiceAccountAccessPolicies);
}
[Theory]
[InlineData(false, false, false)]
[InlineData(false, false, true)]
[InlineData(false, true, false)]
[InlineData(false, true, true)]
[InlineData(true, false, false)]
[InlineData(true, false, true)]
[InlineData(true, true, false)]
public async Task GetPeoplePotentialGrantees_SmAccessDenied_NotFound(bool useSecrets, bool accessSecrets, bool organizationEnabled)
public async Task GetPeoplePotentialGrantees_SmAccessDenied_NotFound(bool useSecrets, bool accessSecrets,
bool organizationEnabled)
{
var (org, _) = await _organizationHelper.Initialize(useSecrets, accessSecrets, organizationEnabled);
await _loginHelper.LoginAsync(_email);
@ -460,7 +108,8 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
[InlineData(true, false, false)]
[InlineData(true, false, true)]
[InlineData(true, true, false)]
public async Task GetServiceAccountPotentialGrantees_SmAccessDenied_NotFound(bool useSecrets, bool accessSecrets, bool organizationEnabled)
public async Task GetServiceAccountPotentialGrantees_SmAccessDenied_NotFound(bool useSecrets, bool accessSecrets,
bool organizationEnabled)
{
var (org, _) = await _organizationHelper.Initialize(useSecrets, accessSecrets, organizationEnabled);
await _loginHelper.LoginAsync(_email);
@ -482,7 +131,7 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
await _serviceAccountRepository.CreateAsync(new ServiceAccount
{
OrganizationId = org.Id,
Name = _mockEncryptedString,
Name = _mockEncryptedString
});
@ -508,7 +157,7 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
var serviceAccount = await _serviceAccountRepository.CreateAsync(new ServiceAccount
{
OrganizationId = org.Id,
Name = _mockEncryptedString,
Name = _mockEncryptedString
});
if (permissionType == PermissionType.RunAsUserWithPermission)
@ -517,16 +166,15 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
await _loginHelper.LoginAsync(email);
await _accessPolicyRepository.CreateManyAsync(
new List<BaseAccessPolicy>
[
new UserServiceAccountAccessPolicy
{
new UserServiceAccountAccessPolicy
{
GrantedServiceAccountId = serviceAccount.Id,
OrganizationUserId = orgUser.Id,
Read = true,
Write = true,
},
});
GrantedServiceAccountId = serviceAccount.Id,
OrganizationUserId = orgUser.Id,
Read = true,
Write = true
}
]);
}
var response =
@ -549,7 +197,8 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
[InlineData(true, false, false)]
[InlineData(true, false, true)]
[InlineData(true, true, false)]
public async Task GetProjectPotentialGrantees_SmAccessDenied_NotFound(bool useSecrets, bool accessSecrets, bool organizationEnabled)
public async Task GetProjectPotentialGrantees_SmAccessDenied_NotFound(bool useSecrets, bool accessSecrets,
bool organizationEnabled)
{
var (org, _) = await _organizationHelper.Initialize(useSecrets, accessSecrets, organizationEnabled);
await _loginHelper.LoginAsync(_email);
@ -593,7 +242,7 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
var project = await _projectRepository.CreateAsync(new Project
{
OrganizationId = org.Id,
Name = _mockEncryptedString,
Name = _mockEncryptedString
});
if (permissionType == PermissionType.RunAsUserWithPermission)
@ -602,13 +251,15 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
await _loginHelper.LoginAsync(email);
await _accessPolicyRepository.CreateManyAsync(
new List<BaseAccessPolicy>
[
new UserProjectAccessPolicy
{
new UserProjectAccessPolicy
{
GrantedProjectId = project.Id, OrganizationUserId = orgUser.Id, Read = true, Write = true,
},
});
GrantedProjectId = project.Id,
OrganizationUserId = orgUser.Id,
Read = true,
Write = true
}
]);
}
var response =
@ -631,7 +282,8 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
[InlineData(true, false, false)]
[InlineData(true, false, true)]
[InlineData(true, true, false)]
public async Task GetProjectPeopleAccessPolicies_SmAccessDenied_NotFound(bool useSecrets, bool accessSecrets, bool organizationEnabled)
public async Task GetProjectPeopleAccessPolicies_SmAccessDenied_NotFound(bool useSecrets, bool accessSecrets,
bool organizationEnabled)
{
var (org, _) = await _organizationHelper.Initialize(useSecrets, accessSecrets, organizationEnabled);
await _loginHelper.LoginAsync(_email);
@ -713,9 +365,11 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
[InlineData(true, false, false)]
[InlineData(true, false, true)]
[InlineData(true, true, false)]
public async Task PutProjectPeopleAccessPolicies_SmAccessDenied_NotFound(bool useSecrets, bool accessSecrets, bool organizationEnabled)
public async Task PutProjectPeopleAccessPolicies_SmAccessDenied_NotFound(bool useSecrets, bool accessSecrets,
bool organizationEnabled)
{
var (_, organizationUser) = await _organizationHelper.Initialize(useSecrets, accessSecrets, organizationEnabled);
var (_, organizationUser) =
await _organizationHelper.Initialize(useSecrets, accessSecrets, organizationEnabled);
await _loginHelper.LoginAsync(_email);
var (project, request) = await SetupProjectPeopleRequestAsync(PermissionType.RunAsAdmin, organizationUser);
@ -795,13 +449,6 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
result.UserAccessPolicies.First().OrganizationUserId);
Assert.True(result.UserAccessPolicies.First().Read);
Assert.True(result.UserAccessPolicies.First().Write);
var createdAccessPolicy =
await _accessPolicyRepository.GetByIdAsync(result.UserAccessPolicies.First().Id);
Assert.NotNull(createdAccessPolicy);
Assert.Equal(result.UserAccessPolicies.First().Read, createdAccessPolicy.Read);
Assert.Equal(result.UserAccessPolicies.First().Write, createdAccessPolicy.Write);
Assert.Equal(result.UserAccessPolicies.First().Id, createdAccessPolicy.Id);
}
[Theory]
@ -812,14 +459,15 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
[InlineData(true, false, false)]
[InlineData(true, false, true)]
[InlineData(true, true, false)]
public async Task GetServiceAccountPeopleAccessPolicies_SmAccessDenied_NotFound(bool useSecrets, bool accessSecrets, bool organizationEnabled)
public async Task GetServiceAccountPeopleAccessPolicies_SmAccessDenied_NotFound(bool useSecrets, bool accessSecrets,
bool organizationEnabled)
{
var (org, _) = await _organizationHelper.Initialize(useSecrets, accessSecrets, organizationEnabled);
await _loginHelper.LoginAsync(_email);
var serviceAccount = await _serviceAccountRepository.CreateAsync(new ServiceAccount
{
OrganizationId = org.Id,
Name = _mockEncryptedString,
Name = _mockEncryptedString
});
var response = await _client.GetAsync($"/service-accounts/{serviceAccount.Id}/access-policies/people");
@ -835,7 +483,7 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
var serviceAccount = await _serviceAccountRepository.CreateAsync(new ServiceAccount
{
OrganizationId = org.Id,
Name = _mockEncryptedString,
Name = _mockEncryptedString
});
var response = await _client.GetAsync($"/service-accounts/{serviceAccount.Id}/access-policies/people");
@ -858,7 +506,7 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
var serviceAccount = await _serviceAccountRepository.CreateAsync(new ServiceAccount
{
OrganizationId = org.Id,
Name = _mockEncryptedString,
Name = _mockEncryptedString
});
var response = await _client.GetAsync($"/service-accounts/{serviceAccount.Id}/access-policies/people");
@ -893,14 +541,18 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
[InlineData(true, false, false)]
[InlineData(true, false, true)]
[InlineData(true, true, false)]
public async Task PutServiceAccountPeopleAccessPolicies_SmNotEnabled_NotFound(bool useSecrets, bool accessSecrets, bool organizationEnabled)
public async Task PutServiceAccountPeopleAccessPolicies_SmNotEnabled_NotFound(bool useSecrets, bool accessSecrets,
bool organizationEnabled)
{
var (_, organizationUser) = await _organizationHelper.Initialize(useSecrets, accessSecrets, organizationEnabled);
var (_, organizationUser) =
await _organizationHelper.Initialize(useSecrets, accessSecrets, organizationEnabled);
await _loginHelper.LoginAsync(_email);
var (serviceAccount, request) = await SetupServiceAccountPeopleRequestAsync(PermissionType.RunAsAdmin, organizationUser);
var (serviceAccount, request) =
await SetupServiceAccountPeopleRequestAsync(PermissionType.RunAsAdmin, organizationUser);
var response = await _client.PutAsJsonAsync($"/service-accounts/{serviceAccount.Id}/access-policies/people", request);
var response =
await _client.PutAsJsonAsync($"/service-accounts/{serviceAccount.Id}/access-policies/people", request);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
@ -914,7 +566,7 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
var serviceAccount = await _serviceAccountRepository.CreateAsync(new ServiceAccount
{
OrganizationId = org.Id,
Name = _mockEncryptedString,
Name = _mockEncryptedString
});
@ -926,7 +578,8 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
}
};
var response = await _client.PutAsJsonAsync($"/service-accounts/{serviceAccount.Id}/access-policies/people", request);
var response =
await _client.PutAsJsonAsync($"/service-accounts/{serviceAccount.Id}/access-policies/people", request);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
@ -951,7 +604,8 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
new() { GranteeId = group.Id, Read = true, Write = true }
};
var response = await _client.PutAsJsonAsync($"/service-accounts/{serviceAccount.Id}/access-policies/people", request);
var response =
await _client.PutAsJsonAsync($"/service-accounts/{serviceAccount.Id}/access-policies/people", request);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
@ -966,7 +620,8 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
var (serviceAccount, request) = await SetupServiceAccountPeopleRequestAsync(permissionType, organizationUser);
var response = await _client.PutAsJsonAsync($"/service-accounts/{serviceAccount.Id}/access-policies/people", request);
var response =
await _client.PutAsJsonAsync($"/service-accounts/{serviceAccount.Id}/access-policies/people", request);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<ServiceAccountPeopleAccessPoliciesResponseModel>();
@ -976,13 +631,6 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
result.UserAccessPolicies.First().OrganizationUserId);
Assert.True(result.UserAccessPolicies.First().Read);
Assert.True(result.UserAccessPolicies.First().Write);
var createdAccessPolicy =
await _accessPolicyRepository.GetByIdAsync(result.UserAccessPolicies.First().Id);
Assert.NotNull(createdAccessPolicy);
Assert.Equal(result.UserAccessPolicies.First().Read, createdAccessPolicy.Read);
Assert.Equal(result.UserAccessPolicies.First().Write, createdAccessPolicy.Write);
Assert.Equal(result.UserAccessPolicies.First().Id, createdAccessPolicy.Id);
}
[Theory]
@ -993,11 +641,12 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
[InlineData(true, false, false)]
[InlineData(true, false, true)]
[InlineData(true, true, false)]
public async Task GetServiceAccountGrantedPoliciesAsync_SmAccessDenied_ReturnsNotFound(bool useSecrets, bool accessSecrets, bool organizationEnabled)
public async Task GetServiceAccountGrantedPoliciesAsync_SmAccessDenied_ReturnsNotFound(bool useSecrets,
bool accessSecrets, bool organizationEnabled)
{
var (org, _) = await _organizationHelper.Initialize(useSecrets, accessSecrets, organizationEnabled);
await _loginHelper.LoginAsync(_email);
var initData = await SetupAccessPolicyRequest(org.Id);
var initData = await CreateServiceAccountProjectAccessPolicyAsync(org.Id);
var response = await _client.GetAsync($"/service-accounts/{initData.ServiceAccountId}/granted-policies");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -1012,13 +661,14 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
var serviceAccount = await _serviceAccountRepository.CreateAsync(new ServiceAccount
{
OrganizationId = org.Id,
Name = _mockEncryptedString,
Name = _mockEncryptedString
});
var response = await _client.GetAsync($"/service-accounts/{serviceAccount.Id}/granted-policies");
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<ServiceAccountGrantedPoliciesPermissionDetailsResponseModel>();
var result = await response.Content
.ReadFromJsonAsync<ServiceAccountGrantedPoliciesPermissionDetailsResponseModel>();
Assert.NotNull(result);
Assert.Empty(result.GrantedProjectPolicies);
@ -1032,7 +682,7 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true);
await _loginHelper.LoginAsync(email);
var initData = await SetupAccessPolicyRequest(orgUser.OrganizationId);
var initData = await CreateServiceAccountProjectAccessPolicyAsync(orgUser.OrganizationId);
var response = await _client.GetAsync($"/service-accounts/{initData.ServiceAccountId}/granted-policies");
@ -1046,7 +696,7 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
{
var (org, _) = await _organizationHelper.Initialize(true, true, true);
await _loginHelper.LoginAsync(_email);
var initData = await SetupAccessPolicyRequest(org.Id);
var initData = await CreateServiceAccountProjectAccessPolicyAsync(org.Id);
if (permissionType == PermissionType.RunAsUserWithPermission)
{
@ -1056,7 +706,10 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
{
new UserServiceAccountAccessPolicy
{
GrantedServiceAccountId = initData.ServiceAccountId, OrganizationUserId = orgUser.Id, Read = true, Write = true,
GrantedServiceAccountId = initData.ServiceAccountId,
OrganizationUserId = orgUser.Id,
Read = true,
Write = true
}
};
await _accessPolicyRepository.CreateManyAsync(accessPolicies);
@ -1083,12 +736,15 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
[InlineData(true, false, false)]
[InlineData(true, false, true)]
[InlineData(true, true, false)]
public async Task PutServiceAccountGrantedPoliciesAsync_SmNotEnabled_NotFound(bool useSecrets, bool accessSecrets, bool organizationEnabled)
public async Task PutServiceAccountGrantedPoliciesAsync_SmNotEnabled_NotFound(bool useSecrets, bool accessSecrets,
bool organizationEnabled)
{
var (_, organizationUser) = await _organizationHelper.Initialize(useSecrets, accessSecrets, organizationEnabled);
var (_, organizationUser) =
await _organizationHelper.Initialize(useSecrets, accessSecrets, organizationEnabled);
await _loginHelper.LoginAsync(_email);
var (serviceAccount, request) = await SetupServiceAccountGrantedPoliciesRequestAsync(PermissionType.RunAsAdmin, organizationUser, false);
var (serviceAccount, request) =
await SetupServiceAccountGrantedPoliciesRequestAsync(PermissionType.RunAsAdmin, organizationUser, false);
var response = await _client.PutAsJsonAsync($"/service-accounts/{serviceAccount.Id}/granted-policies", request);
@ -1120,12 +776,14 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
[Theory]
[InlineData(PermissionType.RunAsAdmin)]
[InlineData(PermissionType.RunAsUserWithPermission)]
public async Task PutServiceAccountGrantedPoliciesAsync_MismatchedOrgIds_ReturnsNotFound(PermissionType permissionType)
public async Task PutServiceAccountGrantedPoliciesAsync_MismatchedOrgIds_ReturnsNotFound(
PermissionType permissionType)
{
var (_, organizationUser) = await _organizationHelper.Initialize(true, true, true);
await _loginHelper.LoginAsync(_email);
var (serviceAccount, request) = await SetupServiceAccountGrantedPoliciesRequestAsync(permissionType, organizationUser, false);
var (serviceAccount, request) =
await SetupServiceAccountGrantedPoliciesRequestAsync(permissionType, organizationUser, false);
var newOrg = await _organizationHelper.CreateSmOrganizationAsync();
var project = await _projectRepository.CreateAsync(new Project
@ -1148,17 +806,21 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
[InlineData(PermissionType.RunAsAdmin, true)]
[InlineData(PermissionType.RunAsUserWithPermission, false)]
[InlineData(PermissionType.RunAsUserWithPermission, true)]
public async Task PutServiceAccountGrantedPoliciesAsync_Success(PermissionType permissionType, bool createPreviousAccessPolicy)
public async Task PutServiceAccountGrantedPoliciesAsync_Success(PermissionType permissionType,
bool createPreviousAccessPolicy)
{
var (_, organizationUser) = await _organizationHelper.Initialize(true, true, true);
await _loginHelper.LoginAsync(_email);
var (serviceAccount, request) = await SetupServiceAccountGrantedPoliciesRequestAsync(permissionType, organizationUser, createPreviousAccessPolicy);
var (serviceAccount, request) =
await SetupServiceAccountGrantedPoliciesRequestAsync(permissionType, organizationUser,
createPreviousAccessPolicy);
var response = await _client.PutAsJsonAsync($"/service-accounts/{serviceAccount.Id}/granted-policies", request);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<ServiceAccountGrantedPoliciesPermissionDetailsResponseModel>();
var result = await response.Content
.ReadFromJsonAsync<ServiceAccountGrantedPoliciesPermissionDetailsResponseModel>();
Assert.NotNull(result);
Assert.Equal(request.ProjectGrantedPolicyRequests.First().GrantedId,
@ -1177,11 +839,12 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
[InlineData(true, false, false)]
[InlineData(true, false, true)]
[InlineData(true, true, false)]
public async Task GetProjectServiceAccountsAccessPoliciesAsync_SmAccessDenied_ReturnsNotFound(bool useSecrets, bool accessSecrets, bool organizationEnabled)
public async Task GetProjectServiceAccountsAccessPoliciesAsync_SmAccessDenied_ReturnsNotFound(bool useSecrets,
bool accessSecrets, bool organizationEnabled)
{
var (org, _) = await _organizationHelper.Initialize(useSecrets, accessSecrets, organizationEnabled);
await _loginHelper.LoginAsync(_email);
var initData = await SetupAccessPolicyRequest(org.Id);
var initData = await CreateServiceAccountProjectAccessPolicyAsync(org.Id);
var response = await _client.GetAsync($"/projects/{initData.ProjectId}/access-policies/service-accounts");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
@ -1196,7 +859,7 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
var project = await _projectRepository.CreateAsync(new Project
{
OrganizationId = org.Id,
Name = _mockEncryptedString,
Name = _mockEncryptedString
});
var response = await _client.GetAsync($"/projects/{project.Id}/access-policies/service-accounts");
@ -1216,7 +879,7 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true);
await _loginHelper.LoginAsync(email);
var initData = await SetupAccessPolicyRequest(orgUser.OrganizationId);
var initData = await CreateServiceAccountProjectAccessPolicyAsync(orgUser.OrganizationId);
var response = await _client.GetAsync($"/projects/{initData.ProjectId}/access-policies/service-accounts");
@ -1230,7 +893,7 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
{
var (org, _) = await _organizationHelper.Initialize(true, true, true);
await _loginHelper.LoginAsync(_email);
var initData = await SetupAccessPolicyRequest(org.Id);
var initData = await CreateServiceAccountProjectAccessPolicyAsync(org.Id);
if (permissionType == PermissionType.RunAsUserWithPermission)
{
@ -1240,7 +903,10 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
{
new UserProjectAccessPolicy
{
GrantedProjectId = initData.ProjectId, OrganizationUserId = orgUser.Id, Read = true, Write = true,
GrantedProjectId = initData.ProjectId,
OrganizationUserId = orgUser.Id,
Read = true,
Write = true
}
};
await _accessPolicyRepository.CreateManyAsync(accessPolicies);
@ -1372,37 +1038,23 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
Assert.Single(result.ServiceAccountAccessPolicies);
}
private async Task<RequestSetupData> SetupAccessPolicyRequest(Guid organizationId)
private async Task<(Guid ProjectId, Guid ServiceAccountId)> CreateServiceAccountProjectAccessPolicyAsync(
Guid organizationId)
{
var project = await _projectRepository.CreateAsync(new Project
{
OrganizationId = organizationId,
Name = _mockEncryptedString,
});
var (projectId, serviceAccountId) = await CreateProjectAndServiceAccountAsync(organizationId);
var serviceAccount = await _serviceAccountRepository.CreateAsync(new ServiceAccount
{
OrganizationId = organizationId,
Name = _mockEncryptedString,
});
var accessPolicy = await _accessPolicyRepository.CreateManyAsync(
await _accessPolicyRepository.CreateManyAsync(
[
new ServiceAccountProjectAccessPolicy
{
Read = true,
Write = true,
ServiceAccountId = serviceAccount.Id,
GrantedProjectId = project.Id,
ServiceAccountId = serviceAccountId,
GrantedProjectId = projectId
}
]);
return new RequestSetupData
{
ProjectId = project.Id,
ServiceAccountId = serviceAccount.Id,
AccessPolicyId = accessPolicy.First().Id,
};
return (projectId, serviceAccountId);
}
private async Task<(Project project, OrganizationUser currentUser)> SetupProjectPeoplePermissionAsync(
@ -1437,14 +1089,15 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
return (project, organizationUser);
}
private async Task<(ServiceAccount serviceAccount, OrganizationUser currentUser)> SetupServiceAccountPeoplePermissionAsync(
PermissionType permissionType,
OrganizationUser organizationUser)
private async Task<(ServiceAccount serviceAccount, OrganizationUser currentUser)>
SetupServiceAccountPeoplePermissionAsync(
PermissionType permissionType,
OrganizationUser organizationUser)
{
var serviceAccount = await _serviceAccountRepository.CreateAsync(new ServiceAccount
{
OrganizationId = organizationUser.OrganizationId,
Name = _mockEncryptedString,
Name = _mockEncryptedString
});
if (permissionType == PermissionType.RunAsUserWithPermission)
@ -1484,10 +1137,12 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
return (project, request);
}
private async Task<(ServiceAccount serviceAccount, PeopleAccessPoliciesRequestModel request)> SetupServiceAccountPeopleRequestAsync(
PermissionType permissionType, OrganizationUser organizationUser)
private async Task<(ServiceAccount serviceAccount, PeopleAccessPoliciesRequestModel request)>
SetupServiceAccountPeopleRequestAsync(
PermissionType permissionType, OrganizationUser organizationUser)
{
var (serviceAccount, currentUser) = await SetupServiceAccountPeoplePermissionAsync(permissionType, organizationUser);
var (serviceAccount, currentUser) =
await SetupServiceAccountPeoplePermissionAsync(permissionType, organizationUser);
var request = new PeopleAccessPoliciesRequestModel
{
UserAccessPolicyRequests = new List<AccessPolicyRequest>
@ -1510,47 +1165,24 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
var project = await _projectRepository.CreateAsync(new Project
{
OrganizationId = misMatchOrganization ? newOrg.Id : organizationId,
Name = _mockEncryptedString,
Name = _mockEncryptedString
});
var serviceAccount = await _serviceAccountRepository.CreateAsync(new ServiceAccount
{
OrganizationId = organizationId,
Name = _mockEncryptedString,
Name = _mockEncryptedString
});
return (project.Id, serviceAccount.Id);
}
private async Task SetupProjectAndServiceAccountPermissionAsync(PermissionType permissionType, Guid projectId,
Guid serviceAccountId)
private async Task<(ServiceAccount serviceAccount, ServiceAccountGrantedPoliciesRequestModel request)>
SetupServiceAccountGrantedPoliciesRequestAsync(
PermissionType permissionType, OrganizationUser organizationUser, bool createPreviousAccessPolicy)
{
if (permissionType == PermissionType.RunAsUserWithPermission)
{
var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true);
await _loginHelper.LoginAsync(email);
var accessPolicies = new List<BaseAccessPolicy>
{
new UserProjectAccessPolicy
{
GrantedProjectId = projectId, OrganizationUserId = orgUser.Id, Read = true, Write = true,
},
new UserServiceAccountAccessPolicy
{
GrantedServiceAccountId = serviceAccountId,
OrganizationUserId = orgUser.Id,
Read = true,
Write = true,
},
};
await _accessPolicyRepository.CreateManyAsync(accessPolicies);
}
}
private async Task<(ServiceAccount serviceAccount, ServiceAccountGrantedPoliciesRequestModel request)> SetupServiceAccountGrantedPoliciesRequestAsync(
PermissionType permissionType, OrganizationUser organizationUser, bool createPreviousAccessPolicy)
{
var (serviceAccount, currentUser) = await SetupServiceAccountPeoplePermissionAsync(permissionType, organizationUser);
var (serviceAccount, currentUser) =
await SetupServiceAccountPeoplePermissionAsync(permissionType, organizationUser);
var project = await _projectRepository.CreateAsync(new Project
{
Name = _mockEncryptedString,
@ -1560,8 +1192,8 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
{
new UserProjectAccessPolicy
{
GrantedProjectId = project.Id, OrganizationUserId = currentUser.Id, Read = true, Write = true,
},
GrantedProjectId = project.Id, OrganizationUserId = currentUser.Id, Read = true, Write = true
}
};
if (createPreviousAccessPolicy)
@ -1577,14 +1209,14 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
GrantedProjectId = anotherProject.Id,
OrganizationUserId = currentUser.Id,
Read = true,
Write = true,
Write = true
});
accessPolicies.Add(new ServiceAccountProjectAccessPolicy
{
GrantedProjectId = anotherProject.Id,
ServiceAccountId = serviceAccount.Id,
Read = true,
Write = true,
Write = true
});
}
@ -1626,7 +1258,7 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
{
ServiceAccountAccessPolicyRequests =
[
new() { GranteeId = serviceAccount.Id, Read = true, Write = true }
new AccessPolicyRequest { GranteeId = serviceAccount.Id, Read = true, Write = true }
]
};
@ -1658,11 +1290,4 @@ public class AccessPoliciesControllerTests : IClassFixture<ApiApplicationFactory
return (project, request);
}
private class RequestSetupData
{
public Guid ProjectId { get; set; }
public Guid AccessPolicyId { get; set; }
public Guid ServiceAccountId { get; set; }
}
}

View File

@ -169,7 +169,7 @@ public class ProjectsControllerTests : IClassFixture<ApiApplicationFactory>, IAs
Assert.Null(createdProject.DeletedDate);
// Check permissions have been bootstrapped.
var accessPolicies = await _accessPolicyRepository.GetManyByGrantedProjectIdAsync(createdProject.Id, currentUserId);
var accessPolicies = await _accessPolicyRepository.GetPeoplePoliciesByGrantedProjectIdAsync(createdProject.Id, currentUserId);
Assert.NotNull(accessPolicies);
var ap = (UserProjectAccessPolicy)accessPolicies.First();
Assert.Equal(createdProject.Id, ap.GrantedProjectId);