1
0
mirror of https://github.com/bitwarden/server.git synced 2025-06-30 07:36:14 -05:00

[SM-654] Individual secret permissions (#4160)

* Add new data and request models

* Update authz handlers

* Update secret commands to handle access policy updates

* Update secret repository to handle access policy updates

* Update secrets controller to handle access policy updates

* Add tests

* Add integration tests for secret create
This commit is contained in:
Thomas Avery
2024-06-20 12:45:28 -05:00
committed by GitHub
parent 0e6e461602
commit 01d67dce48
30 changed files with 2141 additions and 342 deletions

View File

@ -5,6 +5,7 @@ using Bit.Api.IntegrationTest.SecretsManager.Helpers;
using Bit.Api.Models.Response;
using Bit.Api.SecretsManager.Models.Request;
using Bit.Api.SecretsManager.Models.Response;
using Bit.Core.Entities;
using Bit.Core.Enums;
using Bit.Core.SecretsManager.Entities;
using Bit.Core.SecretsManager.Repositories;
@ -148,20 +149,14 @@ public class SecretsControllerTests : IClassFixture<ApiApplicationFactory>, IAsy
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task CreateWithoutProject_RunAsAdmin_Success()
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task Create_WithoutProject_RunAsAdmin_Success(bool withAccessPolicies)
{
var (org, _) = await _organizationHelper.Initialize(true, true, true);
await _loginHelper.LoginAsync(_email);
var (organizationUser, request) = await SetupSecretCreateRequestAsync(withAccessPolicies);
var request = new SecretCreateRequestModel
{
Key = _mockEncryptedString,
Value = _mockEncryptedString,
Note = _mockEncryptedString,
};
var response = await _client.PostAsJsonAsync($"/organizations/{org.Id}/secrets", request);
var response = await _client.PostAsJsonAsync($"/organizations/{organizationUser.OrganizationId}/secrets", request);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<SecretResponseModel>();
@ -180,6 +175,17 @@ public class SecretsControllerTests : IClassFixture<ApiApplicationFactory>, IAsy
AssertHelper.AssertRecent(createdSecret.RevisionDate);
AssertHelper.AssertRecent(createdSecret.CreationDate);
Assert.Null(createdSecret.DeletedDate);
if (withAccessPolicies)
{
var secretAccessPolicies = await _accessPolicyRepository.GetSecretAccessPoliciesAsync(result.Id, organizationUser.UserId!.Value);
Assert.NotNull(secretAccessPolicies);
Assert.NotEmpty(secretAccessPolicies.UserAccessPolicies);
Assert.Equal(organizationUser.Id, secretAccessPolicies.UserAccessPolicies.First().OrganizationUserId);
Assert.Equal(result.Id, secretAccessPolicies.UserAccessPolicies.First().GrantedSecretId);
Assert.True(secretAccessPolicies.UserAccessPolicies.First().Read);
Assert.True(secretAccessPolicies.UserAccessPolicies.First().Write);
}
}
[Fact]
@ -243,65 +249,52 @@ public class SecretsControllerTests : IClassFixture<ApiApplicationFactory>, IAsy
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Theory]
[InlineData(PermissionType.RunAsAdmin)]
[InlineData(PermissionType.RunAsUserWithPermission)]
public async Task CreateWithProject_Success(PermissionType permissionType)
[Fact]
public async Task Create_RunAsServiceAccount_WithAccessPolicies_NotFound()
{
var (org, orgAdminUser) = await _organizationHelper.Initialize(true, true, true);
await _loginHelper.LoginAsync(_email);
var (organizationUser, secretRequest) =
await SetupSecretWithProjectCreateRequestAsync(PermissionType.RunAsServiceAccountWithPermission, true);
var accessType = AccessClientType.NoAccessCheck;
var response =
await _client.PostAsJsonAsync($"/organizations/{organizationUser.OrganizationId}/secrets", secretRequest);
var project = await _projectRepository.CreateAsync(new Project()
{
Id = new Guid(),
OrganizationId = org.Id,
Name = _mockEncryptedString
});
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
var orgUserId = (Guid)orgAdminUser.UserId!;
[Theory]
[InlineData(PermissionType.RunAsAdmin, false)]
[InlineData(PermissionType.RunAsAdmin, true)]
[InlineData(PermissionType.RunAsUserWithPermission, false)]
[InlineData(PermissionType.RunAsUserWithPermission, true)]
[InlineData(PermissionType.RunAsServiceAccountWithPermission, false)]
public async Task Create_WithProject_Success(PermissionType permissionType, bool withAccessPolicies)
{
var (organizationUser, secretRequest) = await SetupSecretWithProjectCreateRequestAsync(permissionType, withAccessPolicies);
if (permissionType == PermissionType.RunAsUserWithPermission)
{
var (email, orgUser) = await _organizationHelper.CreateNewUser(OrganizationUserType.User, true);
await _loginHelper.LoginAsync(email);
await _loginHelper.LoginAsync(email);
accessType = AccessClientType.User;
var accessPolicies = new List<BaseAccessPolicy>
{
new UserProjectAccessPolicy
{
GrantedProjectId = project.Id, OrganizationUserId = orgUser.Id , Read = true, Write = true,
},
};
orgUserId = (Guid)orgUser.UserId!;
await _accessPolicyRepository.CreateManyAsync(accessPolicies);
}
var secretRequest = new SecretCreateRequestModel()
{
Key = _mockEncryptedString,
Value = _mockEncryptedString,
Note = _mockEncryptedString,
ProjectIds = new[] { project.Id },
};
var secretResponse = await _client.PostAsJsonAsync($"/organizations/{org.Id}/secrets", secretRequest);
var secretResponse = await _client.PostAsJsonAsync($"/organizations/{organizationUser.OrganizationId}/secrets", secretRequest);
secretResponse.EnsureSuccessStatusCode();
var secretResult = await secretResponse.Content.ReadFromJsonAsync<SecretResponseModel>();
var result = await secretResponse.Content.ReadFromJsonAsync<SecretResponseModel>();
var result = (await _secretRepository.GetManyDetailsByProjectIdAsync(project.Id, orgUserId, accessType)).First();
var secret = result.Secret;
Assert.NotNull(result);
var secret = await _secretRepository.GetByIdAsync(result.Id);
Assert.Equal(secret.Id, result.Id);
Assert.Equal(secret.OrganizationId, result.OrganizationId);
Assert.Equal(secret.Key, result.Key);
Assert.Equal(secret.Value, result.Value);
Assert.Equal(secret.Note, result.Note);
Assert.Equal(secret.CreationDate, result.CreationDate);
Assert.Equal(secret.RevisionDate, result.RevisionDate);
Assert.NotNull(secretResult);
Assert.Equal(secret.Id, secretResult.Id);
Assert.Equal(secret.OrganizationId, secretResult.OrganizationId);
Assert.Equal(secret.Key, secretResult.Key);
Assert.Equal(secret.Value, secretResult.Value);
Assert.Equal(secret.Note, secretResult.Note);
Assert.Equal(secret.CreationDate, secretResult.CreationDate);
Assert.Equal(secret.RevisionDate, secretResult.RevisionDate);
if (withAccessPolicies)
{
var secretAccessPolicies = await _accessPolicyRepository.GetSecretAccessPoliciesAsync(secret.Id, organizationUser.UserId!.Value);
Assert.NotNull(secretAccessPolicies);
Assert.NotEmpty(secretAccessPolicies.UserAccessPolicies);
Assert.Equal(organizationUser.Id, secretAccessPolicies.UserAccessPolicies.First().OrganizationUserId);
Assert.Equal(secret.Id, secretAccessPolicies.UserAccessPolicies.First().GrantedSecretId);
Assert.True(secretAccessPolicies.UserAccessPolicies.First().Read);
Assert.True(secretAccessPolicies.UserAccessPolicies.First().Write);
}
}
[Theory]
@ -523,37 +516,24 @@ public class SecretsControllerTests : IClassFixture<ApiApplicationFactory>, IAsy
}
[Theory]
[InlineData(PermissionType.RunAsAdmin)]
[InlineData(PermissionType.RunAsUserWithPermission)]
[InlineData(PermissionType.RunAsServiceAccountWithPermission)]
public async Task Update_Success(PermissionType permissionType)
[InlineData(PermissionType.RunAsServiceAccountWithPermission, true)]
public async Task Update_RunAsServiceAccountWithAccessPolicyUpdate_NotFound(PermissionType permissionType, bool withAccessPolices)
{
var (org, _) = await _organizationHelper.Initialize(true, true, true);
var project = await _projectRepository.CreateAsync(new Project()
{
Id = Guid.NewGuid(),
OrganizationId = org.Id,
Name = _mockEncryptedString
});
var (secret, request) = await SetupSecretUpdateRequestAsync(permissionType, withAccessPolices);
await SetupProjectPermissionAndLoginAsync(permissionType, project);
var response = await _client.PutAsJsonAsync($"/secrets/{secret.Id}", request);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
var secret = await _secretRepository.CreateAsync(new Secret
{
OrganizationId = org.Id,
Key = _mockEncryptedString,
Value = _mockEncryptedString,
Note = _mockEncryptedString,
Projects = permissionType != PermissionType.RunAsAdmin ? new List<Project>() { project } : null
});
var request = new SecretUpdateRequestModel()
{
Key = _mockEncryptedString,
Value = "2.3Uk+WNBIoU5xzmVFNcoWzz==|1MsPIYuRfdOHfu/0uY6H2Q==|/98xy4wb6pHP1VTZ9JcNCYgQjEUMFPlqJgCwRk1YXKg=",
Note = _mockEncryptedString,
ProjectIds = permissionType != PermissionType.RunAsAdmin ? new Guid[] { project.Id } : null
};
[Theory]
[InlineData(PermissionType.RunAsAdmin, false)]
[InlineData(PermissionType.RunAsAdmin, true)]
[InlineData(PermissionType.RunAsUserWithPermission, false)]
[InlineData(PermissionType.RunAsUserWithPermission, true)]
[InlineData(PermissionType.RunAsServiceAccountWithPermission, false)]
public async Task Update_Success(PermissionType permissionType, bool withAccessPolices)
{
var (secret, request) = await SetupSecretUpdateRequestAsync(permissionType, withAccessPolices);
var response = await _client.PutAsJsonAsync($"/secrets/{secret.Id}", request);
response.EnsureSuccessStatusCode();
@ -575,6 +555,19 @@ public class SecretsControllerTests : IClassFixture<ApiApplicationFactory>, IAsy
Assert.Null(updatedSecret.DeletedDate);
Assert.NotEqual(secret.Value, updatedSecret.Value);
Assert.NotEqual(secret.RevisionDate, updatedSecret.RevisionDate);
if (withAccessPolices)
{
var secretAccessPolicies = await _accessPolicyRepository.GetSecretAccessPoliciesAsync(secret.Id,
request.AccessPoliciesRequests.UserAccessPolicyRequests.First().GranteeId);
Assert.NotNull(secretAccessPolicies);
Assert.NotEmpty(secretAccessPolicies.UserAccessPolicies);
Assert.Equal(request.AccessPoliciesRequests.UserAccessPolicyRequests.First().GranteeId,
secretAccessPolicies.UserAccessPolicies.First().OrganizationUserId);
Assert.Equal(secret.Id, secretAccessPolicies.UserAccessPolicies.First().GrantedSecretId);
Assert.True(secretAccessPolicies.UserAccessPolicies.First().Read);
Assert.True(secretAccessPolicies.UserAccessPolicies.First().Write);
}
}
[Fact]
@ -978,4 +971,153 @@ public class SecretsControllerTests : IClassFixture<ApiApplicationFactory>, IAsy
sa.RevisionDate = revisionDate;
await _serviceAccountRepository.ReplaceAsync(sa);
}
private async Task<(OrganizationUser, SecretCreateRequestModel)> SetupSecretCreateRequestAsync(
bool withAccessPolicies)
{
var (_, organizationUser) = await _organizationHelper.Initialize(true, true, true);
await _loginHelper.LoginAsync(_email);
var request = new SecretCreateRequestModel
{
Key = _mockEncryptedString,
Value = _mockEncryptedString,
Note = _mockEncryptedString
};
if (withAccessPolicies)
{
request.AccessPoliciesRequests = new SecretAccessPoliciesRequestsModel
{
UserAccessPolicyRequests =
[
new AccessPolicyRequest { GranteeId = organizationUser.Id, Read = true, Write = true }
],
GroupAccessPolicyRequests = [],
ServiceAccountAccessPolicyRequests = []
};
}
return (organizationUser, request);
}
private async Task<(OrganizationUser, SecretCreateRequestModel)> SetupSecretWithProjectCreateRequestAsync(
PermissionType permissionType, bool withAccessPolicies)
{
var (org, orgAdminUser) = await _organizationHelper.Initialize(true, true, true);
await _loginHelper.LoginAsync(_email);
var project = await _projectRepository.CreateAsync(new Project
{
Id = new Guid(),
OrganizationId = org.Id,
Name = _mockEncryptedString
});
var currentOrganizationUser = orgAdminUser;
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 = project.Id, OrganizationUserId = orgUser.Id, Read = true, Write = true
}
};
currentOrganizationUser = orgUser;
await _accessPolicyRepository.CreateManyAsync(accessPolicies);
}
if (permissionType == PermissionType.RunAsServiceAccountWithPermission)
{
var apiKeyDetails = await _organizationHelper.CreateNewServiceAccountApiKeyAsync();
await _loginHelper.LoginWithApiKeyAsync(apiKeyDetails);
var accessPolicies = new List<BaseAccessPolicy>
{
new ServiceAccountProjectAccessPolicy
{
GrantedProjectId = project.Id,
ServiceAccountId = apiKeyDetails.ApiKey.ServiceAccountId,
Read = true,
Write = true
}
};
await _accessPolicyRepository.CreateManyAsync(accessPolicies);
}
var secretRequest = new SecretCreateRequestModel
{
Key = _mockEncryptedString,
Value = _mockEncryptedString,
Note = _mockEncryptedString,
ProjectIds = [project.Id]
};
if (withAccessPolicies)
{
secretRequest.AccessPoliciesRequests = new SecretAccessPoliciesRequestsModel
{
UserAccessPolicyRequests =
[
new AccessPolicyRequest { GranteeId = currentOrganizationUser.Id, Read = true, Write = true }
],
GroupAccessPolicyRequests = [],
ServiceAccountAccessPolicyRequests = []
};
}
return (currentOrganizationUser, secretRequest);
}
private async Task<(Secret, SecretUpdateRequestModel)> SetupSecretUpdateRequestAsync(PermissionType permissionType,
bool withAccessPolicies)
{
var (org, adminOrgUser) = await _organizationHelper.Initialize(true, true, true);
var project = await _projectRepository.CreateAsync(new Project
{
Id = Guid.NewGuid(),
OrganizationId = org.Id,
Name = _mockEncryptedString
});
await SetupProjectPermissionAndLoginAsync(permissionType, project);
var secret = await _secretRepository.CreateAsync(new Secret
{
OrganizationId = org.Id,
Key = _mockEncryptedString,
Value = _mockEncryptedString,
Note = _mockEncryptedString,
Projects = permissionType != PermissionType.RunAsAdmin ? new List<Project> { project } : null
});
var request = new SecretUpdateRequestModel
{
Key = _mockEncryptedString,
Value =
"2.3Uk+WNBIoU5xzmVFNcoWzz==|1MsPIYuRfdOHfu/0uY6H2Q==|/98xy4wb6pHP1VTZ9JcNCYgQjEUMFPlqJgCwRk1YXKg=",
Note = _mockEncryptedString,
ProjectIds = permissionType != PermissionType.RunAsAdmin ? [project.Id] : null
};
if (!withAccessPolicies)
{
return (secret, request);
}
request.AccessPoliciesRequests = new SecretAccessPoliciesRequestsModel
{
UserAccessPolicyRequests =
[new AccessPolicyRequest { GranteeId = adminOrgUser.Id, Read = true, Write = true }],
GroupAccessPolicyRequests = [],
ServiceAccountAccessPolicyRequests = []
};
return (secret, request);
}
}

View File

@ -8,6 +8,8 @@ using Bit.Core.Exceptions;
using Bit.Core.SecretsManager.Commands.Secrets.Interfaces;
using Bit.Core.SecretsManager.Entities;
using Bit.Core.SecretsManager.Models.Data;
using Bit.Core.SecretsManager.Models.Data.AccessPolicyUpdates;
using Bit.Core.SecretsManager.Queries.AccessPolicies.Interfaces;
using Bit.Core.SecretsManager.Queries.Interfaces;
using Bit.Core.SecretsManager.Queries.Secrets.Interfaces;
using Bit.Core.SecretsManager.Repositories;
@ -130,119 +132,158 @@ public class SecretsControllerTests
[Theory]
[BitAutoData]
public async Task CreateSecret_NoAccess_Throws(SutProvider<SecretsController> sutProvider, SecretCreateRequestModel data, Guid organizationId, Guid userId)
public async Task CreateSecret_NoAccess_Throws(SutProvider<SecretsController> sutProvider,
SecretCreateRequestModel data, Guid organizationId)
{
// We currently only allow a secret to be in one project at a time
if (data.ProjectIds != null && data.ProjectIds.Length > 1)
{
data.ProjectIds = new Guid[] { data.ProjectIds.ElementAt(0) };
}
data = SetupSecretCreateRequest(sutProvider, data, organizationId);
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), data.ToSecret(organizationId),
Arg.Any<IEnumerable<IAuthorizationRequirement>>()).ReturnsForAnyArgs(AuthorizationResult.Failed());
var resultSecret = data.ToSecret(organizationId);
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<ICreateSecretCommand>().CreateAsync(default).ReturnsForAnyArgs(resultSecret);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.CreateAsync(organizationId, data));
await sutProvider.GetDependency<ICreateSecretCommand>().DidNotReceiveWithAnyArgs()
.CreateAsync(Arg.Any<Secret>());
.CreateAsync(Arg.Any<Secret>(), Arg.Any<SecretAccessPoliciesUpdates>());
}
[Theory]
[BitAutoData]
public async Task CreateSecret_Success(SutProvider<SecretsController> sutProvider, SecretCreateRequestModel data, Guid organizationId, Guid userId)
public async Task CreateSecret_NoAccessPolicyUpdates_Success(SutProvider<SecretsController> sutProvider,
SecretCreateRequestModel data, Guid organizationId)
{
// We currently only allow a secret to be in one project at a time
if (data.ProjectIds != null && data.ProjectIds.Length > 1)
{
data.ProjectIds = new Guid[] { data.ProjectIds.ElementAt(0) };
}
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), data.ToSecret(organizationId),
Arg.Any<IEnumerable<IAuthorizationRequirement>>()).ReturnsForAnyArgs(AuthorizationResult.Success());
var resultSecret = data.ToSecret(organizationId);
sutProvider.GetDependency<IUserService>().GetProperUserId(default).ReturnsForAnyArgs(userId);
sutProvider.GetDependency<ICreateSecretCommand>().CreateAsync(default).ReturnsForAnyArgs(resultSecret);
data = SetupSecretCreateRequest(sutProvider, data, organizationId);
await sutProvider.Sut.CreateAsync(organizationId, data);
await sutProvider.GetDependency<ICreateSecretCommand>().Received(1)
.CreateAsync(Arg.Any<Secret>());
.CreateAsync(Arg.Any<Secret>(), null);
}
[Theory]
[BitAutoData]
public async Task UpdateSecret_NoAccess_Throws(SutProvider<SecretsController> sutProvider, SecretUpdateRequestModel data, Guid secretId, Guid organizationId, Secret mockSecret)
public async Task CreateSecret_AccessPolicyUpdates_NoAccess_Throws(SutProvider<SecretsController> sutProvider,
SecretCreateRequestModel data, Guid organizationId)
{
// We currently only allow a secret to be in one project at a time
if (data.ProjectIds != null && data.ProjectIds.Length > 1)
{
data.ProjectIds = new Guid[] { data.ProjectIds.ElementAt(0) };
}
data = SetupSecretCreateRequest(sutProvider, data, organizationId, true);
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), data.ToSecret(secretId, organizationId),
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), Arg.Any<SecretAccessPoliciesUpdates>(),
Arg.Any<IEnumerable<IAuthorizationRequirement>>()).Returns(AuthorizationResult.Failed());
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.CreateAsync(organizationId, data));
await sutProvider.GetDependency<ICreateSecretCommand>().DidNotReceiveWithAnyArgs()
.CreateAsync(Arg.Any<Secret>(), Arg.Any<SecretAccessPoliciesUpdates>());
}
[Theory]
[BitAutoData]
public async Task CreateSecret_AccessPolicyUpdate_Success(SutProvider<SecretsController> sutProvider,
SecretCreateRequestModel data, Guid organizationId)
{
data = SetupSecretCreateRequest(sutProvider, data, organizationId, true);
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), Arg.Any<SecretAccessPoliciesUpdates>(),
Arg.Any<IEnumerable<IAuthorizationRequirement>>()).Returns(AuthorizationResult.Success());
await sutProvider.Sut.CreateAsync(organizationId, data);
await sutProvider.GetDependency<ICreateSecretCommand>().Received(1)
.CreateAsync(Arg.Any<Secret>(), Arg.Any<SecretAccessPoliciesUpdates>());
}
[Theory]
[BitAutoData]
public async Task UpdateSecret_NoAccess_Throws(SutProvider<SecretsController> sutProvider,
SecretUpdateRequestModel data, Secret currentSecret)
{
data = SetupSecretUpdateRequest(data);
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), Arg.Any<Secret>(),
Arg.Any<IEnumerable<IAuthorizationRequirement>>()).ReturnsForAnyArgs(AuthorizationResult.Failed());
sutProvider.GetDependency<ISecretRepository>().GetByIdAsync(secretId).ReturnsForAnyArgs(mockSecret);
sutProvider.GetDependency<ISecretRepository>().GetByIdAsync(currentSecret.Id).ReturnsForAnyArgs(currentSecret);
var resultSecret = data.ToSecret(secretId, organizationId);
sutProvider.GetDependency<IUpdateSecretCommand>().UpdateAsync(default).ReturnsForAnyArgs(resultSecret);
sutProvider.GetDependency<IUpdateSecretCommand>()
.UpdateAsync(Arg.Any<Secret>(), Arg.Any<SecretAccessPoliciesUpdates>())
.ReturnsForAnyArgs(data.ToSecret(currentSecret));
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.UpdateSecretAsync(secretId, data));
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.UpdateSecretAsync(currentSecret.Id, data));
await sutProvider.GetDependency<IUpdateSecretCommand>().DidNotReceiveWithAnyArgs()
.UpdateAsync(Arg.Any<Secret>());
.UpdateAsync(Arg.Any<Secret>(), Arg.Any<SecretAccessPoliciesUpdates>());
}
[Theory]
[BitAutoData]
public async Task UpdateSecret_SecretDoesNotExist_Throws(SutProvider<SecretsController> sutProvider, SecretUpdateRequestModel data, Guid secretId, Guid organizationId)
public async Task UpdateSecret_SecretDoesNotExist_Throws(SutProvider<SecretsController> sutProvider,
SecretUpdateRequestModel data, Secret currentSecret)
{
// We currently only allow a secret to be in one project at a time
if (data.ProjectIds != null && data.ProjectIds.Length > 1)
{
data.ProjectIds = new Guid[] { data.ProjectIds.ElementAt(0) };
}
data = SetupSecretUpdateRequest(data);
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), data.ToSecret(secretId, organizationId),
Arg.Any<IEnumerable<IAuthorizationRequirement>>()).ReturnsForAnyArgs(AuthorizationResult.Failed());
var resultSecret = data.ToSecret(secretId, organizationId);
sutProvider.GetDependency<IUpdateSecretCommand>().UpdateAsync(default).ReturnsForAnyArgs(resultSecret);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.UpdateSecretAsync(secretId, data));
await sutProvider.GetDependency<IUpdateSecretCommand>().DidNotReceiveWithAnyArgs()
.UpdateAsync(Arg.Any<Secret>());
}
[Theory]
[BitAutoData]
public async Task UpdateSecret_Success(SutProvider<SecretsController> sutProvider, SecretUpdateRequestModel data, Guid secretId, Guid organizationId, Secret mockSecret)
{
// We currently only allow a secret to be in one project at a time
if (data.ProjectIds != null && data.ProjectIds.Length > 1)
{
data.ProjectIds = new Guid[] { data.ProjectIds.ElementAt(0) };
}
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), data.ToSecret(secretId, organizationId),
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), Arg.Any<Secret>(),
Arg.Any<IEnumerable<IAuthorizationRequirement>>()).ReturnsForAnyArgs(AuthorizationResult.Success());
sutProvider.GetDependency<ISecretRepository>().GetByIdAsync(secretId).ReturnsForAnyArgs(mockSecret);
var resultSecret = data.ToSecret(secretId, organizationId);
sutProvider.GetDependency<IUpdateSecretCommand>().UpdateAsync(default).ReturnsForAnyArgs(resultSecret);
sutProvider.GetDependency<IUpdateSecretCommand>()
.UpdateAsync(Arg.Any<Secret>(), Arg.Any<SecretAccessPoliciesUpdates>())
.ReturnsForAnyArgs(data.ToSecret(currentSecret));
await sutProvider.Sut.UpdateSecretAsync(secretId, data);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.UpdateSecretAsync(currentSecret.Id, data));
await sutProvider.GetDependency<IUpdateSecretCommand>().DidNotReceiveWithAnyArgs()
.UpdateAsync(Arg.Any<Secret>(), Arg.Any<SecretAccessPoliciesUpdates>());
}
[Theory]
[BitAutoData]
public async Task UpdateSecret_NoAccessPolicyUpdates_Success(SutProvider<SecretsController> sutProvider,
SecretUpdateRequestModel data, Secret currentSecret)
{
data = SetupSecretUpdateRequest(data);
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), Arg.Any<Secret>(),
Arg.Any<IEnumerable<IAuthorizationRequirement>>()).ReturnsForAnyArgs(AuthorizationResult.Success());
sutProvider.GetDependency<ISecretRepository>().GetByIdAsync(currentSecret.Id).ReturnsForAnyArgs(currentSecret);
sutProvider.GetDependency<IUpdateSecretCommand>()
.UpdateAsync(Arg.Any<Secret>(), Arg.Any<SecretAccessPoliciesUpdates>())
.ReturnsForAnyArgs(data.ToSecret(currentSecret));
await sutProvider.Sut.UpdateSecretAsync(currentSecret.Id, data);
await sutProvider.GetDependency<IUpdateSecretCommand>().Received(1)
.UpdateAsync(Arg.Any<Secret>());
.UpdateAsync(Arg.Any<Secret>(), null);
}
[Theory]
[BitAutoData]
public async Task UpdateSecret_AccessPolicyUpdate_NoAccess_Throws(SutProvider<SecretsController> sutProvider,
SecretUpdateRequestModel data, Secret currentSecret, SecretAccessPoliciesUpdates accessPoliciesUpdates)
{
data = SetupSecretUpdateAccessPoliciesRequest(sutProvider, data, currentSecret, accessPoliciesUpdates);
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), Arg.Any<SecretAccessPoliciesUpdates>(),
Arg.Any<IEnumerable<IAuthorizationRequirement>>()).Returns(AuthorizationResult.Failed());
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.UpdateSecretAsync(currentSecret.Id, data));
await sutProvider.GetDependency<IUpdateSecretCommand>().DidNotReceiveWithAnyArgs()
.UpdateAsync(Arg.Any<Secret>(), Arg.Any<SecretAccessPoliciesUpdates>());
}
[Theory]
[BitAutoData]
public async Task UpdateSecret_AccessPolicyUpdate_Access_Success(SutProvider<SecretsController> sutProvider,
SecretUpdateRequestModel data, Secret currentSecret, SecretAccessPoliciesUpdates accessPoliciesUpdates)
{
data = SetupSecretUpdateAccessPoliciesRequest(sutProvider, data, currentSecret, accessPoliciesUpdates);
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), Arg.Any<SecretAccessPoliciesUpdates>(),
Arg.Any<IEnumerable<IAuthorizationRequirement>>()).Returns(AuthorizationResult.Success());
await sutProvider.Sut.UpdateSecretAsync(currentSecret.Id, data);
await sutProvider.GetDependency<IUpdateSecretCommand>().Received(1)
.UpdateAsync(Arg.Any<Secret>(), Arg.Any<SecretAccessPoliciesUpdates>());
}
[Theory]
@ -539,4 +580,62 @@ public class SecretsControllerTests
{
return nullLastSyncedDate ? null : DateTime.UtcNow.AddDays(-1);
}
private static SecretCreateRequestModel SetupSecretCreateRequest(SutProvider<SecretsController> sutProvider, SecretCreateRequestModel data, Guid organizationId, bool accessPolicyRequest = false)
{
// We currently only allow a secret to be in one project at a time
if (data.ProjectIds != null && data.ProjectIds.Length > 1)
{
data.ProjectIds = [data.ProjectIds.ElementAt(0)];
}
if (!accessPolicyRequest)
{
data.AccessPoliciesRequests = null;
}
sutProvider.GetDependency<ICreateSecretCommand>()
.CreateAsync(Arg.Any<Secret>(), Arg.Any<SecretAccessPoliciesUpdates>())
.ReturnsForAnyArgs(data.ToSecret(organizationId));
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), Arg.Any<Secret>(),
Arg.Any<IEnumerable<IAuthorizationRequirement>>()).Returns(AuthorizationResult.Success());
return data;
}
private static SecretUpdateRequestModel SetupSecretUpdateRequest(SecretUpdateRequestModel data, bool accessPolicyRequest = false)
{
// We currently only allow a secret to be in one project at a time
if (data.ProjectIds != null && data.ProjectIds.Length > 1)
{
data.ProjectIds = [data.ProjectIds.ElementAt(0)];
}
if (!accessPolicyRequest)
{
data.AccessPoliciesRequests = null;
}
return data;
}
private static SecretUpdateRequestModel SetupSecretUpdateAccessPoliciesRequest(SutProvider<SecretsController> sutProvider, SecretUpdateRequestModel data, Secret currentSecret, SecretAccessPoliciesUpdates accessPoliciesUpdates)
{
data = SetupSecretUpdateRequest(data, true);
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), Arg.Any<Secret>(),
Arg.Any<IEnumerable<IAuthorizationRequirement>>()).Returns(AuthorizationResult.Success());
sutProvider.GetDependency<ISecretRepository>().GetByIdAsync(currentSecret.Id).ReturnsForAnyArgs(currentSecret);
sutProvider.GetDependency<IUserService>().GetProperUserId(Arg.Any<ClaimsPrincipal>()).ReturnsForAnyArgs(Guid.NewGuid());
sutProvider.GetDependency<ISecretAccessPoliciesUpdatesQuery>()
.GetAsync(Arg.Any<SecretAccessPolicies>(), Arg.Any<Guid>())
.ReturnsForAnyArgs(accessPoliciesUpdates);
sutProvider.GetDependency<IUpdateSecretCommand>()
.UpdateAsync(Arg.Any<Secret>(), Arg.Any<SecretAccessPoliciesUpdates>())
.ReturnsForAnyArgs(data.ToSecret(currentSecret));
return data;
}
}

View File

@ -0,0 +1,119 @@
#nullable enable
using Bit.Core.SecretsManager.Entities;
using Bit.Core.SecretsManager.Enums.AccessPolicies;
using Bit.Core.SecretsManager.Models.Data;
using Bit.Core.Test.SecretsManager.AutoFixture.ProjectsFixture;
using Bit.Test.Common.AutoFixture.Attributes;
using Xunit;
namespace Bit.Core.Test.SecretsManager.Models;
[SutProviderCustomize]
[ProjectCustomize]
public class SecretAccessPoliciesTests
{
[Theory]
[BitAutoData]
public void GetPolicyUpdates_NoChanges_ReturnsEmptyList(SecretAccessPolicies data)
{
var result = data.GetPolicyUpdates(data);
Assert.Empty(result.UserAccessPolicyUpdates);
Assert.Empty(result.GroupAccessPolicyUpdates);
Assert.Empty(result.ServiceAccountAccessPolicyUpdates);
}
[Fact]
public void GetPolicyUpdates_ReturnsCorrectPolicyChanges()
{
var secretId = Guid.NewGuid();
var updatedId = Guid.NewGuid();
var createId = Guid.NewGuid();
var unChangedId = Guid.NewGuid();
var deleteId = Guid.NewGuid();
var existing = new SecretAccessPolicies
{
UserAccessPolicies = new List<UserSecretAccessPolicy>
{
new() { OrganizationUserId = updatedId, GrantedSecretId = secretId, Read = true, Write = true },
new() { OrganizationUserId = unChangedId, GrantedSecretId = secretId, Read = true, Write = true },
new() { OrganizationUserId = deleteId, GrantedSecretId = secretId, Read = true, Write = true }
},
GroupAccessPolicies = new List<GroupSecretAccessPolicy>
{
new() { GroupId = updatedId, GrantedSecretId = secretId, Read = true, Write = true },
new() { GroupId = unChangedId, GrantedSecretId = secretId, Read = true, Write = true },
new() { GroupId = deleteId, GrantedSecretId = secretId, Read = true, Write = true }
},
ServiceAccountAccessPolicies = new List<ServiceAccountSecretAccessPolicy>
{
new() { ServiceAccountId = updatedId, GrantedSecretId = secretId, Read = true, Write = true },
new() { ServiceAccountId = unChangedId, GrantedSecretId = secretId, Read = true, Write = true },
new() { ServiceAccountId = deleteId, GrantedSecretId = secretId, Read = true, Write = true }
}
};
var requested = new SecretAccessPolicies
{
UserAccessPolicies = new List<UserSecretAccessPolicy>
{
new() { OrganizationUserId = updatedId, GrantedSecretId = secretId, Read = true, Write = false },
new() { OrganizationUserId = createId, GrantedSecretId = secretId, Read = false, Write = true },
new() { OrganizationUserId = unChangedId, GrantedSecretId = secretId, Read = true, Write = true }
},
GroupAccessPolicies = new List<GroupSecretAccessPolicy>
{
new() { GroupId = updatedId, GrantedSecretId = secretId, Read = true, Write = false },
new() { GroupId = createId, GrantedSecretId = secretId, Read = false, Write = true },
new() { GroupId = unChangedId, GrantedSecretId = secretId, Read = true, Write = true }
},
ServiceAccountAccessPolicies = new List<ServiceAccountSecretAccessPolicy>
{
new() { ServiceAccountId = updatedId, GrantedSecretId = secretId, Read = true, Write = false },
new() { ServiceAccountId = createId, GrantedSecretId = secretId, Read = false, Write = true },
new() { ServiceAccountId = unChangedId, GrantedSecretId = secretId, Read = true, Write = true }
}
};
var result = existing.GetPolicyUpdates(requested);
Assert.Contains(createId, result.UserAccessPolicyUpdates
.Where(pu => pu.Operation == AccessPolicyOperation.Create)
.Select(pu => pu.AccessPolicy.OrganizationUserId!.Value));
Assert.Contains(createId, result.GroupAccessPolicyUpdates
.Where(pu => pu.Operation == AccessPolicyOperation.Create)
.Select(pu => pu.AccessPolicy.GroupId!.Value));
Assert.Contains(createId, result.ServiceAccountAccessPolicyUpdates
.Where(pu => pu.Operation == AccessPolicyOperation.Create)
.Select(pu => pu.AccessPolicy.ServiceAccountId!.Value));
Assert.Contains(deleteId, result.UserAccessPolicyUpdates
.Where(pu => pu.Operation == AccessPolicyOperation.Delete)
.Select(pu => pu.AccessPolicy.OrganizationUserId!.Value));
Assert.Contains(deleteId, result.GroupAccessPolicyUpdates
.Where(pu => pu.Operation == AccessPolicyOperation.Delete)
.Select(pu => pu.AccessPolicy.GroupId!.Value));
Assert.Contains(deleteId, result.ServiceAccountAccessPolicyUpdates
.Where(pu => pu.Operation == AccessPolicyOperation.Delete)
.Select(pu => pu.AccessPolicy.ServiceAccountId!.Value));
Assert.Contains(updatedId, result.UserAccessPolicyUpdates
.Where(pu => pu.Operation == AccessPolicyOperation.Update)
.Select(pu => pu.AccessPolicy.OrganizationUserId!.Value));
Assert.Contains(updatedId, result.GroupAccessPolicyUpdates
.Where(pu => pu.Operation == AccessPolicyOperation.Update)
.Select(pu => pu.AccessPolicy.GroupId!.Value));
Assert.Contains(updatedId, result.ServiceAccountAccessPolicyUpdates
.Where(pu => pu.Operation == AccessPolicyOperation.Update)
.Select(pu => pu.AccessPolicy.ServiceAccountId!.Value));
Assert.DoesNotContain(unChangedId, result.UserAccessPolicyUpdates
.Select(pu => pu.AccessPolicy.OrganizationUserId!.Value));
Assert.DoesNotContain(unChangedId, result.GroupAccessPolicyUpdates
.Select(pu => pu.AccessPolicy.GroupId!.Value));
Assert.DoesNotContain(unChangedId, result.ServiceAccountAccessPolicyUpdates
.Select(pu => pu.AccessPolicy.ServiceAccountId!.Value));
}
}