1
0
mirror of https://github.com/bitwarden/server.git synced 2025-04-05 05:00:19 -05:00

[SM-465] Add access policy on service account creation (#2649)

* Add access policy on service account creation
This commit is contained in:
Thomas Avery 2023-02-02 12:25:14 -06:00 committed by GitHub
parent 6390aaa011
commit 0ce95ec147
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 101 additions and 25 deletions

View File

@ -1,4 +1,5 @@
using Bit.Core.SecretsManager.Commands.ServiceAccounts.Interfaces;
using Bit.Core.Repositories;
using Bit.Core.SecretsManager.Commands.ServiceAccounts.Interfaces;
using Bit.Core.SecretsManager.Entities;
using Bit.Core.SecretsManager.Repositories;
@ -6,15 +7,34 @@ namespace Bit.Commercial.Core.SecretsManager.Commands.ServiceAccounts;
public class CreateServiceAccountCommand : ICreateServiceAccountCommand
{
private readonly IAccessPolicyRepository _accessPolicyRepository;
private readonly IOrganizationUserRepository _organizationUserRepository;
private readonly IServiceAccountRepository _serviceAccountRepository;
public CreateServiceAccountCommand(IServiceAccountRepository serviceAccountRepository)
public CreateServiceAccountCommand(
IAccessPolicyRepository accessPolicyRepository,
IOrganizationUserRepository organizationUserRepository,
IServiceAccountRepository serviceAccountRepository)
{
_accessPolicyRepository = accessPolicyRepository;
_organizationUserRepository = organizationUserRepository;
_serviceAccountRepository = serviceAccountRepository;
}
public async Task<ServiceAccount> CreateAsync(ServiceAccount serviceAccount)
public async Task<ServiceAccount> CreateAsync(ServiceAccount serviceAccount, Guid userId)
{
return await _serviceAccountRepository.CreateAsync(serviceAccount);
var createdServiceAccount = await _serviceAccountRepository.CreateAsync(serviceAccount);
var user = await _organizationUserRepository.GetByOrganizationAsync(createdServiceAccount.OrganizationId,
userId);
var accessPolicy = new UserServiceAccountAccessPolicy
{
OrganizationUserId = user.Id,
GrantedServiceAccountId = createdServiceAccount.Id,
Read = true,
Write = true,
};
await _accessPolicyRepository.CreateManyAsync(new List<BaseAccessPolicy> { accessPolicy });
return createdServiceAccount;
}
}

View File

@ -138,7 +138,7 @@ public class AccessPolicyRepository : BaseEntityFrameworkRepository, IAccessPoli
}
}
public async Task<IEnumerable<Core.SecretsManager.Entities.BaseAccessPolicy>?> GetManyByProjectId(Guid id)
public async Task<IEnumerable<Core.SecretsManager.Entities.BaseAccessPolicy>> GetManyByGrantedProjectIdAsync(Guid id)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
@ -153,10 +153,25 @@ public class AccessPolicyRepository : BaseEntityFrameworkRepository, IAccessPoli
.Include(ap => ((ServiceAccountProjectAccessPolicy)ap).ServiceAccount)
.ToListAsync();
return !entities.Any() ? null : entities.Select(MapToCore);
return entities.Select(MapToCore);
}
}
public async Task<IEnumerable<Core.SecretsManager.Entities.BaseAccessPolicy>> GetManyByGrantedServiceAccountIdAsync(Guid id)
{
using var scope = ServiceScopeFactory.CreateScope();
var dbContext = GetDatabaseContext(scope);
var entities = await dbContext.AccessPolicies.Where(ap =>
((UserServiceAccountAccessPolicy)ap).GrantedServiceAccountId == id ||
((GroupServiceAccountAccessPolicy)ap).GrantedServiceAccountId == id)
.Include(ap => ((UserServiceAccountAccessPolicy)ap).OrganizationUser.User)
.Include(ap => ((GroupServiceAccountAccessPolicy)ap).Group)
.ToListAsync();
return entities.Select(MapToCore);
}
public async Task DeleteAsync(Guid id)
{
using (var scope = ServiceScopeFactory.CreateScope())
@ -178,6 +193,8 @@ public class AccessPolicyRepository : BaseEntityFrameworkRepository, IAccessPoli
UserProjectAccessPolicy ap => Mapper.Map<Core.SecretsManager.Entities.UserProjectAccessPolicy>(ap),
GroupProjectAccessPolicy ap => Mapper.Map<Core.SecretsManager.Entities.GroupProjectAccessPolicy>(ap),
ServiceAccountProjectAccessPolicy ap => Mapper.Map<Core.SecretsManager.Entities.ServiceAccountProjectAccessPolicy>(ap),
UserServiceAccountAccessPolicy ap => Mapper.Map<Core.SecretsManager.Entities.UserServiceAccountAccessPolicy>(ap),
GroupServiceAccountAccessPolicy ap => Mapper.Map<Core.SecretsManager.Entities.GroupServiceAccountAccessPolicy>(ap),
_ => throw new ArgumentException("Unsupported access policy type")
};
}

View File

@ -1,4 +1,6 @@
using Bit.Commercial.Core.SecretsManager.Commands.ServiceAccounts;
using Bit.Core.Entities;
using Bit.Core.Repositories;
using Bit.Core.SecretsManager.Entities;
using Bit.Core.SecretsManager.Repositories;
using Bit.Test.Common.AutoFixture;
@ -15,9 +17,18 @@ public class CreateServiceAccountCommandTests
[Theory]
[BitAutoData]
public async Task CreateAsync_CallsCreate(ServiceAccount data,
SutProvider<CreateServiceAccountCommand> sutProvider)
Guid userId,
SutProvider<CreateServiceAccountCommand> sutProvider)
{
await sutProvider.Sut.CreateAsync(data);
sutProvider.GetDependency<IOrganizationUserRepository>()
.GetByOrganizationAsync(Arg.Any<Guid>(), Arg.Any<Guid>())
.Returns(new OrganizationUser() { Id = userId });
sutProvider.GetDependency<IServiceAccountRepository>()
.CreateAsync(Arg.Any<ServiceAccount>())
.Returns(data);
await sutProvider.Sut.CreateAsync(data, userId);
await sutProvider.GetDependency<IServiceAccountRepository>().Received(1)
.CreateAsync(Arg.Is(AssertHelper.AssertPropertyEqual(data)));

View File

@ -40,7 +40,7 @@ public class AccessPoliciesController : Controller
[HttpGet("/projects/{id}/access-policies")]
public async Task<ProjectAccessPoliciesResponseModel> GetProjectAccessPoliciesAsync([FromRoute] Guid id)
{
var results = await _accessPolicyRepository.GetManyByProjectId(id);
var results = await _accessPolicyRepository.GetManyByGrantedProjectIdAsync(id);
return new ProjectAccessPoliciesResponseModel(results);
}

View File

@ -71,8 +71,8 @@ public class ServiceAccountsController : Controller
{
throw new NotFoundException();
}
var result = await _createServiceAccountCommand.CreateAsync(createRequest.ToServiceAccount(organizationId));
var userId = _userService.GetProperUserId(User).Value;
var result = await _createServiceAccountCommand.CreateAsync(createRequest.ToServiceAccount(organizationId), userId);
return new ServiceAccountResponseModel(result);
}

View File

@ -10,11 +10,6 @@ public class ProjectAccessPoliciesResponseModel : ResponseModel
public ProjectAccessPoliciesResponseModel(IEnumerable<BaseAccessPolicy> baseAccessPolicies)
: base(_objectName)
{
if (baseAccessPolicies == null)
{
return;
}
foreach (var baseAccessPolicy in baseAccessPolicies)
switch (baseAccessPolicy)
{

View File

@ -4,5 +4,5 @@ namespace Bit.Core.SecretsManager.Commands.ServiceAccounts.Interfaces;
public interface ICreateServiceAccountCommand
{
Task<ServiceAccount> CreateAsync(ServiceAccount serviceAccount);
Task<ServiceAccount> CreateAsync(ServiceAccount serviceAccount, Guid userId);
}

View File

@ -8,7 +8,8 @@ public interface IAccessPolicyRepository
Task<List<BaseAccessPolicy>> CreateManyAsync(List<BaseAccessPolicy> baseAccessPolicies);
Task<bool> AccessPolicyExists(BaseAccessPolicy baseAccessPolicy);
Task<BaseAccessPolicy?> GetByIdAsync(Guid id);
Task<IEnumerable<BaseAccessPolicy>?> GetManyByProjectId(Guid id);
Task<IEnumerable<BaseAccessPolicy>> GetManyByGrantedProjectIdAsync(Guid id);
Task<IEnumerable<BaseAccessPolicy>> GetManyByGrantedServiceAccountIdAsync(Guid id);
Task ReplaceAsync(BaseAccessPolicy baseAccessPolicy);
Task DeleteAsync(Guid id);
}

View File

@ -129,6 +129,26 @@ public class AccessPoliciesControllerTest : IClassFixture<ApiApplicationFactory>
Assert.Null(test);
}
[Fact]
public async Task GetProjectAccessPolicies_ReturnsEmpty()
{
var initialProject = await _projectRepository.CreateAsync(new Project
{
OrganizationId = _organization.Id,
Name = _mockEncryptedString,
});
var response = await _client.GetAsync($"/projects/{initialProject.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);
}
[Fact]
public async Task GetProjectAccessPolicies()
{

View File

@ -153,6 +153,15 @@ public class ServiceAccountsControllerTest : IClassFixture<ApiApplicationFactory
Assert.Equal(request.Name, createdServiceAccount.Name);
AssertHelper.AssertRecent(createdServiceAccount.RevisionDate);
AssertHelper.AssertRecent(createdServiceAccount.CreationDate);
// Check permissions have been bootstrapped.
var accessPolicies = await _accessPolicyRepository.GetManyByGrantedServiceAccountIdAsync(createdServiceAccount.Id);
Assert.NotNull(accessPolicies);
var ap = accessPolicies!.First();
Assert.True(ap.Read);
Assert.True(ap.Write);
AssertHelper.AssertRecent(ap.CreationDate);
AssertHelper.AssertRecent(ap.RevisionDate);
}
[Theory]

View File

@ -25,7 +25,7 @@ public class AccessPoliciesControllerTests
var result = await sutProvider.Sut.GetProjectAccessPoliciesAsync(id);
await sutProvider.GetDependency<IAccessPolicyRepository>().Received(1)
.GetManyByProjectId(Arg.Is(AssertHelper.AssertPropertyEqual(id)));
.GetManyByGrantedProjectIdAsync(Arg.Is(AssertHelper.AssertPropertyEqual(id)));
Assert.Empty(result.GroupAccessPolicies);
Assert.Empty(result.UserAccessPolicies);
@ -37,13 +37,13 @@ public class AccessPoliciesControllerTests
public async void GetAccessPoliciesByProject_Success(SutProvider<AccessPoliciesController> sutProvider, Guid id,
UserProjectAccessPolicy resultAccessPolicy)
{
sutProvider.GetDependency<IAccessPolicyRepository>().GetManyByProjectId(default)
sutProvider.GetDependency<IAccessPolicyRepository>().GetManyByGrantedProjectIdAsync(default)
.ReturnsForAnyArgs(new List<BaseAccessPolicy> { resultAccessPolicy });
var result = await sutProvider.Sut.GetProjectAccessPoliciesAsync(id);
await sutProvider.GetDependency<IAccessPolicyRepository>().Received(1)
.GetManyByProjectId(Arg.Is(AssertHelper.AssertPropertyEqual(id)));
.GetManyByGrantedProjectIdAsync(Arg.Is(AssertHelper.AssertPropertyEqual(id)));
Assert.Empty(result.GroupAccessPolicies);
Assert.NotEmpty(result.UserAccessPolicies);

View File

@ -66,14 +66,15 @@ public class ServiceAccountsControllerTests
[BitAutoData]
public async void CreateServiceAccount_Success(SutProvider<ServiceAccountsController> sutProvider, ServiceAccountCreateRequestModel data, Guid organizationId)
{
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(Guid.NewGuid());
sutProvider.GetDependency<ICurrentContext>().AccessSecretsManager(organizationId).Returns(true);
sutProvider.GetDependency<ICurrentContext>().OrganizationUser(default).ReturnsForAnyArgs(true);
var resultServiceAccount = data.ToServiceAccount(organizationId);
sutProvider.GetDependency<ICreateServiceAccountCommand>().CreateAsync(default).ReturnsForAnyArgs(resultServiceAccount);
sutProvider.GetDependency<ICreateServiceAccountCommand>().CreateAsync(default, default).ReturnsForAnyArgs(resultServiceAccount);
await sutProvider.Sut.CreateAsync(organizationId, data);
await sutProvider.GetDependency<ICreateServiceAccountCommand>().Received(1)
.CreateAsync(Arg.Any<ServiceAccount>());
.CreateAsync(Arg.Any<ServiceAccount>(), Arg.Any<Guid>());
}
[Theory]
@ -82,11 +83,13 @@ public class ServiceAccountsControllerTests
{
sutProvider.GetDependency<ICurrentContext>().OrganizationUser(default).ReturnsForAnyArgs(false);
var resultServiceAccount = data.ToServiceAccount(organizationId);
sutProvider.GetDependency<ICreateServiceAccountCommand>().CreateAsync(default).ReturnsForAnyArgs(resultServiceAccount);
sutProvider.GetDependency<ICreateServiceAccountCommand>().CreateAsync(default, default).ReturnsForAnyArgs(resultServiceAccount);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.CreateAsync(organizationId, data));
await sutProvider.GetDependency<ICreateServiceAccountCommand>().DidNotReceiveWithAnyArgs().CreateAsync(Arg.Any<ServiceAccount>());
await sutProvider.GetDependency<ICreateServiceAccountCommand>()
.DidNotReceiveWithAnyArgs()
.CreateAsync(Arg.Any<ServiceAccount>(), Arg.Any<Guid>());
}
[Theory]