1
0
mirror of https://github.com/bitwarden/server synced 2025-12-06 00:03:34 +00:00

[PM-12474] Move to authorization to attibutes/handlers/requirements (#6001)

* Created ReadAllOrganizationUsersBasicInformationRequirement for use with Authorize attribute.

* Removed unused req and Handler and tests. Moved to new auth attribute

* Moved tests to integration tests with new response.

* Removed tests that were migrated to integration tests.

* Made string params Guids instead of parsing them manually in methods.

* Admin and Owner added to requirement.

* Added XML docs for basic get endpoint. Removed unused. Added another auth check. Inverted if check.

* Removed unused endpoint

* Added tests for requirement

* Added checks for both User and Custom

* Added org id check to validate the user being requested belongs to the org in the route.

* typo
This commit is contained in:
Jared McCannon
2025-07-15 07:52:47 -05:00
committed by GitHub
parent 93a00373d2
commit c4965350d1
8 changed files with 253 additions and 307 deletions

View File

@@ -0,0 +1,17 @@
using Bit.Core.Context;
using Bit.Core.Enums;
namespace Bit.Api.AdminConsole.Authorization.Requirements;
public class ManageGroupsOrUsersRequirement : IOrganizationRequirement
{
public async Task<bool> AuthorizeAsync(CurrentContextOrganization organizationClaims, Func<Task<bool>> isProviderUserForOrg) =>
organizationClaims switch
{
{ Type: OrganizationUserType.Owner } => true,
{ Type: OrganizationUserType.Admin } => true,
{ Permissions.ManageGroups: true } => true,
{ Permissions.ManageUsers: true } => true,
_ => await isProviderUserForOrg()
};
}

View File

@@ -1,6 +1,7 @@
// FIXME: Update this file to be null safe and then delete the line below
#nullable disable
using Bit.Api.AdminConsole.Authorization;
using Bit.Api.AdminConsole.Authorization.Requirements;
using Bit.Api.AdminConsole.Models.Request.Organizations;
using Bit.Api.AdminConsole.Models.Response.Organizations;
@@ -126,10 +127,11 @@ public class OrganizationUsersController : Controller
}
[HttpGet("{id}")]
public async Task<OrganizationUserDetailsResponseModel> Get(Guid id, bool includeGroups = false)
[Authorize<ManageUsersRequirement>]
public async Task<OrganizationUserDetailsResponseModel> Get(Guid orgId, Guid id, bool includeGroups = false)
{
var (organizationUser, collections) = await _organizationUserRepository.GetDetailsByIdWithCollectionsAsync(id);
if (organizationUser == null || !await _currentContext.ManageUsers(organizationUser.OrganizationId))
if (organizationUser == null || organizationUser.OrganizationId != orgId)
{
throw new NotFoundException();
}
@@ -148,16 +150,17 @@ public class OrganizationUsersController : Controller
return response;
}
/// <summary>
/// Returns a set of basic information about all members of the organization. This is available to all members of
/// the organization to manage collections. For this reason, it contains as little information as possible and no
/// cryptographic keys or other sensitive data.
/// </summary>
/// <param name="orgId">Organization identifier</param>
/// <returns>List of users for the organization.</returns>
[HttpGet("mini-details")]
[Authorize<MemberOrProviderRequirement>]
public async Task<ListResponseModel<OrganizationUserUserMiniDetailsResponseModel>> GetMiniDetails(Guid orgId)
{
var authorizationResult = await _authorizationService.AuthorizeAsync(User, new OrganizationScope(orgId),
OrganizationUserUserMiniDetailsOperations.ReadAll);
if (!authorizationResult.Succeeded)
{
throw new NotFoundException();
}
var organizationUserUserDetails = await _organizationUserRepository.GetManyDetailsByOrganizationAsync(orgId);
return new ListResponseModel<OrganizationUserUserMiniDetailsResponseModel>(
organizationUserUserDetails.Select(ou => new OrganizationUserUserMiniDetailsResponseModel(ou)));
@@ -207,7 +210,7 @@ public class OrganizationUsersController : Controller
{
OrganizationId = orgId,
IncludeGroups = includeGroups,
IncludeCollections = includeCollections,
IncludeCollections = includeCollections
};
if ((await _authorizationService.AuthorizeAsync(User, new ManageUsersRequirement())).Succeeded)
@@ -231,34 +234,12 @@ public class OrganizationUsersController : Controller
.ToList());
}
[HttpGet("{id}/groups")]
public async Task<IEnumerable<string>> GetGroups(string orgId, string id)
{
var organizationUser = await _organizationUserRepository.GetByIdAsync(new Guid(id));
if (organizationUser == null || (!await _currentContext.ManageGroups(organizationUser.OrganizationId) &&
!await _currentContext.ManageUsers(organizationUser.OrganizationId)))
{
throw new NotFoundException();
}
var groupIds = await _groupRepository.GetManyIdsByUserIdAsync(organizationUser.Id);
var responses = groupIds.Select(g => g.ToString());
return responses;
}
[HttpGet("{id}/reset-password-details")]
public async Task<OrganizationUserResetPasswordDetailsResponseModel> GetResetPasswordDetails(string orgId, string id)
[Authorize<ManageAccountRecoveryRequirement>]
public async Task<OrganizationUserResetPasswordDetailsResponseModel> GetResetPasswordDetails(Guid orgId, Guid id)
{
// Make sure the calling user can reset passwords for this org
var orgGuidId = new Guid(orgId);
if (!await _currentContext.ManageResetPassword(orgGuidId))
{
throw new NotFoundException();
}
var organizationUser = await _organizationUserRepository.GetByIdAsync(new Guid(id));
if (organizationUser == null || !organizationUser.UserId.HasValue)
var organizationUser = await _organizationUserRepository.GetByIdAsync(id);
if (organizationUser is null || organizationUser.UserId is null)
{
throw new NotFoundException();
}
@@ -272,7 +253,7 @@ public class OrganizationUsersController : Controller
}
// Retrieve Encrypted Private Key from organization
var org = await _organizationRepository.GetByIdAsync(orgGuidId);
var org = await _organizationRepository.GetByIdAsync(orgId);
if (org == null)
{
throw new NotFoundException();
@@ -282,26 +263,17 @@ public class OrganizationUsersController : Controller
}
[HttpPost("account-recovery-details")]
[Authorize<ManageAccountRecoveryRequirement>]
public async Task<ListResponseModel<OrganizationUserResetPasswordDetailsResponseModel>> GetAccountRecoveryDetails(Guid orgId, [FromBody] OrganizationUserBulkRequestModel model)
{
// Make sure the calling user can reset passwords for this org
if (!await _currentContext.ManageResetPassword(orgId))
{
throw new NotFoundException();
}
var responses = await _organizationUserRepository.GetManyAccountRecoveryDetailsByOrganizationUserAsync(orgId, model.Ids);
return new ListResponseModel<OrganizationUserResetPasswordDetailsResponseModel>(responses.Select(r => new OrganizationUserResetPasswordDetailsResponseModel(r)));
}
[HttpPost("invite")]
[Authorize<ManageUsersRequirement>]
public async Task Invite(Guid orgId, [FromBody] OrganizationUserInviteRequestModel model)
{
if (!await _currentContext.ManageUsers(orgId))
{
throw new NotFoundException();
}
// Check the user has permission to grant access to the collections for the new user
if (model.Collections?.Any() == true)
{
@@ -317,35 +289,25 @@ public class OrganizationUsersController : Controller
var userId = _userService.GetProperUserId(User);
await _organizationService.InviteUsersAsync(orgId, userId.Value, systemUser: null,
new (OrganizationUserInvite, string)[] { (new OrganizationUserInvite(model.ToData()), null) });
[(new OrganizationUserInvite(model.ToData()), null)]);
}
[HttpPost("reinvite")]
public async Task<ListResponseModel<OrganizationUserBulkResponseModel>> BulkReinvite(string orgId, [FromBody] OrganizationUserBulkRequestModel model)
[Authorize<ManageUsersRequirement>]
public async Task<ListResponseModel<OrganizationUserBulkResponseModel>> BulkReinvite(Guid orgId, [FromBody] OrganizationUserBulkRequestModel model)
{
var orgGuidId = new Guid(orgId);
if (!await _currentContext.ManageUsers(orgGuidId))
{
throw new NotFoundException();
}
var userId = _userService.GetProperUserId(User);
var result = await _organizationService.ResendInvitesAsync(orgGuidId, userId.Value, model.Ids);
var result = await _organizationService.ResendInvitesAsync(orgId, userId.Value, model.Ids);
return new ListResponseModel<OrganizationUserBulkResponseModel>(
result.Select(t => new OrganizationUserBulkResponseModel(t.Item1.Id, t.Item2)));
}
[HttpPost("{id}/reinvite")]
public async Task Reinvite(string orgId, string id)
[Authorize<ManageUsersRequirement>]
public async Task Reinvite(Guid orgId, Guid id)
{
var orgGuidId = new Guid(orgId);
if (!await _currentContext.ManageUsers(orgGuidId))
{
throw new NotFoundException();
}
var userId = _userService.GetProperUserId(User);
await _organizationService.ResendInviteAsync(orgGuidId, userId.Value, new Guid(id));
await _organizationService.ResendInviteAsync(orgId, userId.Value, id);
}
[HttpPost("{organizationUserId}/accept-init")]
@@ -406,57 +368,39 @@ public class OrganizationUsersController : Controller
}
[HttpPost("{id}/confirm")]
[Authorize<ManageUsersRequirement>]
public async Task Confirm(Guid orgId, Guid id, [FromBody] OrganizationUserConfirmRequestModel model)
{
if (!await _currentContext.ManageUsers(orgId))
{
throw new NotFoundException();
}
var userId = _userService.GetProperUserId(User);
var result = await _confirmOrganizationUserCommand.ConfirmUserAsync(orgId, id, model.Key, userId.Value, model.DefaultUserCollectionName);
_ = await _confirmOrganizationUserCommand.ConfirmUserAsync(orgId, id, model.Key, userId.Value, model.DefaultUserCollectionName);
}
[HttpPost("confirm")]
public async Task<ListResponseModel<OrganizationUserBulkResponseModel>> BulkConfirm(string orgId,
[Authorize<ManageUsersRequirement>]
public async Task<ListResponseModel<OrganizationUserBulkResponseModel>> BulkConfirm(Guid orgId,
[FromBody] OrganizationUserBulkConfirmRequestModel model)
{
var orgGuidId = new Guid(orgId);
if (!await _currentContext.ManageUsers(orgGuidId))
{
throw new NotFoundException();
}
var userId = _userService.GetProperUserId(User);
var results = await _confirmOrganizationUserCommand.ConfirmUsersAsync(orgGuidId, model.ToDictionary(), userId.Value);
var results = await _confirmOrganizationUserCommand.ConfirmUsersAsync(orgId, model.ToDictionary(), userId.Value);
return new ListResponseModel<OrganizationUserBulkResponseModel>(results.Select(r =>
new OrganizationUserBulkResponseModel(r.Item1.Id, r.Item2)));
}
[HttpPost("public-keys")]
public async Task<ListResponseModel<OrganizationUserPublicKeyResponseModel>> UserPublicKeys(string orgId, [FromBody] OrganizationUserBulkRequestModel model)
[Authorize<ManageUsersRequirement>]
public async Task<ListResponseModel<OrganizationUserPublicKeyResponseModel>> UserPublicKeys(Guid orgId, [FromBody] OrganizationUserBulkRequestModel model)
{
var orgGuidId = new Guid(orgId);
if (!await _currentContext.ManageUsers(orgGuidId))
{
throw new NotFoundException();
}
var result = await _organizationUserRepository.GetManyPublicKeysByOrganizationUserAsync(orgGuidId, model.Ids);
var result = await _organizationUserRepository.GetManyPublicKeysByOrganizationUserAsync(orgId, model.Ids);
var responses = result.Select(r => new OrganizationUserPublicKeyResponseModel(r.Id, r.UserId, r.PublicKey)).ToList();
return new ListResponseModel<OrganizationUserPublicKeyResponseModel>(responses);
}
[HttpPut("{id}")]
[HttpPost("{id}")]
[Authorize<ManageUsersRequirement>]
public async Task Put(Guid orgId, Guid id, [FromBody] OrganizationUserUpdateRequestModel model)
{
if (!await _currentContext.ManageUsers(orgId))
{
throw new NotFoundException();
}
var (organizationUser, currentAccess) = await _organizationUserRepository.GetByIdWithCollectionsAsync(id);
if (organizationUser == null || organizationUser.OrganizationId != orgId)
{
@@ -557,27 +501,19 @@ public class OrganizationUsersController : Controller
}
[HttpPut("{id}/reset-password")]
public async Task PutResetPassword(string orgId, string id, [FromBody] OrganizationUserResetPasswordRequestModel model)
[Authorize<ManageAccountRecoveryRequirement>]
public async Task PutResetPassword(Guid orgId, Guid id, [FromBody] OrganizationUserResetPasswordRequestModel model)
{
var orgGuidId = new Guid(orgId);
// Calling user must have Manage Reset Password permission
if (!await _currentContext.ManageResetPassword(orgGuidId))
{
throw new NotFoundException();
}
// Get the users role, since provider users aren't a member of the organization we use the owner check
var orgUserType = await _currentContext.OrganizationOwner(orgGuidId)
var orgUserType = await _currentContext.OrganizationOwner(orgId)
? OrganizationUserType.Owner
: _currentContext.Organizations?.FirstOrDefault(o => o.Id == orgGuidId)?.Type;
: _currentContext.Organizations?.FirstOrDefault(o => o.Id == orgId)?.Type;
if (orgUserType == null)
{
throw new NotFoundException();
}
var result = await _userService.AdminResetPasswordAsync(orgUserType.Value, orgGuidId, new Guid(id), model.NewMasterPasswordHash, model.Key);
var result = await _userService.AdminResetPasswordAsync(orgUserType.Value, orgId, id, model.NewMasterPasswordHash, model.Key);
if (result.Succeeded)
{
return;
@@ -594,26 +530,18 @@ public class OrganizationUsersController : Controller
[HttpDelete("{id}")]
[HttpPost("{id}/remove")]
[Authorize<ManageUsersRequirement>]
public async Task Remove(Guid orgId, Guid id)
{
if (!await _currentContext.ManageUsers(orgId))
{
throw new NotFoundException();
}
var userId = _userService.GetProperUserId(User);
await _removeOrganizationUserCommand.RemoveUserAsync(orgId, id, userId.Value);
}
[HttpDelete("")]
[HttpPost("remove")]
[Authorize<ManageUsersRequirement>]
public async Task<ListResponseModel<OrganizationUserBulkResponseModel>> BulkRemove(Guid orgId, [FromBody] OrganizationUserBulkRequestModel model)
{
if (!await _currentContext.ManageUsers(orgId))
{
throw new NotFoundException();
}
var userId = _userService.GetProperUserId(User);
var result = await _removeOrganizationUserCommand.RemoveUsersAsync(orgId, model.Ids, userId.Value);
return new ListResponseModel<OrganizationUserBulkResponseModel>(result.Select(r =>
@@ -622,13 +550,9 @@ public class OrganizationUsersController : Controller
[HttpDelete("{id}/delete-account")]
[HttpPost("{id}/delete-account")]
[Authorize<ManageUsersRequirement>]
public async Task DeleteAccount(Guid orgId, Guid id)
{
if (!await _currentContext.ManageUsers(orgId))
{
throw new NotFoundException();
}
var currentUser = await _userService.GetUserByPrincipalAsync(User);
if (currentUser == null)
{
@@ -640,13 +564,9 @@ public class OrganizationUsersController : Controller
[HttpDelete("delete-account")]
[HttpPost("delete-account")]
[Authorize<ManageUsersRequirement>]
public async Task<ListResponseModel<OrganizationUserBulkResponseModel>> BulkDeleteAccount(Guid orgId, [FromBody] OrganizationUserBulkRequestModel model)
{
if (!await _currentContext.ManageUsers(orgId))
{
throw new NotFoundException();
}
var currentUser = await _userService.GetUserByPrincipalAsync(User);
if (currentUser == null)
{
@@ -661,6 +581,7 @@ public class OrganizationUsersController : Controller
[HttpPatch("{id}/revoke")]
[HttpPut("{id}/revoke")]
[Authorize<ManageUsersRequirement>]
public async Task RevokeAsync(Guid orgId, Guid id)
{
await RestoreOrRevokeUserAsync(orgId, id, _organizationService.RevokeUserAsync);
@@ -668,6 +589,7 @@ public class OrganizationUsersController : Controller
[HttpPatch("revoke")]
[HttpPut("revoke")]
[Authorize<ManageUsersRequirement>]
public async Task<ListResponseModel<OrganizationUserBulkResponseModel>> BulkRevokeAsync(Guid orgId, [FromBody] OrganizationUserBulkRequestModel model)
{
return await RestoreOrRevokeUsersAsync(orgId, model, _organizationService.RevokeUsersAsync);
@@ -675,6 +597,7 @@ public class OrganizationUsersController : Controller
[HttpPatch("{id}/restore")]
[HttpPut("{id}/restore")]
[Authorize<ManageUsersRequirement>]
public async Task RestoreAsync(Guid orgId, Guid id)
{
await RestoreOrRevokeUserAsync(orgId, id, (orgUser, userId) => _restoreOrganizationUserCommand.RestoreUserAsync(orgUser, userId));
@@ -682,6 +605,7 @@ public class OrganizationUsersController : Controller
[HttpPatch("restore")]
[HttpPut("restore")]
[Authorize<ManageUsersRequirement>]
public async Task<ListResponseModel<OrganizationUserBulkResponseModel>> BulkRestoreAsync(Guid orgId, [FromBody] OrganizationUserBulkRequestModel model)
{
return await RestoreOrRevokeUsersAsync(orgId, model, (orgId, orgUserIds, restoringUserId) => _restoreOrganizationUserCommand.RestoreUsersAsync(orgId, orgUserIds, restoringUserId, _userService));
@@ -689,14 +613,10 @@ public class OrganizationUsersController : Controller
[HttpPatch("enable-secrets-manager")]
[HttpPut("enable-secrets-manager")]
[Authorize<ManageUsersRequirement>]
public async Task BulkEnableSecretsManagerAsync(Guid orgId,
[FromBody] OrganizationUserBulkRequestModel model)
{
if (!await _currentContext.ManageUsers(orgId))
{
throw new NotFoundException();
}
var orgUsers = (await _organizationUserRepository.GetManyAsync(model.Ids))
.Where(ou => ou.OrganizationId == orgId && !ou.AccessSecretsManager).ToList();
if (orgUsers.Count == 0)
@@ -729,11 +649,6 @@ public class OrganizationUsersController : Controller
Guid id,
Func<Core.Entities.OrganizationUser, Guid?, Task> statusAction)
{
if (!await _currentContext.ManageUsers(orgId))
{
throw new NotFoundException();
}
var userId = _userService.GetProperUserId(User);
var orgUser = await _organizationUserRepository.GetByIdAsync(id);
if (orgUser == null || orgUser.OrganizationId != orgId)
@@ -749,11 +664,6 @@ public class OrganizationUsersController : Controller
OrganizationUserBulkRequestModel model,
Func<Guid, IEnumerable<Guid>, Guid?, Task<List<Tuple<Core.Entities.OrganizationUser, string>>>> statusAction)
{
if (!await _currentContext.ManageUsers(orgId))
{
throw new NotFoundException();
}
var userId = _userService.GetProperUserId(User);
var result = await statusAction(orgId, model.Ids, userId.Value);
return new ListResponseModel<OrganizationUserBulkResponseModel>(result.Select(r =>

View File

@@ -1,50 +0,0 @@
// FIXME: Update this file to be null safe and then delete the line below
#nullable disable
using Bit.Core.AdminConsole.OrganizationFeatures.Shared.Authorization;
using Bit.Core.Context;
using Microsoft.AspNetCore.Authorization;
namespace Bit.Core.AdminConsole.OrganizationFeatures.OrganizationUsers.Authorization;
public class OrganizationUserUserMiniDetailsAuthorizationHandler :
AuthorizationHandler<OrganizationUserUserMiniDetailsOperationRequirement, OrganizationScope>
{
private readonly ICurrentContext _currentContext;
public OrganizationUserUserMiniDetailsAuthorizationHandler(ICurrentContext currentContext)
{
_currentContext = currentContext;
}
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context,
OrganizationUserUserMiniDetailsOperationRequirement requirement, OrganizationScope organizationScope)
{
var authorized = false;
switch (requirement)
{
case not null when requirement.Name == nameof(OrganizationUserUserMiniDetailsOperations.ReadAll):
authorized = await CanReadAllAsync(organizationScope);
break;
}
if (authorized)
{
context.Succeed(requirement);
}
}
private async Task<bool> CanReadAllAsync(Guid organizationId)
{
// All organization users can access this data to manage collection access
var organization = _currentContext.GetOrganization(organizationId);
if (organization != null)
{
return true;
}
// Providers can also access this to manage the organization generally
return await _currentContext.ProviderUserForOrgAsync(organizationId);
}
}

View File

@@ -178,7 +178,6 @@ public static class OrganizationServiceCollectionExtensions
services.AddScoped<IRestoreOrganizationUserCommand, RestoreOrganizationUserCommand>();
services.AddScoped<IAuthorizationHandler, OrganizationUserUserMiniDetailsAuthorizationHandler>();
services.AddScoped<IAuthorizationHandler, OrganizationUserUserDetailsAuthorizationHandler>();
services.AddScoped<IHasConfirmedOwnersExceptQuery, HasConfirmedOwnersExceptQuery>();

View File

@@ -0,0 +1,101 @@
using System.Net;
using Bit.Api.AdminConsole.Models.Request.Organizations;
using Bit.Api.IntegrationTest.Factories;
using Bit.Api.IntegrationTest.Helpers;
using Bit.Core.AdminConsole.Entities;
using Bit.Core.Billing.Enums;
using Bit.Core.Enums;
using Bit.Core.Models.Data;
using Xunit;
namespace Bit.Api.IntegrationTest.AdminConsole.Controllers;
public class OrganizationUserControllerTests : IClassFixture<ApiApplicationFactory>, IAsyncLifetime
{
public OrganizationUserControllerTests(ApiApplicationFactory apiFactory)
{
_factory = apiFactory;
_client = _factory.CreateClient();
_loginHelper = new LoginHelper(_factory, _client);
}
private readonly HttpClient _client;
private readonly ApiApplicationFactory _factory;
private readonly LoginHelper _loginHelper;
private Organization _organization = null!;
private string _ownerEmail = null!;
[Theory]
[InlineData(OrganizationUserType.User)]
[InlineData(OrganizationUserType.Custom)]
public async Task BulkDeleteAccount_WhenUserCannotManageUsers_ReturnsForbiddenResponse(OrganizationUserType organizationUserType)
{
var (userEmail, _) = await OrganizationTestHelpers.CreateNewUserWithAccountAsync(_factory,
_organization.Id, organizationUserType, new Permissions { ManageUsers = false });
await _loginHelper.LoginAsync(userEmail);
var request = new OrganizationUserBulkRequestModel
{
Ids = new List<Guid> { Guid.NewGuid() }
};
var httpResponse = await _client.PostAsJsonAsync($"organizations/{_organization.Id}/users/remove", request);
Assert.Equal(HttpStatusCode.Forbidden, httpResponse.StatusCode);
}
[Theory]
[InlineData(OrganizationUserType.User)]
[InlineData(OrganizationUserType.Custom)]
public async Task DeleteAccount_WhenUserCannotManageUsers_ReturnsForbiddenResponse(OrganizationUserType organizationUserType)
{
var (userEmail, _) = await OrganizationTestHelpers.CreateNewUserWithAccountAsync(_factory,
_organization.Id, organizationUserType, new Permissions { ManageUsers = false });
await _loginHelper.LoginAsync(userEmail);
var userToRemove = Guid.NewGuid();
var httpResponse = await _client.DeleteAsync($"organizations/{_organization.Id}/users/{userToRemove}");
Assert.Equal(HttpStatusCode.Forbidden, httpResponse.StatusCode);
}
[Theory]
[InlineData(OrganizationUserType.User)]
[InlineData(OrganizationUserType.Custom)]
public async Task GetAccountRecoveryDetails_WithoutManageResetPasswordPermission_ReturnsForbiddenResponse(OrganizationUserType organizationUserType)
{
var (userEmail, _) = await OrganizationTestHelpers.CreateNewUserWithAccountAsync(_factory,
_organization.Id, organizationUserType, new Permissions { ManageUsers = false });
await _loginHelper.LoginAsync(userEmail);
var request = new OrganizationUserBulkRequestModel
{
Ids = []
};
var httpResponse =
await _client.PostAsJsonAsync($"organizations/{_organization.Id}/users/account-recovery-details", request);
Assert.Equal(HttpStatusCode.Forbidden, httpResponse.StatusCode);
}
public async Task InitializeAsync()
{
_ownerEmail = $"org-user-integration-test-{Guid.NewGuid()}@bitwarden.com";
await _factory.LoginWithNewAccount(_ownerEmail);
(_organization, _) = await OrganizationTestHelpers.SignUpAsync(_factory, plan: PlanType.EnterpriseAnnually2023,
ownerEmail: _ownerEmail, passwordManagerSeats: 5, paymentMethod: PaymentMethodType.Card);
}
public Task DisposeAsync()
{
_client.Dispose();
return Task.CompletedTask;
}
}

View File

@@ -0,0 +1,84 @@
using Bit.Api.AdminConsole.Authorization.Requirements;
using Bit.Core.Context;
using Bit.Core.Enums;
using Bit.Core.Models.Data;
using Bit.Core.Test.AdminConsole.AutoFixture;
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
using Xunit;
namespace Bit.Api.Test.AdminConsole.Authorization.Requirements;
[SutProviderCustomize]
public class ManageGroupsOrUsersRequirementTests
{
[Theory]
[CurrentContextOrganizationCustomize]
[BitAutoData(OrganizationUserType.Admin)]
[BitAutoData(OrganizationUserType.Owner)]
public async Task AuthorizeAsync_WhenUserTypeCanManageUsers_ThenRequestShouldBeAuthorized(
OrganizationUserType type,
CurrentContextOrganization organization,
SutProvider<ManageGroupsOrUsersRequirement> sutProvider)
{
organization.Type = type;
var actual = await sutProvider.Sut.AuthorizeAsync(organization, () => Task.FromResult(false));
Assert.True(actual);
}
[Theory]
[CurrentContextOrganizationCustomize]
[BitAutoData(OrganizationUserType.Custom, true, false)]
[BitAutoData(OrganizationUserType.Custom, false, true)]
public async Task AuthorizeAsync_WhenCustomUserThatCanManageUsersOrGroups_ThenRequestShouldBeAuthorized(
OrganizationUserType type,
bool canManageUsers,
bool canManageGroups,
CurrentContextOrganization organization,
SutProvider<ManageGroupsOrUsersRequirement> sutProvider)
{
organization.Type = type;
organization.Permissions = new Permissions { ManageUsers = canManageUsers, ManageGroups = canManageGroups };
var actual = await sutProvider.Sut.AuthorizeAsync(organization, () => Task.FromResult(false));
Assert.True(actual);
}
[Theory]
[CurrentContextOrganizationCustomize]
[BitAutoData]
public async Task AuthorizeAsync_WhenProviderUserForAnOrganization_ThenRequestShouldBeAuthorized(
CurrentContextOrganization organization,
SutProvider<ManageGroupsOrUsersRequirement> sutProvider)
{
var actual = await sutProvider.Sut.AuthorizeAsync(organization, IsProviderUserForOrg);
Assert.True(actual);
return;
Task<bool> IsProviderUserForOrg() => Task.FromResult(true);
}
[Theory]
[CurrentContextOrganizationCustomize]
[BitAutoData(OrganizationUserType.User)]
[BitAutoData(OrganizationUserType.Custom)]
public async Task AuthorizeAsync_WhenUserCannotManageUsersOrGroupsAndIsNotAProviderUser_ThenRequestShouldBeDenied(
OrganizationUserType type,
CurrentContextOrganization organization,
SutProvider<ManageGroupsOrUsersRequirement> sutProvider)
{
organization.Type = type;
organization.Permissions = new Permissions { ManageUsers = false, ManageGroups = false }; // When Type is User, the canManage permissions don't matter
var actual = await sutProvider.Sut.AuthorizeAsync(organization, IsNotProviderUserForOrg);
Assert.False(actual);
return;
Task<bool> IsNotProviderUserForOrg() => Task.FromResult(false);
}
}

View File

@@ -257,7 +257,7 @@ public class OrganizationUsersControllerTests
.GetUsersOrganizationClaimedStatusAsync(organizationUser.OrganizationId, Arg.Is<IEnumerable<Guid>>(ids => ids.Contains(organizationUser.Id)))
.Returns(new Dictionary<Guid, bool> { { organizationUser.Id, true } });
var response = await sutProvider.Sut.Get(organizationUser.Id, false);
var response = await sutProvider.Sut.Get(organizationUser.OrganizationId, organizationUser.Id, false);
Assert.Equal(organizationUser.Id, response.Id);
Assert.True(response.ManagedByOrganization);
@@ -303,18 +303,6 @@ public class OrganizationUsersControllerTests
ou.EncryptedPrivateKey == r.EncryptedPrivateKey)));
}
[Theory]
[BitAutoData]
public async Task GetAccountRecoveryDetails_WithoutManageResetPasswordPermission_Throws(
Guid organizationId,
OrganizationUserBulkRequestModel bulkRequestModel,
SutProvider<OrganizationUsersController> sutProvider)
{
sutProvider.GetDependency<ICurrentContext>().ManageResetPassword(organizationId).Returns(false);
await Assert.ThrowsAsync<NotFoundException>(async () => await sutProvider.Sut.GetAccountRecoveryDetails(organizationId, bulkRequestModel));
}
[Theory]
[BitAutoData]
public async Task DeleteAccount_WhenUserCanManageUsers_Success(
@@ -330,17 +318,6 @@ public class OrganizationUsersControllerTests
.DeleteUserAsync(orgId, id, currentUser.Id);
}
[Theory]
[BitAutoData]
public async Task DeleteAccount_WhenUserCannotManageUsers_ThrowsNotFoundException(
Guid orgId, Guid id, SutProvider<OrganizationUsersController> sutProvider)
{
sutProvider.GetDependency<ICurrentContext>().ManageUsers(orgId).Returns(false);
await Assert.ThrowsAsync<NotFoundException>(() =>
sutProvider.Sut.DeleteAccount(orgId, id));
}
[Theory]
[BitAutoData]
public async Task DeleteAccount_WhenCurrentUserNotFound_ThrowsUnauthorizedAccessException(
@@ -374,17 +351,6 @@ public class OrganizationUsersControllerTests
.DeleteManyUsersAsync(orgId, model.Ids, currentUser.Id);
}
[Theory]
[BitAutoData]
public async Task BulkDeleteAccount_WhenUserCannotManageUsers_ThrowsNotFoundException(
Guid orgId, OrganizationUserBulkRequestModel model, SutProvider<OrganizationUsersController> sutProvider)
{
sutProvider.GetDependency<ICurrentContext>().ManageUsers(orgId).Returns(false);
await Assert.ThrowsAsync<NotFoundException>(() =>
sutProvider.Sut.BulkDeleteAccount(orgId, model));
}
[Theory]
[BitAutoData]
public async Task BulkDeleteAccount_WhenCurrentUserNotFound_ThrowsUnauthorizedAccessException(

View File

@@ -1,81 +0,0 @@
using System.Security.Claims;
using Bit.Core.AdminConsole.OrganizationFeatures.OrganizationUsers.Authorization;
using Bit.Core.AdminConsole.OrganizationFeatures.Shared.Authorization;
using Bit.Core.Context;
using Bit.Core.Enums;
using Bit.Core.Test.AdminConsole.AutoFixture;
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
using Microsoft.AspNetCore.Authorization;
using NSubstitute;
using Xunit;
namespace Bit.Core.Test.AdminConsole.Authorization;
[SutProviderCustomize]
public class OrganizationUserUserMiniDetailsAuthorizationHandlerTests
{
[Theory, CurrentContextOrganizationCustomize]
[BitAutoData(OrganizationUserType.Admin)]
[BitAutoData(OrganizationUserType.Owner)]
[BitAutoData(OrganizationUserType.Custom)]
[BitAutoData(OrganizationUserType.User)]
public async Task ReadAll_AnyOrganizationMember_Success(
OrganizationUserType userType,
CurrentContextOrganization organization,
SutProvider<OrganizationUserUserMiniDetailsAuthorizationHandler> sutProvider)
{
organization.Type = userType;
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
var context = new AuthorizationHandlerContext(
new[] { OrganizationUserUserMiniDetailsOperations.ReadAll },
new ClaimsPrincipal(),
new OrganizationScope(organization.Id));
await sutProvider.Sut.HandleAsync(context);
Assert.True(context.HasSucceeded);
}
[Theory, BitAutoData, CurrentContextOrganizationCustomize]
public async Task ReadAll_ProviderUser_Success(
CurrentContextOrganization organization,
SutProvider<OrganizationUserUserMiniDetailsAuthorizationHandler> sutProvider)
{
organization.Type = OrganizationUserType.User;
sutProvider.GetDependency<ICurrentContext>()
.GetOrganization(organization.Id)
.Returns((CurrentContextOrganization)null);
sutProvider.GetDependency<ICurrentContext>()
.ProviderUserForOrgAsync(organization.Id)
.Returns(true);
var context = new AuthorizationHandlerContext(
new[] { OrganizationUserUserMiniDetailsOperations.ReadAll },
new ClaimsPrincipal(),
new OrganizationScope(organization.Id));
await sutProvider.Sut.HandleAsync(context);
Assert.True(context.HasSucceeded);
}
[Theory, BitAutoData, CurrentContextOrganizationCustomize]
public async Task ReadAll_NotMember_NoSuccess(
CurrentContextOrganization organization,
SutProvider<OrganizationUserUserMiniDetailsAuthorizationHandler> sutProvider)
{
var context = new AuthorizationHandlerContext(
new[] { OrganizationUserUserMiniDetailsOperations.ReadAll },
new ClaimsPrincipal(),
new OrganizationScope(organization.Id)
);
sutProvider.GetDependency<ICurrentContext>().GetOrganization(Arg.Any<Guid>()).Returns((CurrentContextOrganization)null);
sutProvider.GetDependency<ICurrentContext>().ProviderUserForOrgAsync(Arg.Any<Guid>()).Returns(false);
await sutProvider.Sut.HandleAsync(context);
Assert.False(context.HasSucceeded);
}
}