mirror of
https://github.com/bitwarden/server.git
synced 2024-11-21 12:05:42 +01:00
[AC-1139] Flexible collections: deprecate Manage/Edit/Delete Assigned Collections custom permissions (#3360)
* [AC-1117] Add manage permission (#3126)
* Update sql files to add Manage permission
* Add migration script
* Rename collection manage migration file to remove duplicate migration date
* Migrations
* Add manage to models
* Add manage to repository
* Add constraint to Manage columns
* Migration lint fixes
* Add manage to OrganizationUserUserDetails_ReadWithCollectionsById
* Add missing manage fields
* Add 'Manage' to UserCollectionDetails
* Use CREATE OR ALTER where possible
* [AC-1374] Limit collection creation/deletion to Owner/Admin (#3145)
* feat: update org table with new column, write migration, refs AC-1374
* feat: update views with new column, refs AC-1374
* feat: Alter sprocs (org create/update) to include new column, refs AC-1374
* feat: update entity/data/request/response models to handle new column, refs AC-1374
* feat: update necessary Provider related views during migration, refs AC-1374
* fix: update org create to default new column to false, refs AC-1374
* feat: added new API/request model for collection management and removed property from update request model, refs AC-1374
* fix: renamed migration script to be after secrets manage beta column changes, refs AC-1374
* fix: dotnet format, refs AC-1374
* feat: add ef migrations to reflect mssql changes, refs AC-1374
* fix: dotnet format, refs AC-1374
* feat: update API signature to accept Guid and explain Cd verbiage, refs AC-1374
* fix: merge conflict resolution
* [AC-1174] CollectionUser and CollectionGroup authorization handlers (#3194)
* [AC-1174] Introduce BulkAuthorizationHandler.cs
* [AC-1174] Introduce CollectionUserAuthorizationHandler
* [AC-1174] Add CreateForNewCollection CollectionUser requirement
* [AC-1174] Add some more details to CollectionCustomization
* [AC-1174] Formatting
* [AC-1174] Add CollectionGroupOperation.cs
* [AC-1174] Introduce CollectionGroupAuthorizationHandler.cs
* [AC-1174] Cleanup CollectionFixture customization
Implement and use re-usable extension method to support seeded Guids
* [AC-1174] Introduce WithValueFromList AutoFixtureExtensions
Modify CollectionCustomization to use multiple organization Ids for auto generated test data
* [AC-1174] Simplify CollectionUserAuthorizationHandler.cs
Modify the authorization handler to only perform authorization logic. Validation logic will need to be handled by any calling commands/controllers instead.
* [AC-1174] Introduce shared CollectionAccessAuthorizationHandlerBase
A shared base authorization handler was created for both CollectionUser and CollectionGroup resources, as they share the same underlying management authorization logic.
* [AC-1174] Update CollectionUserAuthorizationHandler and CollectionGroupAuthorizationHandler to use the new CollectionAccessAuthorizationHandlerBase class
* [AC-1174] Formatting
* [AC-1174] Cleanup typo and redundant ToList() call
* [AC-1174] Add check for provider users
* [AC-1174] Reduce nested loops
* [AC-1174] Introduce ICollectionAccess.cs
* [AC-1174] Remove individual CollectionGroup and CollectionUser auth handlers and use base class instead
* [AC-1174] Tweak unit test to fail minimally
* [AC-1174] Reorganize authorization handlers in Core project
* [AC-1174] Introduce new AddCoreAuthorizationHandlers() extension method
* [AC-1174] Move CollectionAccessAuthorizationHandler into Api project
* [AC-1174] Move CollectionFixture to Vault folder
* [AC-1174] Rename operation to CreateUpdateDelete
* [AC-1174] Require single organization for collection access authorization handler
- Add requirement that all target collections must belong to the same organization
- Simplify logic related to multiple organizations
- Update tests and helpers
- Use ToHashSet to improve lookup time
* [AC-1174] Fix null reference exception
* [AC-1174] Throw bad request exception when collections belong to different organizations
* [AC-1174] Switch to CollectionAuthorizationHandler instead of CollectionAccessAuthorizationHandler to reduce complexity
* Fix improper merge conflict resolution
* fix: add permission check for collection management api, refs AC-1647 (#3252)
* [AC-1125] Enforce org setting for creating/deleting collections (#3241)
* [AC-1117] Add manage permission (#3126)
* Update sql files to add Manage permission
* Add migration script
* Rename collection manage migration file to remove duplicate migration date
* Migrations
* Add manage to models
* Add manage to repository
* Add constraint to Manage columns
* Migration lint fixes
* Add manage to OrganizationUserUserDetails_ReadWithCollectionsById
* Add missing manage fields
* Add 'Manage' to UserCollectionDetails
* Use CREATE OR ALTER where possible
* [AC-1374] Limit collection creation/deletion to Owner/Admin (#3145)
* feat: update org table with new column, write migration, refs AC-1374
* feat: update views with new column, refs AC-1374
* feat: Alter sprocs (org create/update) to include new column, refs AC-1374
* feat: update entity/data/request/response models to handle new column, refs AC-1374
* feat: update necessary Provider related views during migration, refs AC-1374
* fix: update org create to default new column to false, refs AC-1374
* feat: added new API/request model for collection management and removed property from update request model, refs AC-1374
* fix: renamed migration script to be after secrets manage beta column changes, refs AC-1374
* fix: dotnet format, refs AC-1374
* feat: add ef migrations to reflect mssql changes, refs AC-1374
* fix: dotnet format, refs AC-1374
* feat: update API signature to accept Guid and explain Cd verbiage, refs AC-1374
* feat: created collection auth handler/operations, added LimitCollectionCdOwnerAdmin to CurrentContentOrganization, refs AC-1125
* feat: create vault service collection extensions and register with base services, refs AC-1125
* feat: deprecated CurrentContext.CreateNewCollections, refs AC-1125
* feat: deprecate DeleteAnyCollection for single resource usages, refs AC-1125
* feat: move service registration to api, update references, refs AC-1125
* feat: add bulk delete authorization handler, refs AC-1125
* feat: always assign user and give manage access on create, refs AC-1125
* fix: updated CurrentContextOrganization type, refs AC-1125
* feat: combined existing collection authorization handlers/operations, refs AC-1125
* fix: OrganizationServiceTests -> CurrentContentOrganization typo, refs AC-1125
* fix: format, refs AC-1125
* fix: update collection controller tests, refs AC-1125
* fix: dotnet format, refs AC-1125
* feat: removed extra BulkAuthorizationHandler, refs AC-1125
* fix: dotnet format, refs AC-1125
* fix: change string to guid for org id, update bulk delete request model, refs AC-1125
* fix: remove delete many collection check, refs AC-1125
* fix: clean up collection auth handler, refs AC-1125
* fix: format fix for CollectionOperations, refs AC-1125
* fix: removed unnecessary owner check, add org null check to custom permission validation, refs AC-1125
* fix: remove unused methods in CurrentContext, refs AC-1125
* fix: removed obsolete test, fixed failling delete many test, refs AC-1125
* fix: CollectionAuthorizationHandlerTests fixes, refs AC-1125
* fix: OrganizationServiceTests fix broken test by mocking GetOrganization, refs AC-1125
* fix: CollectionAuthorizationHandler - remove unused repository, refs AC-1125
* feat: moved UserId null check to common method, refs AC-1125
* fix: updated auth handler tests to remove dependency on requirement for common code checks, refs AC-1125
* feat: updated conditionals/comments for create/delete methods within colleciton auth handler, refs AC-1125
* feat: added create/delete collection auth handler success methods, refs AC-1125
* fix: new up permissions to prevent excessive null checks, refs AC-1125
* fix: remove old reference to CreateNewCollections, refs AC-1125
* fix: typo within ViewAssignedCollections method, refs AC-1125
---------
Co-authored-by: Robyn MacCallum <robyntmaccallum@gmail.com>
* refactor: remove organizationId from CollectionBulkDeleteRequestModel, refs AC-1649 (#3282)
* [AC-1174] Bulk Collection Management (#3229)
* [AC-1174] Update SelectionReadOnlyRequestModel to use Guid for Id property
* [AC-1174] Introduce initial bulk-access collection endpoint
* [AC-1174] Introduce BulkAddCollectionAccessCommand and validation logic/tests
* [AC-1174] Add CreateOrUpdateAccessMany method to CollectionRepository
* [AC-1174] Add event logs for bulk add collection access command
* [AC-1174] Add User_BumpAccountRevisionDateByCollectionIds and database migration script
* [AC-1174] Implement EF repository method
* [AC-1174] Improve null checks
* [AC-1174] Remove unnecessary BulkCollectionAccessRequestModel helpers
* [AC-1174] Add unit tests for new controller endpoint
* [AC-1174] Fix formatting
* [AC-1174] Remove comment
* [AC-1174] Remove redundant organizationId parameter
* [AC-1174] Ensure user and group Ids are distinct
* [AC-1174] Cleanup tests based on PR feedback
* [AC-1174] Formatting
* [AC-1174] Update CollectionGroup alias in the sproc
* [AC-1174] Add some additional comments to SQL sproc
* [AC-1174] Add comment explaining additional SaveChangesAsync call
---------
Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
* [AC-1646] Rename LimitCollectionCdOwnerAdmin column (#3300)
* Rename LimitCollectionCdOwnerAdmin -> LimitCollectionCreationDeletion
* Rename and bump migration script
* [AC-1666] Removed EditAnyCollection from Create/Delete permission checks (#3301)
* fix: remove EditAnyCollection from Create/Delete permission check, refs AC-1666
* fix: updated comment, refs AC-1666
* Add feature flags constants and flag new route
* Update feature flag keys
* Create LegacyCollectionsAuthorizationHandler and start to re-implement old logic
* [AC-1669] Bug - Remove obsolete assignUserId from CollectionService.SaveAsync(...) (#3312)
* fix: remove AssignUserId from CollectionService.SaveAsync, refs AC-1669
* fix: add manage access conditional before creating collection, refs AC-1669
* fix: move access logic for create/update, fix all tests, refs AC-1669
* fix: add CollectionAccessSelection fixture, update tests, update bad reqeuest message, refs AC-1669
* fix: format, refs AC-1669
* fix: update null params with specific arg.is null checks, refs Ac-1669
* fix: update attribute class name, refs AC-1669
* Revert "Create LegacyCollectionsAuthorizationHandler and start to re-implement old logic"
This reverts commit fbb19cdadd
.
* Restore old logic behind flags
* Add missing flags
* Fix logic, add comment
* Fix tests
* Add EnableFeatureFlag extension method for tests
* Restore legacy tests
* Add FeatureServiceFixtures to set feature flags in test
* Remove unused method
* Fix formatting
* Set feature flag to ON for auth handler tests
* Use fixture instead of calling nsubstitute directly
* Change FlexibleCollectionsIsEnabled method to property
Co-authored-by: Rui Tomé <108268980+r-tome@users.noreply.github.com>
* Finish changing to property
* [AC-1139] Marked as obsolete the methods EditAssignedCollections, DeleteAssignedCollections and ViewAssignedCollections on ICurrentContext
* [AC-1139] Disabled the ability to set the custom permissions 'Delete/Edit Assigned Collections' if flexible collections feature flag is enabled
* [AC-1713] [Flexible collections] Add feature flags to server (#3334)
* Add feature flags for FlexibleCollections and BulkCollectionAccess
* Flag new routes and behaviour
---------
Co-authored-by: Rui Tomé <108268980+r-tome@users.noreply.github.com>
* [AC-1748] Updated CurrentContext EditAssignedCollections, DeleteAssignedCollections, ViewAssignedCollections to check for flexible collections feature flag
* [AC-1748] Created GroupAuthorizationHandler and modified GroupsController.Get to use it if flexible collections feature flag is enabled
* [AC-1748] Created OrganizationUserAuthorizationHandler and modified OrganizationUsersController.Get to use that if flexible collections feature flag is enabled
* [AC-1748] Reverted changes on OrganizationService
* [AC-1748] Removed GroupAuthorizationHandler
* [AC-1748] Set resource as null when reading OrganizationUserUserDetailsResponseModel list
* [AC-1139] Updated CollectionsController GetManyWithDetails and Get to check for flexible collections flag
* [AC-1139] Modified CollectionsController.Get to check access before getting collections
* [AC-1139] Updated CollectionsController to use CollectionAuthorizationHandler in all endpoints if flag is enabled
* [AC-1139] Lining up collection access data with Manage = true if feature flag is off
* Add joint codeownership for auth handlers (#3346)
* [AC-1139] Separated flexible collections logic from old logic in CollectionsController; Refactored CollectionAuthorizationHandler
* [AC-1139] Fixed formatting on OrganizationUsersController; renamed OrganizationUserOperations.Read to ReadAll
* [AC-1748] Fixed logic to set manage = true for collections if user has EditAssignedCollection permission
* [AC-1717] Update default values for LimitCollectionCreationDeletion (#3365)
* Change default value in organization create sproc to 1
* Drop old column name still present in some QA instances
* Set LimitCollectionCreationDeletion value in code based on feature flag
* Fix: add missing namespace after merging in master
* Fix: add missing namespace after merging in master
* [AC-1683] Fix DB migrations for new Manage permission (#3307)
* [AC-1683] Update migration script and introduce V2 procedures and types
* [AC-1683] Update repository calls to use new V2 procedures / types
* [AC-1684] Update bulk add collection migration script to use new V2 type
* [AC-1683] Undo Manage changes to more original procedures
* [AC-1683] Restore whitespace changes
* [AC-1683] Clarify comments regarding explicit column lists
* [AC-1683] Update migration script dates
* [AC-1683] Split the migration script for readability
* [AC-1683] Re-name SelectReadOnlyArray_V2 to CollectionAccessSelectionType
* [AC-1139] Added permission checks for GroupsController.Get if FC feature flag is enabled
* [AC-1139] Added an AuthorizationHandler for Collections and renamed existing to BulkCollectionAuthorizationHandler
* [AC-1648] [Flexible Collections] Bump migration scripts before feature branch merge (#3371)
* Bump dates on sql migration scripts
* Bump date on ef migrations
* [AC-1139] Renamed existing CollectionAuthorizationHandler to BulkCollectionAuthorizationHandler for collections and created CollectionAuthorizationHandler for single item access. Fixed unit tests and created more
* [AC-1139] Fixed Provider AuthorizationHandler logic for Groups and OrganizationUsers
* [AC-1139] Fixed CollectionAuthorizationHandler unit tests
* [AC-1139] Added unit tests for GroupAuthorizationHandler and OrganizationUserAuthorizationHandler
* [AC-1139] Added unit test to test setting users with EditAssignedCollections with Manage permission when saving a collection
* [AC-1139] Added unit tests for OrganizationService InviteUser and SaveUser with EditAssignedCollections = true
* [AC-1139] Reverted changes on OrganizationService
* [AC-1139] Marked obsolete Permissions EditAssignedCollections and DeleteAssignedCollections
* [AC-1139] Renamed FlexibleCollectionsIsEnabled properties to UseFlexibleCollections
* [AC-1139] Renamed new flexible collections controller methods to have 'vNext' in the name to indicate its a new version
* [AC-1139] Created AuthorizationServiceExtensions to have an extension method for AuthorizeAsync where the resource is null
* [AC-1139] Renamed CollectionsController method to delete collection users from 'Delete' to 'DeleteUser'
* [AC-1139] Refactored BulkCollectionAuthorizationHandler.CheckCollectionPermissionsAsync
* [AC-1139] Created new CollectionOperation ReadAccess and changed GetUsers_vNext to use it
* [AC-1139] Created new CollectionOperationRequirement ReadAllWithAccess
* [AC-1139] Addressing PR suggestions
* [AC-1139] Unit tests refactors and added tests
* [AC-1139] Updated BulkCollectionAuthorizationHandler to not fail if the resource list is null or empty.
* [AC-1139] Modified authorization handlers to not fail in case the resource is null
* [AC-1139] Reverted changes made to CollectionService and OrganizationService
* [AC-1139] Reverted changes to CollectionServiceTests and OrganizationServiceTests
* [AC-1139] Fixed OrganizationUser.ReadAll permissions
---------
Co-authored-by: Robyn MacCallum <robyntmaccallum@gmail.com>
Co-authored-by: Vincent Salucci <26154748+vincentsalucci@users.noreply.github.com>
Co-authored-by: Vincent Salucci <vincesalucci21@gmail.com>
Co-authored-by: Shane Melton <smelton@bitwarden.com>
Co-authored-by: Thomas Rittson <trittson@bitwarden.com>
Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
This commit is contained in:
parent
e422cab553
commit
fb0c442fe2
@ -1,12 +1,16 @@
|
|||||||
using Bit.Api.AdminConsole.Models.Request;
|
using Bit.Api.AdminConsole.Models.Request;
|
||||||
using Bit.Api.AdminConsole.Models.Response;
|
using Bit.Api.AdminConsole.Models.Response;
|
||||||
using Bit.Api.Models.Response;
|
using Bit.Api.Models.Response;
|
||||||
|
using Bit.Api.Utilities;
|
||||||
|
using Bit.Api.Vault.AuthorizationHandlers.Groups;
|
||||||
|
using Bit.Core;
|
||||||
using Bit.Core.AdminConsole.OrganizationFeatures.Groups.Interfaces;
|
using Bit.Core.AdminConsole.OrganizationFeatures.Groups.Interfaces;
|
||||||
using Bit.Core.AdminConsole.Repositories;
|
using Bit.Core.AdminConsole.Repositories;
|
||||||
using Bit.Core.AdminConsole.Services;
|
using Bit.Core.AdminConsole.Services;
|
||||||
using Bit.Core.Context;
|
using Bit.Core.Context;
|
||||||
using Bit.Core.Exceptions;
|
using Bit.Core.Exceptions;
|
||||||
using Bit.Core.Repositories;
|
using Bit.Core.Repositories;
|
||||||
|
using Bit.Core.Services;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
@ -23,6 +27,10 @@ public class GroupsController : Controller
|
|||||||
private readonly ICurrentContext _currentContext;
|
private readonly ICurrentContext _currentContext;
|
||||||
private readonly ICreateGroupCommand _createGroupCommand;
|
private readonly ICreateGroupCommand _createGroupCommand;
|
||||||
private readonly IUpdateGroupCommand _updateGroupCommand;
|
private readonly IUpdateGroupCommand _updateGroupCommand;
|
||||||
|
private readonly IFeatureService _featureService;
|
||||||
|
private readonly IAuthorizationService _authorizationService;
|
||||||
|
|
||||||
|
private bool UseFlexibleCollections => _featureService.IsEnabled(FeatureFlagKeys.FlexibleCollections, _currentContext);
|
||||||
|
|
||||||
public GroupsController(
|
public GroupsController(
|
||||||
IGroupRepository groupRepository,
|
IGroupRepository groupRepository,
|
||||||
@ -31,7 +39,9 @@ public class GroupsController : Controller
|
|||||||
ICurrentContext currentContext,
|
ICurrentContext currentContext,
|
||||||
ICreateGroupCommand createGroupCommand,
|
ICreateGroupCommand createGroupCommand,
|
||||||
IUpdateGroupCommand updateGroupCommand,
|
IUpdateGroupCommand updateGroupCommand,
|
||||||
IDeleteGroupCommand deleteGroupCommand)
|
IDeleteGroupCommand deleteGroupCommand,
|
||||||
|
IFeatureService featureService,
|
||||||
|
IAuthorizationService authorizationService)
|
||||||
{
|
{
|
||||||
_groupRepository = groupRepository;
|
_groupRepository = groupRepository;
|
||||||
_groupService = groupService;
|
_groupService = groupService;
|
||||||
@ -40,6 +50,8 @@ public class GroupsController : Controller
|
|||||||
_createGroupCommand = createGroupCommand;
|
_createGroupCommand = createGroupCommand;
|
||||||
_updateGroupCommand = updateGroupCommand;
|
_updateGroupCommand = updateGroupCommand;
|
||||||
_deleteGroupCommand = deleteGroupCommand;
|
_deleteGroupCommand = deleteGroupCommand;
|
||||||
|
_featureService = featureService;
|
||||||
|
_authorizationService = authorizationService;
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet("{id}")]
|
[HttpGet("{id}")]
|
||||||
@ -67,20 +79,26 @@ public class GroupsController : Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet("")]
|
[HttpGet("")]
|
||||||
public async Task<ListResponseModel<GroupDetailsResponseModel>> Get(string orgId)
|
public async Task<ListResponseModel<GroupDetailsResponseModel>> Get(Guid orgId)
|
||||||
{
|
{
|
||||||
var orgIdGuid = new Guid(orgId);
|
if (UseFlexibleCollections)
|
||||||
var canAccess = await _currentContext.ManageGroups(orgIdGuid) ||
|
{
|
||||||
await _currentContext.ViewAssignedCollections(orgIdGuid) ||
|
// New flexible collections logic
|
||||||
await _currentContext.ViewAllCollections(orgIdGuid) ||
|
return await Get_vNext(orgId);
|
||||||
await _currentContext.ManageUsers(orgIdGuid);
|
}
|
||||||
|
|
||||||
|
// Old pre-flexible collections logic follows
|
||||||
|
var canAccess = await _currentContext.ManageGroups(orgId) ||
|
||||||
|
await _currentContext.ViewAssignedCollections(orgId) ||
|
||||||
|
await _currentContext.ViewAllCollections(orgId) ||
|
||||||
|
await _currentContext.ManageUsers(orgId);
|
||||||
|
|
||||||
if (!canAccess)
|
if (!canAccess)
|
||||||
{
|
{
|
||||||
throw new NotFoundException();
|
throw new NotFoundException();
|
||||||
}
|
}
|
||||||
|
|
||||||
var groups = await _groupRepository.GetManyWithCollectionsByOrganizationIdAsync(orgIdGuid);
|
var groups = await _groupRepository.GetManyWithCollectionsByOrganizationIdAsync(orgId);
|
||||||
var responses = groups.Select(g => new GroupDetailsResponseModel(g.Item1, g.Item2));
|
var responses = groups.Select(g => new GroupDetailsResponseModel(g.Item1, g.Item2));
|
||||||
return new ListResponseModel<GroupDetailsResponseModel>(responses);
|
return new ListResponseModel<GroupDetailsResponseModel>(responses);
|
||||||
}
|
}
|
||||||
@ -185,4 +203,18 @@ public class GroupsController : Controller
|
|||||||
|
|
||||||
await _groupService.DeleteUserAsync(group, new Guid(orgUserId));
|
await _groupService.DeleteUserAsync(group, new Guid(orgUserId));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async Task<ListResponseModel<GroupDetailsResponseModel>> Get_vNext(Guid orgId)
|
||||||
|
{
|
||||||
|
var authorized =
|
||||||
|
(await _authorizationService.AuthorizeAsync(User, GroupOperations.ReadAll(orgId))).Succeeded;
|
||||||
|
if (!authorized)
|
||||||
|
{
|
||||||
|
throw new NotFoundException();
|
||||||
|
}
|
||||||
|
|
||||||
|
var groups = await _groupRepository.GetManyWithCollectionsByOrganizationIdAsync(orgId);
|
||||||
|
var responses = groups.Select(g => new GroupDetailsResponseModel(g.Item1, g.Item2));
|
||||||
|
return new ListResponseModel<GroupDetailsResponseModel>(responses);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -2,6 +2,9 @@
|
|||||||
using Bit.Api.AdminConsole.Models.Response.Organizations;
|
using Bit.Api.AdminConsole.Models.Response.Organizations;
|
||||||
using Bit.Api.Models.Request.Organizations;
|
using Bit.Api.Models.Request.Organizations;
|
||||||
using Bit.Api.Models.Response;
|
using Bit.Api.Models.Response;
|
||||||
|
using Bit.Api.Utilities;
|
||||||
|
using Bit.Api.Vault.AuthorizationHandlers.OrganizationUsers;
|
||||||
|
using Bit.Core;
|
||||||
using Bit.Core.AdminConsole.Enums;
|
using Bit.Core.AdminConsole.Enums;
|
||||||
using Bit.Core.AdminConsole.Models.Data.Organizations.Policies;
|
using Bit.Core.AdminConsole.Models.Data.Organizations.Policies;
|
||||||
using Bit.Core.AdminConsole.OrganizationFeatures.OrganizationUsers.Interfaces;
|
using Bit.Core.AdminConsole.OrganizationFeatures.OrganizationUsers.Interfaces;
|
||||||
@ -36,6 +39,10 @@ public class OrganizationUsersController : Controller
|
|||||||
private readonly IUpdateSecretsManagerSubscriptionCommand _updateSecretsManagerSubscriptionCommand;
|
private readonly IUpdateSecretsManagerSubscriptionCommand _updateSecretsManagerSubscriptionCommand;
|
||||||
private readonly IUpdateOrganizationUserGroupsCommand _updateOrganizationUserGroupsCommand;
|
private readonly IUpdateOrganizationUserGroupsCommand _updateOrganizationUserGroupsCommand;
|
||||||
private readonly IAcceptOrgUserCommand _acceptOrgUserCommand;
|
private readonly IAcceptOrgUserCommand _acceptOrgUserCommand;
|
||||||
|
private readonly IFeatureService _featureService;
|
||||||
|
private readonly IAuthorizationService _authorizationService;
|
||||||
|
|
||||||
|
private bool UseFlexibleCollections => _featureService.IsEnabled(FeatureFlagKeys.FlexibleCollections, _currentContext);
|
||||||
|
|
||||||
public OrganizationUsersController(
|
public OrganizationUsersController(
|
||||||
IOrganizationRepository organizationRepository,
|
IOrganizationRepository organizationRepository,
|
||||||
@ -49,7 +56,9 @@ public class OrganizationUsersController : Controller
|
|||||||
ICountNewSmSeatsRequiredQuery countNewSmSeatsRequiredQuery,
|
ICountNewSmSeatsRequiredQuery countNewSmSeatsRequiredQuery,
|
||||||
IUpdateSecretsManagerSubscriptionCommand updateSecretsManagerSubscriptionCommand,
|
IUpdateSecretsManagerSubscriptionCommand updateSecretsManagerSubscriptionCommand,
|
||||||
IUpdateOrganizationUserGroupsCommand updateOrganizationUserGroupsCommand,
|
IUpdateOrganizationUserGroupsCommand updateOrganizationUserGroupsCommand,
|
||||||
IAcceptOrgUserCommand acceptOrgUserCommand)
|
IAcceptOrgUserCommand acceptOrgUserCommand,
|
||||||
|
IFeatureService featureService,
|
||||||
|
IAuthorizationService authorizationService)
|
||||||
{
|
{
|
||||||
_organizationRepository = organizationRepository;
|
_organizationRepository = organizationRepository;
|
||||||
_organizationUserRepository = organizationUserRepository;
|
_organizationUserRepository = organizationUserRepository;
|
||||||
@ -63,6 +72,8 @@ public class OrganizationUsersController : Controller
|
|||||||
_updateSecretsManagerSubscriptionCommand = updateSecretsManagerSubscriptionCommand;
|
_updateSecretsManagerSubscriptionCommand = updateSecretsManagerSubscriptionCommand;
|
||||||
_updateOrganizationUserGroupsCommand = updateOrganizationUserGroupsCommand;
|
_updateOrganizationUserGroupsCommand = updateOrganizationUserGroupsCommand;
|
||||||
_acceptOrgUserCommand = acceptOrgUserCommand;
|
_acceptOrgUserCommand = acceptOrgUserCommand;
|
||||||
|
_featureService = featureService;
|
||||||
|
_authorizationService = authorizationService;
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet("{id}")]
|
[HttpGet("{id}")]
|
||||||
@ -85,18 +96,20 @@ public class OrganizationUsersController : Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet("")]
|
[HttpGet("")]
|
||||||
public async Task<ListResponseModel<OrganizationUserUserDetailsResponseModel>> Get(string orgId, bool includeGroups = false, bool includeCollections = false)
|
public async Task<ListResponseModel<OrganizationUserUserDetailsResponseModel>> Get(Guid orgId, bool includeGroups = false, bool includeCollections = false)
|
||||||
{
|
{
|
||||||
var orgGuidId = new Guid(orgId);
|
var authorized = UseFlexibleCollections
|
||||||
if (!await _currentContext.ViewAllCollections(orgGuidId) &&
|
? (await _authorizationService.AuthorizeAsync(User, OrganizationUserOperations.ReadAll(orgId))).Succeeded
|
||||||
!await _currentContext.ViewAssignedCollections(orgGuidId) &&
|
: await _currentContext.ViewAllCollections(orgId) ||
|
||||||
!await _currentContext.ManageGroups(orgGuidId) &&
|
await _currentContext.ViewAssignedCollections(orgId) ||
|
||||||
!await _currentContext.ManageUsers(orgGuidId))
|
await _currentContext.ManageGroups(orgId) ||
|
||||||
|
await _currentContext.ManageUsers(orgId);
|
||||||
|
if (!authorized)
|
||||||
{
|
{
|
||||||
throw new NotFoundException();
|
throw new NotFoundException();
|
||||||
}
|
}
|
||||||
|
|
||||||
var organizationUsers = await _organizationUserRepository.GetManyDetailsByOrganizationAsync(orgGuidId, includeGroups, includeCollections);
|
var organizationUsers = await _organizationUserRepository.GetManyDetailsByOrganizationAsync(orgId, includeGroups, includeCollections);
|
||||||
var responseTasks = organizationUsers.Select(async o => new OrganizationUserUserDetailsResponseModel(o,
|
var responseTasks = organizationUsers.Select(async o => new OrganizationUserUserDetailsResponseModel(o,
|
||||||
await _userService.TwoFactorIsEnabledAsync(o)));
|
await _userService.TwoFactorIsEnabledAsync(o)));
|
||||||
var responses = await Task.WhenAll(responseTasks);
|
var responses = await Task.WhenAll(responseTasks);
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
using Bit.Api.Models.Request;
|
using Bit.Api.Models.Request;
|
||||||
using Bit.Api.Models.Response;
|
using Bit.Api.Models.Response;
|
||||||
|
using Bit.Api.Utilities;
|
||||||
using Bit.Api.Vault.AuthorizationHandlers.Collections;
|
using Bit.Api.Vault.AuthorizationHandlers.Collections;
|
||||||
using Bit.Core;
|
using Bit.Core;
|
||||||
using Bit.Core.Context;
|
using Bit.Core.Context;
|
||||||
@ -42,6 +43,7 @@ public class CollectionsController : Controller
|
|||||||
IOrganizationUserRepository organizationUserRepository)
|
IOrganizationUserRepository organizationUserRepository)
|
||||||
{
|
{
|
||||||
_collectionRepository = collectionRepository;
|
_collectionRepository = collectionRepository;
|
||||||
|
_organizationUserRepository = organizationUserRepository;
|
||||||
_collectionService = collectionService;
|
_collectionService = collectionService;
|
||||||
_deleteCollectionCommand = deleteCollectionCommand;
|
_deleteCollectionCommand = deleteCollectionCommand;
|
||||||
_userService = userService;
|
_userService = userService;
|
||||||
@ -57,18 +59,33 @@ public class CollectionsController : Controller
|
|||||||
[HttpGet("{id}")]
|
[HttpGet("{id}")]
|
||||||
public async Task<CollectionResponseModel> Get(Guid orgId, Guid id)
|
public async Task<CollectionResponseModel> Get(Guid orgId, Guid id)
|
||||||
{
|
{
|
||||||
|
if (FlexibleCollectionsIsEnabled)
|
||||||
|
{
|
||||||
|
// New flexible collections logic
|
||||||
|
return await Get_vNext(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Old pre-flexible collections logic follows
|
||||||
if (!await CanViewCollectionAsync(orgId, id))
|
if (!await CanViewCollectionAsync(orgId, id))
|
||||||
{
|
{
|
||||||
throw new NotFoundException();
|
throw new NotFoundException();
|
||||||
}
|
}
|
||||||
|
|
||||||
var collection = await GetCollectionAsync(id, orgId);
|
var collection = await GetCollectionAsync(id, orgId);
|
||||||
|
|
||||||
return new CollectionResponseModel(collection);
|
return new CollectionResponseModel(collection);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet("{id}/details")]
|
[HttpGet("{id}/details")]
|
||||||
public async Task<CollectionAccessDetailsResponseModel> GetDetails(Guid orgId, Guid id)
|
public async Task<CollectionAccessDetailsResponseModel> GetDetails(Guid orgId, Guid id)
|
||||||
{
|
{
|
||||||
|
if (FlexibleCollectionsIsEnabled)
|
||||||
|
{
|
||||||
|
// New flexible collections logic
|
||||||
|
return await GetDetails_vNext(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Old pre-flexible collections logic follows
|
||||||
if (!await ViewAtLeastOneCollectionAsync(orgId) && !await _currentContext.ManageUsers(orgId))
|
if (!await ViewAtLeastOneCollectionAsync(orgId) && !await _currentContext.ManageUsers(orgId))
|
||||||
{
|
{
|
||||||
throw new NotFoundException();
|
throw new NotFoundException();
|
||||||
@ -100,8 +117,14 @@ public class CollectionsController : Controller
|
|||||||
[HttpGet("details")]
|
[HttpGet("details")]
|
||||||
public async Task<ListResponseModel<CollectionAccessDetailsResponseModel>> GetManyWithDetails(Guid orgId)
|
public async Task<ListResponseModel<CollectionAccessDetailsResponseModel>> GetManyWithDetails(Guid orgId)
|
||||||
{
|
{
|
||||||
if (!await ViewAtLeastOneCollectionAsync(orgId) && !await _currentContext.ManageUsers(orgId) &&
|
if (FlexibleCollectionsIsEnabled)
|
||||||
!await _currentContext.ManageGroups(orgId))
|
{
|
||||||
|
// New flexible collections logic
|
||||||
|
return await GetManyWithDetails_vNext(orgId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Old pre-flexible collections logic follows
|
||||||
|
if (!await ViewAtLeastOneCollectionAsync(orgId) && !await _currentContext.ManageUsers(orgId) && !await _currentContext.ManageGroups(orgId))
|
||||||
{
|
{
|
||||||
throw new NotFoundException();
|
throw new NotFoundException();
|
||||||
}
|
}
|
||||||
@ -135,8 +158,14 @@ public class CollectionsController : Controller
|
|||||||
[HttpGet("")]
|
[HttpGet("")]
|
||||||
public async Task<ListResponseModel<CollectionResponseModel>> Get(Guid orgId)
|
public async Task<ListResponseModel<CollectionResponseModel>> Get(Guid orgId)
|
||||||
{
|
{
|
||||||
IEnumerable<Collection> orgCollections = await _collectionService.GetOrganizationCollectionsAsync(orgId);
|
if (FlexibleCollectionsIsEnabled)
|
||||||
|
{
|
||||||
|
// New flexible collections logic
|
||||||
|
return await GetByOrgId_vNext(orgId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Old pre-flexible collections logic follows
|
||||||
|
var orgCollections = await _collectionService.GetOrganizationCollectionsAsync(orgId);
|
||||||
var responses = orgCollections.Select(c => new CollectionResponseModel(c));
|
var responses = orgCollections.Select(c => new CollectionResponseModel(c));
|
||||||
return new ListResponseModel<CollectionResponseModel>(responses);
|
return new ListResponseModel<CollectionResponseModel>(responses);
|
||||||
}
|
}
|
||||||
@ -153,6 +182,13 @@ public class CollectionsController : Controller
|
|||||||
[HttpGet("{id}/users")]
|
[HttpGet("{id}/users")]
|
||||||
public async Task<IEnumerable<SelectionReadOnlyResponseModel>> GetUsers(Guid orgId, Guid id)
|
public async Task<IEnumerable<SelectionReadOnlyResponseModel>> GetUsers(Guid orgId, Guid id)
|
||||||
{
|
{
|
||||||
|
if (FlexibleCollectionsIsEnabled)
|
||||||
|
{
|
||||||
|
// New flexible collections logic
|
||||||
|
return await GetUsers_vNext(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Old pre-flexible collections logic follows
|
||||||
var collection = await GetCollectionAsync(id, orgId);
|
var collection = await GetCollectionAsync(id, orgId);
|
||||||
var collectionUsers = await _collectionRepository.GetManyUsersByIdAsync(collection.Id);
|
var collectionUsers = await _collectionRepository.GetManyUsersByIdAsync(collection.Id);
|
||||||
var responses = collectionUsers.Select(cu => new SelectionReadOnlyResponseModel(cu));
|
var responses = collectionUsers.Select(cu => new SelectionReadOnlyResponseModel(cu));
|
||||||
@ -165,7 +201,7 @@ public class CollectionsController : Controller
|
|||||||
var collection = model.ToCollection(orgId);
|
var collection = model.ToCollection(orgId);
|
||||||
|
|
||||||
var authorized = FlexibleCollectionsIsEnabled
|
var authorized = FlexibleCollectionsIsEnabled
|
||||||
? (await _authorizationService.AuthorizeAsync(User, collection, CollectionOperations.Create)).Succeeded
|
? (await _authorizationService.AuthorizeAsync(User, collection, BulkCollectionOperations.Create)).Succeeded
|
||||||
: await CanCreateCollection(orgId, collection.Id) || await CanEditCollectionAsync(orgId, collection.Id);
|
: await CanCreateCollection(orgId, collection.Id) || await CanEditCollectionAsync(orgId, collection.Id);
|
||||||
if (!authorized)
|
if (!authorized)
|
||||||
{
|
{
|
||||||
@ -205,6 +241,13 @@ public class CollectionsController : Controller
|
|||||||
[HttpPost("{id}")]
|
[HttpPost("{id}")]
|
||||||
public async Task<CollectionResponseModel> Put(Guid orgId, Guid id, [FromBody] CollectionRequestModel model)
|
public async Task<CollectionResponseModel> Put(Guid orgId, Guid id, [FromBody] CollectionRequestModel model)
|
||||||
{
|
{
|
||||||
|
if (FlexibleCollectionsIsEnabled)
|
||||||
|
{
|
||||||
|
// New flexible collections logic
|
||||||
|
return await Put_vNext(id, model);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Old pre-flexible collections logic follows
|
||||||
if (!await CanEditCollectionAsync(orgId, id))
|
if (!await CanEditCollectionAsync(orgId, id))
|
||||||
{
|
{
|
||||||
throw new NotFoundException();
|
throw new NotFoundException();
|
||||||
@ -220,6 +263,14 @@ public class CollectionsController : Controller
|
|||||||
[HttpPut("{id}/users")]
|
[HttpPut("{id}/users")]
|
||||||
public async Task PutUsers(Guid orgId, Guid id, [FromBody] IEnumerable<SelectionReadOnlyRequestModel> model)
|
public async Task PutUsers(Guid orgId, Guid id, [FromBody] IEnumerable<SelectionReadOnlyRequestModel> model)
|
||||||
{
|
{
|
||||||
|
if (FlexibleCollectionsIsEnabled)
|
||||||
|
{
|
||||||
|
// New flexible collections logic
|
||||||
|
await PutUsers_vNext(id, model);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Old pre-flexible collections logic follows
|
||||||
if (!await CanEditCollectionAsync(orgId, id))
|
if (!await CanEditCollectionAsync(orgId, id))
|
||||||
{
|
{
|
||||||
throw new NotFoundException();
|
throw new NotFoundException();
|
||||||
@ -243,7 +294,7 @@ public class CollectionsController : Controller
|
|||||||
throw new NotFoundException("One or more collections not found.");
|
throw new NotFoundException("One or more collections not found.");
|
||||||
}
|
}
|
||||||
|
|
||||||
var result = await _authorizationService.AuthorizeAsync(User, collections, CollectionOperations.ModifyAccess);
|
var result = await _authorizationService.AuthorizeAsync(User, collections, BulkCollectionOperations.ModifyAccess);
|
||||||
|
|
||||||
if (!result.Succeeded)
|
if (!result.Succeeded)
|
||||||
{
|
{
|
||||||
@ -260,16 +311,20 @@ public class CollectionsController : Controller
|
|||||||
[HttpPost("{id}/delete")]
|
[HttpPost("{id}/delete")]
|
||||||
public async Task Delete(Guid orgId, Guid id)
|
public async Task Delete(Guid orgId, Guid id)
|
||||||
{
|
{
|
||||||
var collection = await GetCollectionAsync(id, orgId);
|
if (FlexibleCollectionsIsEnabled)
|
||||||
|
{
|
||||||
|
// New flexible collections logic
|
||||||
|
await Delete_vNext(id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
var authorized = FlexibleCollectionsIsEnabled
|
// Old pre-flexible collections logic follows
|
||||||
? (await _authorizationService.AuthorizeAsync(User, collection, CollectionOperations.Delete)).Succeeded
|
if (!await CanDeleteCollectionAsync(orgId, id))
|
||||||
: await CanDeleteCollectionAsync(orgId, id);
|
|
||||||
if (!authorized)
|
|
||||||
{
|
{
|
||||||
throw new NotFoundException();
|
throw new NotFoundException();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var collection = await GetCollectionAsync(id, orgId);
|
||||||
await _deleteCollectionCommand.DeleteAsync(collection);
|
await _deleteCollectionCommand.DeleteAsync(collection);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -281,7 +336,7 @@ public class CollectionsController : Controller
|
|||||||
{
|
{
|
||||||
// New flexible collections logic
|
// New flexible collections logic
|
||||||
var collections = await _collectionRepository.GetManyByManyIdsAsync(model.Ids);
|
var collections = await _collectionRepository.GetManyByManyIdsAsync(model.Ids);
|
||||||
var result = await _authorizationService.AuthorizeAsync(User, collections, CollectionOperations.Delete);
|
var result = await _authorizationService.AuthorizeAsync(User, collections, BulkCollectionOperations.Delete);
|
||||||
if (!result.Succeeded)
|
if (!result.Succeeded)
|
||||||
{
|
{
|
||||||
throw new NotFoundException();
|
throw new NotFoundException();
|
||||||
@ -311,14 +366,33 @@ public class CollectionsController : Controller
|
|||||||
|
|
||||||
[HttpDelete("{id}/user/{orgUserId}")]
|
[HttpDelete("{id}/user/{orgUserId}")]
|
||||||
[HttpPost("{id}/delete-user/{orgUserId}")]
|
[HttpPost("{id}/delete-user/{orgUserId}")]
|
||||||
public async Task Delete(string orgId, string id, string orgUserId)
|
public async Task DeleteUser(Guid orgId, Guid id, Guid orgUserId)
|
||||||
{
|
{
|
||||||
var collection = await GetCollectionAsync(new Guid(id), new Guid(orgId));
|
if (FlexibleCollectionsIsEnabled)
|
||||||
await _collectionService.DeleteUserAsync(collection, new Guid(orgUserId));
|
{
|
||||||
|
// New flexible collections logic
|
||||||
|
await DeleteUser_vNext(id, orgUserId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Old pre-flexible collections logic follows
|
||||||
|
var collection = await GetCollectionAsync(id, orgId);
|
||||||
|
await _collectionService.DeleteUserAsync(collection, orgUserId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void DeprecatedPermissionsGuard()
|
||||||
|
{
|
||||||
|
if (FlexibleCollectionsIsEnabled)
|
||||||
|
{
|
||||||
|
throw new FeatureUnavailableException("Flexible Collections is ON when it should be OFF.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Obsolete("Pre-Flexible Collections logic. Will be replaced by CollectionsAuthorizationHandler.")]
|
||||||
private async Task<Collection> GetCollectionAsync(Guid id, Guid orgId)
|
private async Task<Collection> GetCollectionAsync(Guid id, Guid orgId)
|
||||||
{
|
{
|
||||||
|
DeprecatedPermissionsGuard();
|
||||||
|
|
||||||
Collection collection = default;
|
Collection collection = default;
|
||||||
if (await _currentContext.ViewAllCollections(orgId))
|
if (await _currentContext.ViewAllCollections(orgId))
|
||||||
{
|
{
|
||||||
@ -337,14 +411,6 @@ public class CollectionsController : Controller
|
|||||||
return collection;
|
return collection;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void DeprecatedPermissionsGuard()
|
|
||||||
{
|
|
||||||
if (FlexibleCollectionsIsEnabled)
|
|
||||||
{
|
|
||||||
throw new FeatureUnavailableException("Flexible Collections is ON when it should be OFF.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Obsolete("Pre-Flexible Collections logic. Will be replaced by CollectionsAuthorizationHandler.")]
|
[Obsolete("Pre-Flexible Collections logic. Will be replaced by CollectionsAuthorizationHandler.")]
|
||||||
private async Task<bool> CanCreateCollection(Guid orgId, Guid collectionId)
|
private async Task<bool> CanCreateCollection(Guid orgId, Guid collectionId)
|
||||||
{
|
{
|
||||||
@ -359,8 +425,11 @@ public class CollectionsController : Controller
|
|||||||
(o.Permissions?.CreateNewCollections ?? false)) ?? false);
|
(o.Permissions?.CreateNewCollections ?? false)) ?? false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Obsolete("Pre-Flexible Collections logic. Will be replaced by CollectionsAuthorizationHandler.")]
|
||||||
private async Task<bool> CanEditCollectionAsync(Guid orgId, Guid collectionId)
|
private async Task<bool> CanEditCollectionAsync(Guid orgId, Guid collectionId)
|
||||||
{
|
{
|
||||||
|
DeprecatedPermissionsGuard();
|
||||||
|
|
||||||
if (collectionId == default)
|
if (collectionId == default)
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
@ -416,8 +485,11 @@ public class CollectionsController : Controller
|
|||||||
&& (o.Permissions?.DeleteAnyCollection ?? false)) ?? false);
|
&& (o.Permissions?.DeleteAnyCollection ?? false)) ?? false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Obsolete("Pre-Flexible Collections logic. Will be replaced by CollectionsAuthorizationHandler.")]
|
||||||
private async Task<bool> CanViewCollectionAsync(Guid orgId, Guid collectionId)
|
private async Task<bool> CanViewCollectionAsync(Guid orgId, Guid collectionId)
|
||||||
{
|
{
|
||||||
|
DeprecatedPermissionsGuard();
|
||||||
|
|
||||||
if (collectionId == default)
|
if (collectionId == default)
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
@ -438,8 +510,166 @@ public class CollectionsController : Controller
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Obsolete("Pre-Flexible Collections logic. Will be replaced by CollectionsAuthorizationHandler.")]
|
||||||
private async Task<bool> ViewAtLeastOneCollectionAsync(Guid orgId)
|
private async Task<bool> ViewAtLeastOneCollectionAsync(Guid orgId)
|
||||||
{
|
{
|
||||||
|
DeprecatedPermissionsGuard();
|
||||||
|
|
||||||
return await _currentContext.ViewAllCollections(orgId) || await _currentContext.ViewAssignedCollections(orgId);
|
return await _currentContext.ViewAllCollections(orgId) || await _currentContext.ViewAssignedCollections(orgId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async Task<CollectionResponseModel> Get_vNext(Guid collectionId)
|
||||||
|
{
|
||||||
|
var collection = await _collectionRepository.GetByIdAsync(collectionId);
|
||||||
|
var authorized = (await _authorizationService.AuthorizeAsync(User, collection, BulkCollectionOperations.Read)).Succeeded;
|
||||||
|
if (!authorized)
|
||||||
|
{
|
||||||
|
throw new NotFoundException();
|
||||||
|
}
|
||||||
|
|
||||||
|
return new CollectionResponseModel(collection);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<CollectionAccessDetailsResponseModel> GetDetails_vNext(Guid id)
|
||||||
|
{
|
||||||
|
// New flexible collections logic
|
||||||
|
var (collection, access) = await _collectionRepository.GetByIdWithAccessAsync(id);
|
||||||
|
var authorized = (await _authorizationService.AuthorizeAsync(User, collection, BulkCollectionOperations.ReadWithAccess)).Succeeded;
|
||||||
|
if (!authorized)
|
||||||
|
{
|
||||||
|
throw new NotFoundException();
|
||||||
|
}
|
||||||
|
|
||||||
|
return new CollectionAccessDetailsResponseModel(collection, access.Groups, access.Users);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<ListResponseModel<CollectionAccessDetailsResponseModel>> GetManyWithDetails_vNext(Guid orgId)
|
||||||
|
{
|
||||||
|
// We always need to know which collections the current user is assigned to
|
||||||
|
var assignedOrgCollections = await _collectionRepository
|
||||||
|
.GetManyByUserIdWithAccessAsync(_currentContext.UserId.Value, orgId);
|
||||||
|
|
||||||
|
var readAllAuthorized =
|
||||||
|
(await _authorizationService.AuthorizeAsync(User, CollectionOperations.ReadAllWithAccess(orgId))).Succeeded;
|
||||||
|
if (readAllAuthorized)
|
||||||
|
{
|
||||||
|
// The user can view all collections, but they may not always be assigned to all of them
|
||||||
|
var allOrgCollections = await _collectionRepository.GetManyByOrganizationIdWithAccessAsync(orgId);
|
||||||
|
|
||||||
|
return new ListResponseModel<CollectionAccessDetailsResponseModel>(allOrgCollections.Select(c =>
|
||||||
|
new CollectionAccessDetailsResponseModel(c.Item1, c.Item2.Groups, c.Item2.Users)
|
||||||
|
{
|
||||||
|
// Manually determine which collections they're assigned to
|
||||||
|
Assigned = assignedOrgCollections.Any(ac => ac.Item1.Id == c.Item1.Id)
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filter the assigned collections to only return those where the user has Manage permission
|
||||||
|
var manageableOrgCollections = assignedOrgCollections.Where(c => c.Item1.Manage).ToList();
|
||||||
|
var readAssignedAuthorized = await _authorizationService.AuthorizeAsync(User, manageableOrgCollections.Select(c => c.Item1), BulkCollectionOperations.ReadWithAccess);
|
||||||
|
if (!readAssignedAuthorized.Succeeded)
|
||||||
|
{
|
||||||
|
throw new NotFoundException();
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ListResponseModel<CollectionAccessDetailsResponseModel>(manageableOrgCollections.Select(c =>
|
||||||
|
new CollectionAccessDetailsResponseModel(c.Item1, c.Item2.Groups, c.Item2.Users)
|
||||||
|
{
|
||||||
|
Assigned = true // Mapping from manageableOrgCollections implies they're all assigned
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<ListResponseModel<CollectionResponseModel>> GetByOrgId_vNext(Guid orgId)
|
||||||
|
{
|
||||||
|
IEnumerable<Collection> orgCollections;
|
||||||
|
|
||||||
|
var readAllAuthorized = (await _authorizationService.AuthorizeAsync(User, CollectionOperations.ReadAll(orgId))).Succeeded;
|
||||||
|
if (readAllAuthorized)
|
||||||
|
{
|
||||||
|
orgCollections = await _collectionRepository.GetManyByOrganizationIdAsync(orgId);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var collections = await _collectionRepository.GetManyByUserIdAsync(_currentContext.UserId.Value);
|
||||||
|
var readAuthorized = (await _authorizationService.AuthorizeAsync(User, collections, BulkCollectionOperations.Read)).Succeeded;
|
||||||
|
if (readAuthorized)
|
||||||
|
{
|
||||||
|
orgCollections = collections.Where(c => c.OrganizationId == orgId);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
throw new NotFoundException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var responses = orgCollections.Select(c => new CollectionResponseModel(c));
|
||||||
|
return new ListResponseModel<CollectionResponseModel>(responses);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<IEnumerable<SelectionReadOnlyResponseModel>> GetUsers_vNext(Guid id)
|
||||||
|
{
|
||||||
|
var collection = await _collectionRepository.GetByIdAsync(id);
|
||||||
|
var authorized = (await _authorizationService.AuthorizeAsync(User, collection, BulkCollectionOperations.ReadAccess)).Succeeded;
|
||||||
|
if (!authorized)
|
||||||
|
{
|
||||||
|
throw new NotFoundException();
|
||||||
|
}
|
||||||
|
|
||||||
|
var collectionUsers = await _collectionRepository.GetManyUsersByIdAsync(collection.Id);
|
||||||
|
var responses = collectionUsers.Select(cu => new SelectionReadOnlyResponseModel(cu));
|
||||||
|
return responses;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<CollectionResponseModel> Put_vNext(Guid id, CollectionRequestModel model)
|
||||||
|
{
|
||||||
|
var collection = await _collectionRepository.GetByIdAsync(id);
|
||||||
|
var authorized = (await _authorizationService.AuthorizeAsync(User, collection, BulkCollectionOperations.Update)).Succeeded;
|
||||||
|
if (!authorized)
|
||||||
|
{
|
||||||
|
throw new NotFoundException();
|
||||||
|
}
|
||||||
|
|
||||||
|
var groups = model.Groups?.Select(g => g.ToSelectionReadOnly());
|
||||||
|
var users = model.Users?.Select(g => g.ToSelectionReadOnly());
|
||||||
|
await _collectionService.SaveAsync(model.ToCollection(collection), groups, users);
|
||||||
|
return new CollectionResponseModel(collection);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task PutUsers_vNext(Guid id, IEnumerable<SelectionReadOnlyRequestModel> model)
|
||||||
|
{
|
||||||
|
var collection = await _collectionRepository.GetByIdAsync(id);
|
||||||
|
var authorized = (await _authorizationService.AuthorizeAsync(User, collection, BulkCollectionOperations.ModifyAccess)).Succeeded;
|
||||||
|
if (!authorized)
|
||||||
|
{
|
||||||
|
throw new NotFoundException();
|
||||||
|
}
|
||||||
|
|
||||||
|
await _collectionRepository.UpdateUsersAsync(collection.Id, model?.Select(g => g.ToSelectionReadOnly()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task Delete_vNext(Guid id)
|
||||||
|
{
|
||||||
|
var collection = await _collectionRepository.GetByIdAsync(id);
|
||||||
|
var authorized = (await _authorizationService.AuthorizeAsync(User, collection, BulkCollectionOperations.Delete)).Succeeded;
|
||||||
|
if (!authorized)
|
||||||
|
{
|
||||||
|
throw new NotFoundException();
|
||||||
|
}
|
||||||
|
|
||||||
|
await _deleteCollectionCommand.DeleteAsync(collection);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task DeleteUser_vNext(Guid id, Guid orgUserId)
|
||||||
|
{
|
||||||
|
var collection = await _collectionRepository.GetByIdAsync(id);
|
||||||
|
var authorized = (await _authorizationService.AuthorizeAsync(User, collection, BulkCollectionOperations.ModifyAccess)).Succeeded;
|
||||||
|
if (!authorized)
|
||||||
|
{
|
||||||
|
throw new NotFoundException();
|
||||||
|
}
|
||||||
|
|
||||||
|
await _collectionService.DeleteUserAsync(collection, orgUserId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
32
src/Api/Utilities/AuthorizationServiceExtensions.cs
Normal file
32
src/Api/Utilities/AuthorizationServiceExtensions.cs
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
using System.Security.Claims;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
|
||||||
|
namespace Bit.Api.Utilities;
|
||||||
|
|
||||||
|
public static class AuthorizationServiceExtensions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Checks if a user meets a specific requirement.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="service">The <see cref="IAuthorizationService"/> providing authorization.</param>
|
||||||
|
/// <param name="user">The user to evaluate the policy against.</param>
|
||||||
|
/// <param name="requirement">The requirement to evaluate the policy against.</param>
|
||||||
|
/// <returns>
|
||||||
|
/// A flag indicating whether requirement evaluation has succeeded or failed.
|
||||||
|
/// This value is <value>true</value> when the user fulfills the policy, otherwise <value>false</value>.
|
||||||
|
/// </returns>
|
||||||
|
public static Task<AuthorizationResult> AuthorizeAsync(this IAuthorizationService service, ClaimsPrincipal user, IAuthorizationRequirement requirement)
|
||||||
|
{
|
||||||
|
if (service == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(service));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (requirement == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(requirement));
|
||||||
|
}
|
||||||
|
|
||||||
|
return service.AuthorizeAsync(user, resource: null, new[] { requirement });
|
||||||
|
}
|
||||||
|
}
|
@ -1,4 +1,6 @@
|
|||||||
using Bit.Api.Vault.AuthorizationHandlers.Collections;
|
using Bit.Api.Vault.AuthorizationHandlers.Collections;
|
||||||
|
using Bit.Api.Vault.AuthorizationHandlers.Groups;
|
||||||
|
using Bit.Api.Vault.AuthorizationHandlers.OrganizationUsers;
|
||||||
using Bit.Core.IdentityServer;
|
using Bit.Core.IdentityServer;
|
||||||
using Bit.Core.Settings;
|
using Bit.Core.Settings;
|
||||||
using Bit.Core.Utilities;
|
using Bit.Core.Utilities;
|
||||||
@ -120,6 +122,9 @@ public static class ServiceCollectionExtensions
|
|||||||
|
|
||||||
public static void AddAuthorizationHandlers(this IServiceCollection services)
|
public static void AddAuthorizationHandlers(this IServiceCollection services)
|
||||||
{
|
{
|
||||||
|
services.AddScoped<IAuthorizationHandler, BulkCollectionAuthorizationHandler>();
|
||||||
services.AddScoped<IAuthorizationHandler, CollectionAuthorizationHandler>();
|
services.AddScoped<IAuthorizationHandler, CollectionAuthorizationHandler>();
|
||||||
|
services.AddScoped<IAuthorizationHandler, GroupAuthorizationHandler>();
|
||||||
|
services.AddScoped<IAuthorizationHandler, OrganizationUserAuthorizationHandler>();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,265 @@
|
|||||||
|
#nullable enable
|
||||||
|
using Bit.Core;
|
||||||
|
using Bit.Core.Context;
|
||||||
|
using Bit.Core.Entities;
|
||||||
|
using Bit.Core.Enums;
|
||||||
|
using Bit.Core.Exceptions;
|
||||||
|
using Bit.Core.Repositories;
|
||||||
|
using Bit.Core.Services;
|
||||||
|
using Bit.Core.Utilities;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
|
||||||
|
namespace Bit.Api.Vault.AuthorizationHandlers.Collections;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handles authorization logic for Collection objects, including access permissions for users and groups.
|
||||||
|
/// This uses new logic implemented in the Flexible Collections initiative.
|
||||||
|
/// </summary>
|
||||||
|
public class BulkCollectionAuthorizationHandler : BulkAuthorizationHandler<BulkCollectionOperationRequirement, Collection>
|
||||||
|
{
|
||||||
|
private readonly ICurrentContext _currentContext;
|
||||||
|
private readonly ICollectionRepository _collectionRepository;
|
||||||
|
private readonly IFeatureService _featureService;
|
||||||
|
private Guid _targetOrganizationId;
|
||||||
|
|
||||||
|
private bool FlexibleCollectionsIsEnabled => _featureService.IsEnabled(FeatureFlagKeys.FlexibleCollections, _currentContext);
|
||||||
|
|
||||||
|
public BulkCollectionAuthorizationHandler(
|
||||||
|
ICurrentContext currentContext,
|
||||||
|
ICollectionRepository collectionRepository,
|
||||||
|
IFeatureService featureService)
|
||||||
|
{
|
||||||
|
_currentContext = currentContext;
|
||||||
|
_collectionRepository = collectionRepository;
|
||||||
|
_featureService = featureService;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context,
|
||||||
|
BulkCollectionOperationRequirement requirement, ICollection<Collection>? resources)
|
||||||
|
{
|
||||||
|
if (!FlexibleCollectionsIsEnabled)
|
||||||
|
{
|
||||||
|
// Flexible collections is OFF, should not be using this handler
|
||||||
|
throw new FeatureUnavailableException("Flexible collections is OFF when it should be ON.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Establish pattern of authorization handler null checking passed resources
|
||||||
|
if (resources == null || !resources.Any())
|
||||||
|
{
|
||||||
|
context.Fail();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Acting user is not authenticated, fail
|
||||||
|
if (!_currentContext.UserId.HasValue)
|
||||||
|
{
|
||||||
|
context.Fail();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_targetOrganizationId = resources.First().OrganizationId;
|
||||||
|
|
||||||
|
// Ensure all target collections belong to the same organization
|
||||||
|
if (resources.Any(tc => tc.OrganizationId != _targetOrganizationId))
|
||||||
|
{
|
||||||
|
throw new BadRequestException("Requested collections must belong to the same organization.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var org = _currentContext.GetOrganization(_targetOrganizationId);
|
||||||
|
|
||||||
|
switch (requirement)
|
||||||
|
{
|
||||||
|
case not null when requirement == BulkCollectionOperations.Create:
|
||||||
|
await CanCreateAsync(context, requirement, org);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case not null when requirement == BulkCollectionOperations.Read:
|
||||||
|
case not null when requirement == BulkCollectionOperations.ReadAccess:
|
||||||
|
await CanReadAsync(context, requirement, resources, org);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case not null when requirement == BulkCollectionOperations.ReadWithAccess:
|
||||||
|
await CanReadWithAccessAsync(context, requirement, resources, org);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case not null when requirement == BulkCollectionOperations.Update:
|
||||||
|
case not null when requirement == BulkCollectionOperations.ModifyAccess:
|
||||||
|
await CanUpdateCollection(context, requirement, resources, org);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case not null when requirement == BulkCollectionOperations.Delete:
|
||||||
|
await CanDeleteAsync(context, requirement, resources, org);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task CanCreateAsync(AuthorizationHandlerContext context, IAuthorizationRequirement requirement,
|
||||||
|
CurrentContextOrganization? org)
|
||||||
|
{
|
||||||
|
// If the limit collection management setting is disabled, allow any user to create collections
|
||||||
|
// Otherwise, Owners, Admins, and users with CreateNewCollections permission can always create collections
|
||||||
|
if (org is
|
||||||
|
{ LimitCollectionCreationDeletion: false } or
|
||||||
|
{ Type: OrganizationUserType.Owner or OrganizationUserType.Admin } or
|
||||||
|
{ Permissions.CreateNewCollections: true })
|
||||||
|
{
|
||||||
|
context.Succeed(requirement);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow provider users to create collections if they are a provider for the target organization
|
||||||
|
if (await _currentContext.ProviderUserForOrgAsync(_targetOrganizationId))
|
||||||
|
{
|
||||||
|
context.Succeed(requirement);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task CanReadAsync(AuthorizationHandlerContext context, IAuthorizationRequirement requirement,
|
||||||
|
ICollection<Collection> resources, CurrentContextOrganization? org)
|
||||||
|
{
|
||||||
|
// Owners, Admins, and users with EditAnyCollection or DeleteAnyCollection permission can always read a collection
|
||||||
|
if (org is
|
||||||
|
{ Type: OrganizationUserType.Owner or OrganizationUserType.Admin } or
|
||||||
|
{ Permissions.EditAnyCollection: true } or
|
||||||
|
{ Permissions.DeleteAnyCollection: true })
|
||||||
|
{
|
||||||
|
context.Succeed(requirement);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The acting user is a member of the target organization,
|
||||||
|
// ensure they have access for the collection being read
|
||||||
|
if (org is not null)
|
||||||
|
{
|
||||||
|
var isAssignedToCollections = await IsAssignedToCollectionsAsync(resources, org, false);
|
||||||
|
if (isAssignedToCollections)
|
||||||
|
{
|
||||||
|
context.Succeed(requirement);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow provider users to read collections if they are a provider for the target organization
|
||||||
|
if (await _currentContext.ProviderUserForOrgAsync(_targetOrganizationId))
|
||||||
|
{
|
||||||
|
context.Succeed(requirement);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task CanReadWithAccessAsync(AuthorizationHandlerContext context, IAuthorizationRequirement requirement,
|
||||||
|
ICollection<Collection> resources, CurrentContextOrganization? org)
|
||||||
|
{
|
||||||
|
// Owners, Admins, and users with EditAnyCollection, DeleteAnyCollection or ManageUsers permission can always read a collection
|
||||||
|
if (org is
|
||||||
|
{ Type: OrganizationUserType.Owner or OrganizationUserType.Admin } or
|
||||||
|
{ Permissions.EditAnyCollection: true } or
|
||||||
|
{ Permissions.DeleteAnyCollection: true } or
|
||||||
|
{ Permissions.ManageUsers: true })
|
||||||
|
{
|
||||||
|
context.Succeed(requirement);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The acting user is a member of the target organization,
|
||||||
|
// ensure they have access with manage permission for the collection being read
|
||||||
|
if (org is not null)
|
||||||
|
{
|
||||||
|
var isAssignedToCollections = await IsAssignedToCollectionsAsync(resources, org, true);
|
||||||
|
if (isAssignedToCollections)
|
||||||
|
{
|
||||||
|
context.Succeed(requirement);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow provider users to read collections if they are a provider for the target organization
|
||||||
|
if (await _currentContext.ProviderUserForOrgAsync(_targetOrganizationId))
|
||||||
|
{
|
||||||
|
context.Succeed(requirement);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Ensures the acting user is allowed to update the target collections or manage access permissions for them.
|
||||||
|
/// </summary>
|
||||||
|
private async Task CanUpdateCollection(AuthorizationHandlerContext context,
|
||||||
|
IAuthorizationRequirement requirement, ICollection<Collection> resources,
|
||||||
|
CurrentContextOrganization? org)
|
||||||
|
{
|
||||||
|
// Owners, Admins, and users with EditAnyCollection permission can always manage collection access
|
||||||
|
if (org is
|
||||||
|
{ Type: OrganizationUserType.Owner or OrganizationUserType.Admin } or
|
||||||
|
{ Permissions.EditAnyCollection: true })
|
||||||
|
{
|
||||||
|
context.Succeed(requirement);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The acting user is a member of the target organization,
|
||||||
|
// ensure they have manage permission for the collection being managed
|
||||||
|
if (org is not null)
|
||||||
|
{
|
||||||
|
var canManageCollections = await IsAssignedToCollectionsAsync(resources, org, true);
|
||||||
|
if (canManageCollections)
|
||||||
|
{
|
||||||
|
context.Succeed(requirement);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow providers to manage collections if they are a provider for the target organization
|
||||||
|
if (await _currentContext.ProviderUserForOrgAsync(_targetOrganizationId))
|
||||||
|
{
|
||||||
|
context.Succeed(requirement);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task CanDeleteAsync(AuthorizationHandlerContext context, IAuthorizationRequirement requirement,
|
||||||
|
ICollection<Collection> resources, CurrentContextOrganization? org)
|
||||||
|
{
|
||||||
|
// Owners, Admins, and users with DeleteAnyCollection permission can always delete collections
|
||||||
|
if (org is
|
||||||
|
{ Type: OrganizationUserType.Owner or OrganizationUserType.Admin } or
|
||||||
|
{ Permissions.DeleteAnyCollection: true })
|
||||||
|
{
|
||||||
|
context.Succeed(requirement);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The limit collection management setting is disabled,
|
||||||
|
// ensure acting user has manage permissions for all collections being deleted
|
||||||
|
if (org is { LimitCollectionCreationDeletion: false })
|
||||||
|
{
|
||||||
|
var canManageCollections = await IsAssignedToCollectionsAsync(resources, org, true);
|
||||||
|
if (canManageCollections)
|
||||||
|
{
|
||||||
|
context.Succeed(requirement);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow providers to delete collections if they are a provider for the target organization
|
||||||
|
if (await _currentContext.ProviderUserForOrgAsync(_targetOrganizationId))
|
||||||
|
{
|
||||||
|
context.Succeed(requirement);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<bool> IsAssignedToCollectionsAsync(
|
||||||
|
ICollection<Collection> targetCollections,
|
||||||
|
CurrentContextOrganization org,
|
||||||
|
bool requireManagePermission)
|
||||||
|
{
|
||||||
|
// List of collection Ids the acting user has access to
|
||||||
|
var assignedCollectionIds =
|
||||||
|
(await _collectionRepository.GetManyByUserIdAsync(_currentContext.UserId!.Value))
|
||||||
|
.Where(c =>
|
||||||
|
// Check Collections with Manage permission
|
||||||
|
(!requireManagePermission || c.Manage) && c.OrganizationId == org.Id)
|
||||||
|
.Select(c => c.Id)
|
||||||
|
.ToHashSet();
|
||||||
|
|
||||||
|
// Check if the acting user has access to all target collections
|
||||||
|
return targetCollections.All(tc => assignedCollectionIds.Contains(tc.Id));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
using Microsoft.AspNetCore.Authorization.Infrastructure;
|
||||||
|
|
||||||
|
namespace Bit.Api.Vault.AuthorizationHandlers.Collections;
|
||||||
|
|
||||||
|
public class BulkCollectionOperationRequirement : OperationAuthorizationRequirement { }
|
||||||
|
|
||||||
|
public static class BulkCollectionOperations
|
||||||
|
{
|
||||||
|
public static readonly BulkCollectionOperationRequirement Create = new() { Name = nameof(Create) };
|
||||||
|
public static readonly BulkCollectionOperationRequirement Read = new() { Name = nameof(Read) };
|
||||||
|
public static readonly BulkCollectionOperationRequirement ReadAccess = new() { Name = nameof(ReadAccess) };
|
||||||
|
public static readonly BulkCollectionOperationRequirement ReadWithAccess = new() { Name = nameof(ReadWithAccess) };
|
||||||
|
public static readonly BulkCollectionOperationRequirement Update = new() { Name = nameof(Update) };
|
||||||
|
/// <summary>
|
||||||
|
/// The operation that represents creating, updating, or removing collection access.
|
||||||
|
/// Combined together to allow for a single requirement to be used for each operation
|
||||||
|
/// as they all currently share the same underlying authorization logic.
|
||||||
|
/// </summary>
|
||||||
|
public static readonly BulkCollectionOperationRequirement ModifyAccess = new() { Name = nameof(ModifyAccess) };
|
||||||
|
public static readonly BulkCollectionOperationRequirement Delete = new() { Name = nameof(Delete) };
|
||||||
|
}
|
@ -1,176 +1,108 @@
|
|||||||
#nullable enable
|
#nullable enable
|
||||||
using Bit.Core;
|
using Bit.Core;
|
||||||
using Bit.Core.Context;
|
using Bit.Core.Context;
|
||||||
using Bit.Core.Entities;
|
|
||||||
using Bit.Core.Enums;
|
using Bit.Core.Enums;
|
||||||
using Bit.Core.Exceptions;
|
using Bit.Core.Exceptions;
|
||||||
using Bit.Core.Repositories;
|
|
||||||
using Bit.Core.Services;
|
using Bit.Core.Services;
|
||||||
using Bit.Core.Utilities;
|
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
|
||||||
namespace Bit.Api.Vault.AuthorizationHandlers.Collections;
|
namespace Bit.Api.Vault.AuthorizationHandlers.Collections;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Handles authorization logic for Collection objects, including access permissions for users and groups.
|
/// Handles authorization logic for Collection operations.
|
||||||
/// This uses new logic implemented in the Flexible Collections initiative.
|
/// This uses new logic implemented in the Flexible Collections initiative.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class CollectionAuthorizationHandler : BulkAuthorizationHandler<CollectionOperationRequirement, Collection>
|
public class CollectionAuthorizationHandler : AuthorizationHandler<CollectionOperationRequirement>
|
||||||
{
|
{
|
||||||
private readonly ICurrentContext _currentContext;
|
private readonly ICurrentContext _currentContext;
|
||||||
private readonly ICollectionRepository _collectionRepository;
|
|
||||||
private readonly IFeatureService _featureService;
|
private readonly IFeatureService _featureService;
|
||||||
private Guid _targetOrganizationId;
|
|
||||||
|
|
||||||
public CollectionAuthorizationHandler(ICurrentContext currentContext, ICollectionRepository collectionRepository,
|
private bool FlexibleCollectionsIsEnabled => _featureService.IsEnabled(FeatureFlagKeys.FlexibleCollections, _currentContext);
|
||||||
|
|
||||||
|
public CollectionAuthorizationHandler(
|
||||||
|
ICurrentContext currentContext,
|
||||||
IFeatureService featureService)
|
IFeatureService featureService)
|
||||||
{
|
{
|
||||||
_currentContext = currentContext;
|
_currentContext = currentContext;
|
||||||
_collectionRepository = collectionRepository;
|
|
||||||
_featureService = featureService;
|
_featureService = featureService;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context,
|
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context,
|
||||||
CollectionOperationRequirement requirement, ICollection<Collection>? resources)
|
CollectionOperationRequirement requirement)
|
||||||
{
|
{
|
||||||
if (!_featureService.IsEnabled(FeatureFlagKeys.FlexibleCollections, _currentContext))
|
if (!FlexibleCollectionsIsEnabled)
|
||||||
{
|
{
|
||||||
// Flexible collections is OFF, should not be using this handler
|
// Flexible collections is OFF, should not be using this handler
|
||||||
throw new FeatureUnavailableException("Flexible collections is OFF when it should be ON.");
|
throw new FeatureUnavailableException("Flexible collections is OFF when it should be ON.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Establish pattern of authorization handler null checking passed resources
|
// Acting user is not authenticated, fail
|
||||||
if (resources == null || !resources.Any())
|
|
||||||
{
|
|
||||||
context.Fail();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!_currentContext.UserId.HasValue)
|
if (!_currentContext.UserId.HasValue)
|
||||||
{
|
{
|
||||||
context.Fail();
|
context.Fail();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
_targetOrganizationId = resources.First().OrganizationId;
|
if (requirement.OrganizationId == default)
|
||||||
|
|
||||||
// Ensure all target collections belong to the same organization
|
|
||||||
if (resources.Any(tc => tc.OrganizationId != _targetOrganizationId))
|
|
||||||
{
|
{
|
||||||
throw new BadRequestException("Requested collections must belong to the same organization.");
|
context.Fail();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var org = _currentContext.GetOrganization(_targetOrganizationId);
|
var org = _currentContext.GetOrganization(requirement.OrganizationId);
|
||||||
|
|
||||||
switch (requirement)
|
switch (requirement)
|
||||||
{
|
{
|
||||||
case not null when requirement == CollectionOperations.Create:
|
case not null when requirement.Name == nameof(CollectionOperations.ReadAll):
|
||||||
await CanCreateAsync(context, requirement, org);
|
await CanReadAllAsync(context, requirement, org);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case not null when requirement == CollectionOperations.Delete:
|
case not null when requirement.Name == nameof(CollectionOperations.ReadAllWithAccess):
|
||||||
await CanDeleteAsync(context, requirement, resources, org);
|
await CanReadAllWithAccessAsync(context, requirement, org);
|
||||||
break;
|
|
||||||
|
|
||||||
case not null when requirement == CollectionOperations.ModifyAccess:
|
|
||||||
await CanManageCollectionAccessAsync(context, requirement, resources, org);
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task CanCreateAsync(AuthorizationHandlerContext context, CollectionOperationRequirement requirement,
|
private async Task CanReadAllAsync(AuthorizationHandlerContext context, CollectionOperationRequirement requirement,
|
||||||
CurrentContextOrganization? org)
|
CurrentContextOrganization? org)
|
||||||
{
|
{
|
||||||
// If the limit collection management setting is disabled, allow any user to create collections
|
// Owners, Admins, and users with EditAnyCollection, DeleteAnyCollection,
|
||||||
// Otherwise, Owners, Admins, and users with CreateNewCollections permission can always create collections
|
// or AccessImportExport permission can always read a collection
|
||||||
if (org is
|
if (org is
|
||||||
{ LimitCollectionCreationDeletion: false } or
|
|
||||||
{ Type: OrganizationUserType.Owner or OrganizationUserType.Admin } or
|
{ Type: OrganizationUserType.Owner or OrganizationUserType.Admin } or
|
||||||
{ Permissions.CreateNewCollections: true })
|
{ Permissions.EditAnyCollection: true } or
|
||||||
|
{ Permissions.DeleteAnyCollection: true } or
|
||||||
|
{ Permissions.AccessImportExport: true } or
|
||||||
|
{ Permissions.ManageGroups: true })
|
||||||
{
|
{
|
||||||
context.Succeed(requirement);
|
context.Succeed(requirement);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Allow provider users to create collections if they are a provider for the target organization
|
// Allow provider users to read collections if they are a provider for the target organization
|
||||||
if (await _currentContext.ProviderUserForOrgAsync(_targetOrganizationId))
|
if (await _currentContext.ProviderUserForOrgAsync(requirement.OrganizationId))
|
||||||
{
|
{
|
||||||
context.Succeed(requirement);
|
context.Succeed(requirement);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task CanDeleteAsync(AuthorizationHandlerContext context, CollectionOperationRequirement requirement,
|
private async Task CanReadAllWithAccessAsync(AuthorizationHandlerContext context, CollectionOperationRequirement requirement,
|
||||||
ICollection<Collection> resources, CurrentContextOrganization? org)
|
|
||||||
{
|
|
||||||
// Owners, Admins, and users with DeleteAnyCollection permission can always delete collections
|
|
||||||
if (org is
|
|
||||||
{ Type: OrganizationUserType.Owner or OrganizationUserType.Admin } or
|
|
||||||
{ Permissions.DeleteAnyCollection: true })
|
|
||||||
{
|
|
||||||
context.Succeed(requirement);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The limit collection management setting is disabled,
|
|
||||||
// ensure acting user has manage permissions for all collections being deleted
|
|
||||||
if (org is { LimitCollectionCreationDeletion: false })
|
|
||||||
{
|
|
||||||
var manageableCollectionIds =
|
|
||||||
(await _collectionRepository.GetManyByUserIdAsync(_currentContext.UserId!.Value))
|
|
||||||
.Where(c => c.Manage && c.OrganizationId == org.Id)
|
|
||||||
.Select(c => c.Id)
|
|
||||||
.ToHashSet();
|
|
||||||
|
|
||||||
// The acting user has permission to manage all target collections, succeed
|
|
||||||
if (resources.All(c => manageableCollectionIds.Contains(c.Id)))
|
|
||||||
{
|
|
||||||
context.Succeed(requirement);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Allow providers to delete collections if they are a provider for the target organization
|
|
||||||
if (await _currentContext.ProviderUserForOrgAsync(_targetOrganizationId))
|
|
||||||
{
|
|
||||||
context.Succeed(requirement);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Ensures the acting user is allowed to manage access permissions for the target collections.
|
|
||||||
/// </summary>
|
|
||||||
private async Task CanManageCollectionAccessAsync(AuthorizationHandlerContext context,
|
|
||||||
IAuthorizationRequirement requirement, ICollection<Collection> targetCollections,
|
|
||||||
CurrentContextOrganization? org)
|
CurrentContextOrganization? org)
|
||||||
{
|
{
|
||||||
// Owners, Admins, and users with EditAnyCollection permission can always manage collection access
|
// Owners, Admins, and users with EditAnyCollection or DeleteAnyCollection
|
||||||
|
// permission can always read a collection
|
||||||
if (org is
|
if (org is
|
||||||
{ Type: OrganizationUserType.Owner or OrganizationUserType.Admin } or
|
{ Type: OrganizationUserType.Owner or OrganizationUserType.Admin } or
|
||||||
{ Permissions.EditAnyCollection: true })
|
{ Permissions.EditAnyCollection: true } or
|
||||||
|
{ Permissions.DeleteAnyCollection: true } or
|
||||||
|
{ Permissions.ManageUsers: true })
|
||||||
{
|
{
|
||||||
context.Succeed(requirement);
|
context.Succeed(requirement);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only check collection management permissions if the user is a member of the target organization (org != null)
|
// Allow provider users to read collections if they are a provider for the target organization
|
||||||
if (org is not null)
|
if (await _currentContext.ProviderUserForOrgAsync(requirement.OrganizationId))
|
||||||
{
|
|
||||||
var manageableCollectionIds =
|
|
||||||
(await _collectionRepository.GetManyByUserIdAsync(_currentContext.UserId!.Value))
|
|
||||||
.Where(c => c.Manage && c.OrganizationId == org.Id)
|
|
||||||
.Select(c => c.Id)
|
|
||||||
.ToHashSet();
|
|
||||||
|
|
||||||
// The acting user has permission to manage all target collections, succeed
|
|
||||||
if (targetCollections.All(c => manageableCollectionIds.Contains(c.Id)))
|
|
||||||
{
|
|
||||||
context.Succeed(requirement);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Allow providers to manage collections if they are a provider for the target organization
|
|
||||||
if (await _currentContext.ProviderUserForOrgAsync(_targetOrganizationId))
|
|
||||||
{
|
{
|
||||||
context.Succeed(requirement);
|
context.Succeed(requirement);
|
||||||
}
|
}
|
||||||
|
@ -2,16 +2,26 @@
|
|||||||
|
|
||||||
namespace Bit.Api.Vault.AuthorizationHandlers.Collections;
|
namespace Bit.Api.Vault.AuthorizationHandlers.Collections;
|
||||||
|
|
||||||
public class CollectionOperationRequirement : OperationAuthorizationRequirement { }
|
public class CollectionOperationRequirement : OperationAuthorizationRequirement
|
||||||
|
{
|
||||||
|
public Guid OrganizationId { get; init; }
|
||||||
|
|
||||||
|
public CollectionOperationRequirement(string name, Guid organizationId)
|
||||||
|
{
|
||||||
|
Name = name;
|
||||||
|
OrganizationId = organizationId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public static class CollectionOperations
|
public static class CollectionOperations
|
||||||
{
|
{
|
||||||
public static readonly CollectionOperationRequirement Create = new() { Name = nameof(Create) };
|
public static CollectionOperationRequirement ReadAll(Guid organizationId)
|
||||||
public static readonly CollectionOperationRequirement Delete = new() { Name = nameof(Delete) };
|
{
|
||||||
/// <summary>
|
return new CollectionOperationRequirement(nameof(ReadAll), organizationId);
|
||||||
/// The operation that represents creating, updating, or removing collection access.
|
}
|
||||||
/// Combined together to allow for a single requirement to be used for each operation
|
public static CollectionOperationRequirement ReadAllWithAccess(Guid organizationId)
|
||||||
/// as they all currently share the same underlying authorization logic.
|
{
|
||||||
/// </summary>
|
return new CollectionOperationRequirement(nameof(ReadAllWithAccess), organizationId);
|
||||||
public static readonly CollectionOperationRequirement ModifyAccess = new() { Name = nameof(ModifyAccess) };
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -0,0 +1,86 @@
|
|||||||
|
#nullable enable
|
||||||
|
using Bit.Core;
|
||||||
|
using Bit.Core.Context;
|
||||||
|
using Bit.Core.Enums;
|
||||||
|
using Bit.Core.Exceptions;
|
||||||
|
using Bit.Core.Services;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
|
||||||
|
namespace Bit.Api.Vault.AuthorizationHandlers.Groups;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handles authorization logic for Group operations.
|
||||||
|
/// This uses new logic implemented in the Flexible Collections initiative.
|
||||||
|
/// </summary>
|
||||||
|
public class GroupAuthorizationHandler : AuthorizationHandler<GroupOperationRequirement>
|
||||||
|
{
|
||||||
|
private readonly ICurrentContext _currentContext;
|
||||||
|
private readonly IFeatureService _featureService;
|
||||||
|
|
||||||
|
private bool FlexibleCollectionsIsEnabled => _featureService.IsEnabled(FeatureFlagKeys.FlexibleCollections, _currentContext);
|
||||||
|
|
||||||
|
public GroupAuthorizationHandler(
|
||||||
|
ICurrentContext currentContext,
|
||||||
|
IFeatureService featureService)
|
||||||
|
{
|
||||||
|
_currentContext = currentContext;
|
||||||
|
_featureService = featureService;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context,
|
||||||
|
GroupOperationRequirement requirement)
|
||||||
|
{
|
||||||
|
if (!FlexibleCollectionsIsEnabled)
|
||||||
|
{
|
||||||
|
// Flexible collections is OFF, should not be using this handler
|
||||||
|
throw new FeatureUnavailableException("Flexible collections is OFF when it should be ON.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Acting user is not authenticated, fail
|
||||||
|
if (!_currentContext.UserId.HasValue)
|
||||||
|
{
|
||||||
|
context.Fail();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (requirement.OrganizationId == default)
|
||||||
|
{
|
||||||
|
context.Fail();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var org = _currentContext.GetOrganization(requirement.OrganizationId);
|
||||||
|
|
||||||
|
switch (requirement)
|
||||||
|
{
|
||||||
|
case not null when requirement.Name == nameof(GroupOperations.ReadAll):
|
||||||
|
await CanReadAllAsync(context, requirement, org);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task CanReadAllAsync(AuthorizationHandlerContext context, GroupOperationRequirement requirement,
|
||||||
|
CurrentContextOrganization? org)
|
||||||
|
{
|
||||||
|
// If the limit collection management setting is disabled, allow any user to read all groups
|
||||||
|
// Otherwise, Owners, Admins, and users with any of ManageGroups, ManageUsers, EditAnyCollection, DeleteAnyCollection, CreateNewCollections permissions can always read all groups
|
||||||
|
if (org is
|
||||||
|
{ LimitCollectionCreationDeletion: false } or
|
||||||
|
{ Type: OrganizationUserType.Owner or OrganizationUserType.Admin } or
|
||||||
|
{ Permissions.ManageGroups: true } or
|
||||||
|
{ Permissions.ManageUsers: true } or
|
||||||
|
{ Permissions.EditAnyCollection: true } or
|
||||||
|
{ Permissions.DeleteAnyCollection: true } or
|
||||||
|
{ Permissions.CreateNewCollections: true })
|
||||||
|
{
|
||||||
|
context.Succeed(requirement);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow provider users to read all groups if they are a provider for the target organization
|
||||||
|
if (await _currentContext.ProviderUserForOrgAsync(requirement.OrganizationId))
|
||||||
|
{
|
||||||
|
context.Succeed(requirement);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
using Microsoft.AspNetCore.Authorization.Infrastructure;
|
||||||
|
|
||||||
|
namespace Bit.Api.Vault.AuthorizationHandlers.Groups;
|
||||||
|
|
||||||
|
public class GroupOperationRequirement : OperationAuthorizationRequirement
|
||||||
|
{
|
||||||
|
public Guid OrganizationId { get; init; }
|
||||||
|
|
||||||
|
public GroupOperationRequirement(string name, Guid organizationId)
|
||||||
|
{
|
||||||
|
Name = name;
|
||||||
|
OrganizationId = organizationId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class GroupOperations
|
||||||
|
{
|
||||||
|
public static GroupOperationRequirement ReadAll(Guid organizationId)
|
||||||
|
{
|
||||||
|
return new GroupOperationRequirement(nameof(ReadAll), organizationId);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,85 @@
|
|||||||
|
#nullable enable
|
||||||
|
using Bit.Core;
|
||||||
|
using Bit.Core.Context;
|
||||||
|
using Bit.Core.Enums;
|
||||||
|
using Bit.Core.Exceptions;
|
||||||
|
using Bit.Core.Services;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
|
||||||
|
namespace Bit.Api.Vault.AuthorizationHandlers.OrganizationUsers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handles authorization logic for OrganizationUser objects.
|
||||||
|
/// This uses new logic implemented in the Flexible Collections initiative.
|
||||||
|
/// </summary>
|
||||||
|
public class OrganizationUserAuthorizationHandler : AuthorizationHandler<OrganizationUserOperationRequirement>
|
||||||
|
{
|
||||||
|
private readonly ICurrentContext _currentContext;
|
||||||
|
private readonly IFeatureService _featureService;
|
||||||
|
|
||||||
|
private bool FlexibleCollectionsIsEnabled => _featureService.IsEnabled(FeatureFlagKeys.FlexibleCollections, _currentContext);
|
||||||
|
|
||||||
|
public OrganizationUserAuthorizationHandler(
|
||||||
|
ICurrentContext currentContext,
|
||||||
|
IFeatureService featureService)
|
||||||
|
{
|
||||||
|
_currentContext = currentContext;
|
||||||
|
_featureService = featureService;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context,
|
||||||
|
OrganizationUserOperationRequirement requirement)
|
||||||
|
{
|
||||||
|
if (!FlexibleCollectionsIsEnabled)
|
||||||
|
{
|
||||||
|
// Flexible collections is OFF, should not be using this handler
|
||||||
|
throw new FeatureUnavailableException("Flexible collections is OFF when it should be ON.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!_currentContext.UserId.HasValue)
|
||||||
|
{
|
||||||
|
context.Fail();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (requirement.OrganizationId == default)
|
||||||
|
{
|
||||||
|
context.Fail();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var org = _currentContext.GetOrganization(requirement.OrganizationId);
|
||||||
|
|
||||||
|
switch (requirement)
|
||||||
|
{
|
||||||
|
case not null when requirement.Name == nameof(OrganizationUserOperations.ReadAll):
|
||||||
|
await CanReadAllAsync(context, requirement, org);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task CanReadAllAsync(AuthorizationHandlerContext context, OrganizationUserOperationRequirement requirement,
|
||||||
|
CurrentContextOrganization? org)
|
||||||
|
{
|
||||||
|
// If the limit collection management setting is disabled, allow any user to read all organization users
|
||||||
|
// Otherwise, Owners, Admins, and users with any of ManageGroups, ManageUsers, EditAnyCollection, DeleteAnyCollection, CreateNewCollections permissions can always read all organization users
|
||||||
|
if (org is
|
||||||
|
{ LimitCollectionCreationDeletion: false } or
|
||||||
|
{ Type: OrganizationUserType.Owner or OrganizationUserType.Admin } or
|
||||||
|
{ Permissions.ManageGroups: true } or
|
||||||
|
{ Permissions.ManageUsers: true } or
|
||||||
|
{ Permissions.EditAnyCollection: true } or
|
||||||
|
{ Permissions.DeleteAnyCollection: true } or
|
||||||
|
{ Permissions.CreateNewCollections: true })
|
||||||
|
{
|
||||||
|
context.Succeed(requirement);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow provider users to read all organization users if they are a provider for the target organization
|
||||||
|
if (await _currentContext.ProviderUserForOrgAsync(requirement.OrganizationId))
|
||||||
|
{
|
||||||
|
context.Succeed(requirement);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
using Microsoft.AspNetCore.Authorization.Infrastructure;
|
||||||
|
|
||||||
|
namespace Bit.Api.Vault.AuthorizationHandlers.OrganizationUsers;
|
||||||
|
|
||||||
|
public class OrganizationUserOperationRequirement : OperationAuthorizationRequirement
|
||||||
|
{
|
||||||
|
public Guid OrganizationId { get; }
|
||||||
|
|
||||||
|
public OrganizationUserOperationRequirement(string name, Guid organizationId)
|
||||||
|
{
|
||||||
|
Name = name;
|
||||||
|
OrganizationId = organizationId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class OrganizationUserOperations
|
||||||
|
{
|
||||||
|
public static OrganizationUserOperationRequirement ReadAll(Guid organizationId)
|
||||||
|
{
|
||||||
|
return new OrganizationUserOperationRequirement(nameof(ReadAll), organizationId);
|
||||||
|
}
|
||||||
|
}
|
@ -10,7 +10,9 @@ public class Permissions
|
|||||||
public bool CreateNewCollections { get; set; }
|
public bool CreateNewCollections { get; set; }
|
||||||
public bool EditAnyCollection { get; set; }
|
public bool EditAnyCollection { get; set; }
|
||||||
public bool DeleteAnyCollection { get; set; }
|
public bool DeleteAnyCollection { get; set; }
|
||||||
|
[Obsolete("Pre-Flexible Collections logic.")]
|
||||||
public bool EditAssignedCollections { get; set; }
|
public bool EditAssignedCollections { get; set; }
|
||||||
|
[Obsolete("Pre-Flexible Collections logic.")]
|
||||||
public bool DeleteAssignedCollections { get; set; }
|
public bool DeleteAssignedCollections { get; set; }
|
||||||
public bool ManageGroups { get; set; }
|
public bool ManageGroups { get; set; }
|
||||||
public bool ManagePolicies { get; set; }
|
public bool ManagePolicies { get; set; }
|
||||||
|
@ -5,9 +5,11 @@ using Bit.Core.AdminConsole.Models.Data.Provider;
|
|||||||
using Bit.Core.AdminConsole.Repositories;
|
using Bit.Core.AdminConsole.Repositories;
|
||||||
using Bit.Core.Entities;
|
using Bit.Core.Entities;
|
||||||
using Bit.Core.Enums;
|
using Bit.Core.Enums;
|
||||||
|
using Bit.Core.Exceptions;
|
||||||
using Bit.Core.Identity;
|
using Bit.Core.Identity;
|
||||||
using Bit.Core.Models.Data;
|
using Bit.Core.Models.Data;
|
||||||
using Bit.Core.Repositories;
|
using Bit.Core.Repositories;
|
||||||
|
using Bit.Core.Services;
|
||||||
using Bit.Core.Settings;
|
using Bit.Core.Settings;
|
||||||
using Bit.Core.Utilities;
|
using Bit.Core.Utilities;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
@ -18,11 +20,14 @@ public class CurrentContext : ICurrentContext
|
|||||||
{
|
{
|
||||||
private readonly IProviderOrganizationRepository _providerOrganizationRepository;
|
private readonly IProviderOrganizationRepository _providerOrganizationRepository;
|
||||||
private readonly IProviderUserRepository _providerUserRepository;
|
private readonly IProviderUserRepository _providerUserRepository;
|
||||||
|
private readonly IFeatureService _featureService;
|
||||||
private bool _builtHttpContext;
|
private bool _builtHttpContext;
|
||||||
private bool _builtClaimsPrincipal;
|
private bool _builtClaimsPrincipal;
|
||||||
private IEnumerable<ProviderOrganizationProviderDetails> _providerOrganizationProviderDetails;
|
private IEnumerable<ProviderOrganizationProviderDetails> _providerOrganizationProviderDetails;
|
||||||
private IEnumerable<ProviderUserOrganizationDetails> _providerUserOrganizations;
|
private IEnumerable<ProviderUserOrganizationDetails> _providerUserOrganizations;
|
||||||
|
|
||||||
|
private bool FlexibleCollectionsIsEnabled => _featureService.IsEnabled(FeatureFlagKeys.FlexibleCollections, this);
|
||||||
|
|
||||||
public virtual HttpContext HttpContext { get; set; }
|
public virtual HttpContext HttpContext { get; set; }
|
||||||
public virtual Guid? UserId { get; set; }
|
public virtual Guid? UserId { get; set; }
|
||||||
public virtual User User { get; set; }
|
public virtual User User { get; set; }
|
||||||
@ -44,10 +49,12 @@ public class CurrentContext : ICurrentContext
|
|||||||
|
|
||||||
public CurrentContext(
|
public CurrentContext(
|
||||||
IProviderOrganizationRepository providerOrganizationRepository,
|
IProviderOrganizationRepository providerOrganizationRepository,
|
||||||
IProviderUserRepository providerUserRepository)
|
IProviderUserRepository providerUserRepository,
|
||||||
|
IFeatureService featureService)
|
||||||
{
|
{
|
||||||
_providerOrganizationRepository = providerOrganizationRepository;
|
_providerOrganizationRepository = providerOrganizationRepository;
|
||||||
_providerUserRepository = providerUserRepository;
|
_providerUserRepository = providerUserRepository;
|
||||||
|
_featureService = featureService;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async virtual Task BuildAsync(HttpContext httpContext, GlobalSettings globalSettings)
|
public async virtual Task BuildAsync(HttpContext httpContext, GlobalSettings globalSettings)
|
||||||
@ -338,12 +345,22 @@ public class CurrentContext : ICurrentContext
|
|||||||
|
|
||||||
public async Task<bool> EditAssignedCollections(Guid orgId)
|
public async Task<bool> EditAssignedCollections(Guid orgId)
|
||||||
{
|
{
|
||||||
|
if (FlexibleCollectionsIsEnabled)
|
||||||
|
{
|
||||||
|
throw new FeatureUnavailableException("Flexible Collections is ON when it should be OFF.");
|
||||||
|
}
|
||||||
|
|
||||||
return await OrganizationManager(orgId) || (Organizations?.Any(o => o.Id == orgId
|
return await OrganizationManager(orgId) || (Organizations?.Any(o => o.Id == orgId
|
||||||
&& (o.Permissions?.EditAssignedCollections ?? false)) ?? false);
|
&& (o.Permissions?.EditAssignedCollections ?? false)) ?? false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<bool> DeleteAssignedCollections(Guid orgId)
|
public async Task<bool> DeleteAssignedCollections(Guid orgId)
|
||||||
{
|
{
|
||||||
|
if (FlexibleCollectionsIsEnabled)
|
||||||
|
{
|
||||||
|
throw new FeatureUnavailableException("Flexible Collections is ON when it should be OFF.");
|
||||||
|
}
|
||||||
|
|
||||||
return await OrganizationManager(orgId) || (Organizations?.Any(o => o.Id == orgId
|
return await OrganizationManager(orgId) || (Organizations?.Any(o => o.Id == orgId
|
||||||
&& (o.Permissions?.DeleteAssignedCollections ?? false)) ?? false);
|
&& (o.Permissions?.DeleteAssignedCollections ?? false)) ?? false);
|
||||||
}
|
}
|
||||||
@ -355,6 +372,12 @@ public class CurrentContext : ICurrentContext
|
|||||||
* Owner, Admin, Manager, and Provider checks are handled via the EditAssigned/DeleteAssigned context calls.
|
* Owner, Admin, Manager, and Provider checks are handled via the EditAssigned/DeleteAssigned context calls.
|
||||||
* This entire method will be moved to the CollectionAuthorizationHandler in the future
|
* This entire method will be moved to the CollectionAuthorizationHandler in the future
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
if (FlexibleCollectionsIsEnabled)
|
||||||
|
{
|
||||||
|
throw new FeatureUnavailableException("Flexible Collections is ON when it should be OFF.");
|
||||||
|
}
|
||||||
|
|
||||||
var canCreateNewCollections = false;
|
var canCreateNewCollections = false;
|
||||||
var org = GetOrganization(orgId);
|
var org = GetOrganization(orgId);
|
||||||
if (org != null)
|
if (org != null)
|
||||||
|
@ -45,8 +45,11 @@ public interface ICurrentContext
|
|||||||
Task<bool> AccessReports(Guid orgId);
|
Task<bool> AccessReports(Guid orgId);
|
||||||
Task<bool> EditAnyCollection(Guid orgId);
|
Task<bool> EditAnyCollection(Guid orgId);
|
||||||
Task<bool> ViewAllCollections(Guid orgId);
|
Task<bool> ViewAllCollections(Guid orgId);
|
||||||
|
[Obsolete("Pre-Flexible Collections logic.")]
|
||||||
Task<bool> EditAssignedCollections(Guid orgId);
|
Task<bool> EditAssignedCollections(Guid orgId);
|
||||||
|
[Obsolete("Pre-Flexible Collections logic.")]
|
||||||
Task<bool> DeleteAssignedCollections(Guid orgId);
|
Task<bool> DeleteAssignedCollections(Guid orgId);
|
||||||
|
[Obsolete("Pre-Flexible Collections logic.")]
|
||||||
Task<bool> ViewAssignedCollections(Guid orgId);
|
Task<bool> ViewAssignedCollections(Guid orgId);
|
||||||
Task<bool> ManageGroups(Guid orgId);
|
Task<bool> ManageGroups(Guid orgId);
|
||||||
Task<bool> ManagePolicies(Guid orgId);
|
Task<bool> ManagePolicies(Guid orgId);
|
||||||
|
@ -10,7 +10,7 @@ public interface ICollectionRepository : IRepository<Collection, Guid>
|
|||||||
Task<Tuple<CollectionDetails, CollectionAccessDetails>> GetByIdWithAccessAsync(Guid id, Guid userId);
|
Task<Tuple<CollectionDetails, CollectionAccessDetails>> GetByIdWithAccessAsync(Guid id, Guid userId);
|
||||||
Task<ICollection<Collection>> GetManyByOrganizationIdAsync(Guid organizationId);
|
Task<ICollection<Collection>> GetManyByOrganizationIdAsync(Guid organizationId);
|
||||||
Task<ICollection<Tuple<Collection, CollectionAccessDetails>>> GetManyByOrganizationIdWithAccessAsync(Guid organizationId);
|
Task<ICollection<Tuple<Collection, CollectionAccessDetails>>> GetManyByOrganizationIdWithAccessAsync(Guid organizationId);
|
||||||
Task<ICollection<Tuple<Collection, CollectionAccessDetails>>> GetManyByUserIdWithAccessAsync(Guid userId, Guid organizationId);
|
Task<ICollection<Tuple<CollectionDetails, CollectionAccessDetails>>> GetManyByUserIdWithAccessAsync(Guid userId, Guid organizationId);
|
||||||
Task<CollectionDetails> GetByIdAsync(Guid id, Guid userId);
|
Task<CollectionDetails> GetByIdAsync(Guid id, Guid userId);
|
||||||
Task<ICollection<Collection>> GetManyByManyIdsAsync(IEnumerable<Guid> collectionIds);
|
Task<ICollection<Collection>> GetManyByManyIdsAsync(IEnumerable<Guid> collectionIds);
|
||||||
Task<ICollection<CollectionDetails>> GetManyByUserIdAsync(Guid userId);
|
Task<ICollection<CollectionDetails>> GetManyByUserIdAsync(Guid userId);
|
||||||
|
@ -7,5 +7,6 @@ public interface ICollectionService
|
|||||||
{
|
{
|
||||||
Task SaveAsync(Collection collection, IEnumerable<CollectionAccessSelection> groups = null, IEnumerable<CollectionAccessSelection> users = null);
|
Task SaveAsync(Collection collection, IEnumerable<CollectionAccessSelection> groups = null, IEnumerable<CollectionAccessSelection> users = null);
|
||||||
Task DeleteUserAsync(Collection collection, Guid organizationUserId);
|
Task DeleteUserAsync(Collection collection, Guid organizationUserId);
|
||||||
|
[Obsolete("Pre-Flexible Collections logic.")]
|
||||||
Task<IEnumerable<Collection>> GetOrganizationCollectionsAsync(Guid organizationId);
|
Task<IEnumerable<Collection>> GetOrganizationCollectionsAsync(Guid organizationId);
|
||||||
}
|
}
|
||||||
|
@ -139,7 +139,7 @@ public class CollectionRepository : Repository<Collection, Guid>, ICollectionRep
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<ICollection<Tuple<Collection, CollectionAccessDetails>>> GetManyByUserIdWithAccessAsync(Guid userId, Guid organizationId)
|
public async Task<ICollection<Tuple<CollectionDetails, CollectionAccessDetails>>> GetManyByUserIdWithAccessAsync(Guid userId, Guid organizationId)
|
||||||
{
|
{
|
||||||
using (var connection = new SqlConnection(ConnectionString))
|
using (var connection = new SqlConnection(ConnectionString))
|
||||||
{
|
{
|
||||||
@ -148,14 +148,14 @@ public class CollectionRepository : Repository<Collection, Guid>, ICollectionRep
|
|||||||
new { UserId = userId },
|
new { UserId = userId },
|
||||||
commandType: CommandType.StoredProcedure);
|
commandType: CommandType.StoredProcedure);
|
||||||
|
|
||||||
var collections = (await results.ReadAsync<Collection>()).Where(c => c.OrganizationId == organizationId);
|
var collections = (await results.ReadAsync<CollectionDetails>()).Where(c => c.OrganizationId == organizationId);
|
||||||
var groups = (await results.ReadAsync<CollectionGroup>())
|
var groups = (await results.ReadAsync<CollectionGroup>())
|
||||||
.GroupBy(g => g.CollectionId);
|
.GroupBy(g => g.CollectionId);
|
||||||
var users = (await results.ReadAsync<CollectionUser>())
|
var users = (await results.ReadAsync<CollectionUser>())
|
||||||
.GroupBy(u => u.CollectionId);
|
.GroupBy(u => u.CollectionId);
|
||||||
|
|
||||||
return collections.Select(collection =>
|
return collections.Select(collection =>
|
||||||
new Tuple<Collection, CollectionAccessDetails>(
|
new Tuple<CollectionDetails, CollectionAccessDetails>(
|
||||||
collection,
|
collection,
|
||||||
new CollectionAccessDetails
|
new CollectionAccessDetails
|
||||||
{
|
{
|
||||||
@ -181,7 +181,6 @@ public class CollectionRepository : Repository<Collection, Guid>, ICollectionRep
|
|||||||
)
|
)
|
||||||
).ToList();
|
).ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<CollectionDetails> GetByIdAsync(Guid id, Guid userId)
|
public async Task<CollectionDetails> GetByIdAsync(Guid id, Guid userId)
|
||||||
|
@ -231,7 +231,7 @@ public class CollectionRepository : Repository<Core.Entities.Collection, Collect
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<ICollection<Tuple<Core.Entities.Collection, CollectionAccessDetails>>> GetManyByUserIdWithAccessAsync(Guid userId, Guid organizationId)
|
public async Task<ICollection<Tuple<CollectionDetails, CollectionAccessDetails>>> GetManyByUserIdWithAccessAsync(Guid userId, Guid organizationId)
|
||||||
{
|
{
|
||||||
var collections = (await GetManyByUserIdAsync(userId)).Where(c => c.OrganizationId == organizationId).ToList();
|
var collections = (await GetManyByUserIdAsync(userId)).Where(c => c.OrganizationId == organizationId).ToList();
|
||||||
using (var scope = ServiceScopeFactory.CreateScope())
|
using (var scope = ServiceScopeFactory.CreateScope())
|
||||||
@ -249,7 +249,7 @@ public class CollectionRepository : Repository<Core.Entities.Collection, Collect
|
|||||||
select u;
|
select u;
|
||||||
|
|
||||||
return collections.Select(collection =>
|
return collections.Select(collection =>
|
||||||
new Tuple<Core.Entities.Collection, CollectionAccessDetails>(
|
new Tuple<CollectionDetails, CollectionAccessDetails>(
|
||||||
collection,
|
collection,
|
||||||
new CollectionAccessDetails
|
new CollectionAccessDetails
|
||||||
{
|
{
|
||||||
|
@ -18,7 +18,7 @@ public class NotificationsHub : Microsoft.AspNetCore.SignalR.Hub
|
|||||||
|
|
||||||
public override async Task OnConnectedAsync()
|
public override async Task OnConnectedAsync()
|
||||||
{
|
{
|
||||||
var currentContext = new CurrentContext(null, null);
|
var currentContext = new CurrentContext(null, null, null);
|
||||||
await currentContext.BuildAsync(Context.User, _globalSettings);
|
await currentContext.BuildAsync(Context.User, _globalSettings);
|
||||||
if (currentContext.Organizations != null)
|
if (currentContext.Organizations != null)
|
||||||
{
|
{
|
||||||
@ -33,7 +33,7 @@ public class NotificationsHub : Microsoft.AspNetCore.SignalR.Hub
|
|||||||
|
|
||||||
public override async Task OnDisconnectedAsync(Exception exception)
|
public override async Task OnDisconnectedAsync(Exception exception)
|
||||||
{
|
{
|
||||||
var currentContext = new CurrentContext(null, null);
|
var currentContext = new CurrentContext(null, null, null);
|
||||||
await currentContext.BuildAsync(Context.User, _globalSettings);
|
await currentContext.BuildAsync(Context.User, _globalSettings);
|
||||||
if (currentContext.Organizations != null)
|
if (currentContext.Organizations != null)
|
||||||
{
|
{
|
||||||
|
@ -36,7 +36,7 @@ public class CollectionsControllerTests
|
|||||||
sutProvider.GetDependency<IAuthorizationService>()
|
sutProvider.GetDependency<IAuthorizationService>()
|
||||||
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(),
|
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(),
|
||||||
ExpectedCollection(),
|
ExpectedCollection(),
|
||||||
Arg.Is<IEnumerable<IAuthorizationRequirement>>(r => r.Contains(CollectionOperations.Create)))
|
Arg.Is<IEnumerable<IAuthorizationRequirement>>(r => r.Contains(BulkCollectionOperations.Create)))
|
||||||
.Returns(AuthorizationResult.Success());
|
.Returns(AuthorizationResult.Success());
|
||||||
|
|
||||||
_ = await sutProvider.Sut.Post(orgId, collectionRequest);
|
_ = await sutProvider.Sut.Post(orgId, collectionRequest);
|
||||||
@ -48,101 +48,126 @@ public class CollectionsControllerTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Theory, BitAutoData]
|
[Theory, BitAutoData]
|
||||||
public async Task Put_Success(Guid orgId, Guid collectionId, Guid userId, CollectionRequestModel collectionRequest,
|
public async Task Put_Success(Collection collection, CollectionRequestModel collectionRequest,
|
||||||
SutProvider<CollectionsController> sutProvider)
|
SutProvider<CollectionsController> sutProvider)
|
||||||
{
|
{
|
||||||
sutProvider.GetDependency<ICurrentContext>()
|
Collection ExpectedCollection() => Arg.Is<Collection>(c => c.Id == collection.Id &&
|
||||||
.ViewAssignedCollections(orgId)
|
c.Name == collectionRequest.Name && c.ExternalId == collectionRequest.ExternalId &&
|
||||||
.Returns(true);
|
c.OrganizationId == collection.OrganizationId);
|
||||||
|
|
||||||
sutProvider.GetDependency<ICurrentContext>()
|
|
||||||
.EditAssignedCollections(orgId)
|
|
||||||
.Returns(true);
|
|
||||||
|
|
||||||
sutProvider.GetDependency<ICurrentContext>()
|
|
||||||
.UserId
|
|
||||||
.Returns(userId);
|
|
||||||
|
|
||||||
sutProvider.GetDependency<ICollectionRepository>()
|
sutProvider.GetDependency<ICollectionRepository>()
|
||||||
.GetByIdAsync(collectionId, userId)
|
.GetByIdAsync(collection.Id)
|
||||||
.Returns(new CollectionDetails
|
.Returns(collection);
|
||||||
{
|
|
||||||
OrganizationId = orgId,
|
|
||||||
});
|
|
||||||
|
|
||||||
_ = await sutProvider.Sut.Put(orgId, collectionId, collectionRequest);
|
sutProvider.GetDependency<IAuthorizationService>()
|
||||||
|
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(),
|
||||||
|
collection,
|
||||||
|
Arg.Is<IEnumerable<IAuthorizationRequirement>>(r => r.Contains(BulkCollectionOperations.Update)))
|
||||||
|
.Returns(AuthorizationResult.Success());
|
||||||
|
|
||||||
|
_ = await sutProvider.Sut.Put(collection.OrganizationId, collection.Id, collectionRequest);
|
||||||
|
|
||||||
|
await sutProvider.GetDependency<ICollectionService>()
|
||||||
|
.Received(1)
|
||||||
|
.SaveAsync(ExpectedCollection(), Arg.Any<IEnumerable<CollectionAccessSelection>>(),
|
||||||
|
Arg.Any<IEnumerable<CollectionAccessSelection>>());
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory, BitAutoData]
|
[Theory, BitAutoData]
|
||||||
public async Task Put_CanNotEditAssignedCollection_ThrowsNotFound(Guid orgId, Guid collectionId, Guid userId, CollectionRequestModel collectionRequest,
|
public async Task Put_WithNoCollectionPermission_ThrowsNotFound(Collection collection, CollectionRequestModel collectionRequest,
|
||||||
SutProvider<CollectionsController> sutProvider)
|
SutProvider<CollectionsController> sutProvider)
|
||||||
{
|
{
|
||||||
sutProvider.GetDependency<ICurrentContext>()
|
sutProvider.GetDependency<IAuthorizationService>()
|
||||||
.EditAssignedCollections(orgId)
|
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(),
|
||||||
.Returns(true);
|
collection,
|
||||||
|
Arg.Is<IEnumerable<IAuthorizationRequirement>>(r => r.Contains(BulkCollectionOperations.Update)))
|
||||||
sutProvider.GetDependency<ICurrentContext>()
|
.Returns(AuthorizationResult.Failed());
|
||||||
.UserId
|
|
||||||
.Returns(userId);
|
|
||||||
|
|
||||||
sutProvider.GetDependency<ICollectionRepository>()
|
sutProvider.GetDependency<ICollectionRepository>()
|
||||||
.GetByIdAsync(collectionId, userId)
|
.GetByIdAsync(collection.Id)
|
||||||
.Returns(Task.FromResult<CollectionDetails>(null));
|
.Returns(collection);
|
||||||
|
|
||||||
_ = await Assert.ThrowsAsync<NotFoundException>(async () => await sutProvider.Sut.Put(orgId, collectionId, collectionRequest));
|
_ = await Assert.ThrowsAsync<NotFoundException>(async () => await sutProvider.Sut.Put(collection.OrganizationId, collection.Id, collectionRequest));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory, BitAutoData]
|
[Theory, BitAutoData]
|
||||||
public async Task GetOrganizationCollectionsWithGroups_NoManagerPermissions_ThrowsNotFound(Organization organization, SutProvider<CollectionsController> sutProvider)
|
public async Task GetOrganizationCollectionsWithGroups_WithReadAllPermissions_GetsAllCollections(Organization organization, Guid userId, SutProvider<CollectionsController> sutProvider)
|
||||||
{
|
{
|
||||||
sutProvider.GetDependency<ICurrentContext>().ViewAssignedCollections(organization.Id).Returns(false);
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
|
|
||||||
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.GetManyWithDetails(organization.Id));
|
sutProvider.GetDependency<IAuthorizationService>()
|
||||||
await sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs().GetManyByOrganizationIdWithAccessAsync(default);
|
.AuthorizeAsync(
|
||||||
await sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs().GetManyByUserIdWithAccessAsync(default, default);
|
Arg.Any<ClaimsPrincipal>(),
|
||||||
}
|
Arg.Any<object>(),
|
||||||
|
Arg.Is<IEnumerable<IAuthorizationRequirement>>(requirements =>
|
||||||
[Theory, BitAutoData]
|
requirements.Cast<CollectionOperationRequirement>().All(operation =>
|
||||||
public async Task GetOrganizationCollectionsWithGroups_AdminPermissions_GetsAllCollections(Organization organization, User user, SutProvider<CollectionsController> sutProvider)
|
operation.Name == nameof(CollectionOperations.ReadAllWithAccess)
|
||||||
{
|
&& operation.OrganizationId == organization.Id)))
|
||||||
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(user.Id);
|
.Returns(AuthorizationResult.Success());
|
||||||
sutProvider.GetDependency<ICurrentContext>().ViewAllCollections(organization.Id).Returns(true);
|
|
||||||
sutProvider.GetDependency<ICurrentContext>().OrganizationAdmin(organization.Id).Returns(true);
|
|
||||||
|
|
||||||
await sutProvider.Sut.GetManyWithDetails(organization.Id);
|
await sutProvider.Sut.GetManyWithDetails(organization.Id);
|
||||||
|
|
||||||
await sutProvider.GetDependency<ICollectionRepository>().Received().GetManyByOrganizationIdWithAccessAsync(organization.Id);
|
await sutProvider.GetDependency<ICollectionRepository>().Received(1).GetManyByUserIdWithAccessAsync(userId, organization.Id);
|
||||||
await sutProvider.GetDependency<ICollectionRepository>().Received().GetManyByUserIdWithAccessAsync(user.Id, organization.Id);
|
await sutProvider.GetDependency<ICollectionRepository>().Received(1).GetManyByOrganizationIdWithAccessAsync(organization.Id);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory, BitAutoData]
|
[Theory, BitAutoData]
|
||||||
public async Task GetOrganizationCollectionsWithGroups_MissingViewAllPermissions_GetsAssignedCollections(Organization organization, User user, SutProvider<CollectionsController> sutProvider)
|
public async Task GetOrganizationCollectionsWithGroups_MissingReadAllPermissions_GetsAssignedCollections(Organization organization, Guid userId, SutProvider<CollectionsController> sutProvider)
|
||||||
{
|
{
|
||||||
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(user.Id);
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
sutProvider.GetDependency<ICurrentContext>().ViewAssignedCollections(organization.Id).Returns(true);
|
|
||||||
sutProvider.GetDependency<ICurrentContext>().OrganizationManager(organization.Id).Returns(true);
|
sutProvider.GetDependency<IAuthorizationService>()
|
||||||
|
.AuthorizeAsync(
|
||||||
|
Arg.Any<ClaimsPrincipal>(),
|
||||||
|
Arg.Any<object>(),
|
||||||
|
Arg.Is<IEnumerable<IAuthorizationRequirement>>(requirements =>
|
||||||
|
requirements.Cast<CollectionOperationRequirement>().All(operation =>
|
||||||
|
operation.Name == nameof(CollectionOperations.ReadAllWithAccess)
|
||||||
|
&& operation.OrganizationId == organization.Id)))
|
||||||
|
.Returns(AuthorizationResult.Failed());
|
||||||
|
|
||||||
|
sutProvider.GetDependency<IAuthorizationService>()
|
||||||
|
.AuthorizeAsync(
|
||||||
|
Arg.Any<ClaimsPrincipal>(),
|
||||||
|
Arg.Any<object>(),
|
||||||
|
Arg.Is<IEnumerable<IAuthorizationRequirement>>(requirements =>
|
||||||
|
requirements.Cast<BulkCollectionOperationRequirement>().All(operation =>
|
||||||
|
operation.Name == nameof(BulkCollectionOperations.ReadWithAccess))))
|
||||||
|
.Returns(AuthorizationResult.Success());
|
||||||
|
|
||||||
await sutProvider.Sut.GetManyWithDetails(organization.Id);
|
await sutProvider.Sut.GetManyWithDetails(organization.Id);
|
||||||
|
|
||||||
await sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs().GetManyByOrganizationIdWithAccessAsync(default);
|
await sutProvider.GetDependency<ICollectionRepository>().Received(1).GetManyByUserIdWithAccessAsync(userId, organization.Id);
|
||||||
await sutProvider.GetDependency<ICollectionRepository>().Received().GetManyByUserIdWithAccessAsync(user.Id, organization.Id);
|
await sutProvider.GetDependency<ICollectionRepository>().DidNotReceive().GetManyByOrganizationIdWithAccessAsync(organization.Id);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory, BitAutoData]
|
[Theory, BitAutoData]
|
||||||
public async Task GetOrganizationCollectionsWithGroups_CustomUserWithManagerPermissions_GetsAssignedCollections(Organization organization, User user, SutProvider<CollectionsController> sutProvider)
|
public async Task GetOrganizationCollectionsWithGroups_MissingReadPermissions_ThrowsNotFound(Organization organization, Guid userId, SutProvider<CollectionsController> sutProvider)
|
||||||
{
|
{
|
||||||
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(user.Id);
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
sutProvider.GetDependency<ICurrentContext>().ViewAssignedCollections(organization.Id).Returns(true);
|
|
||||||
sutProvider.GetDependency<ICurrentContext>().EditAssignedCollections(organization.Id).Returns(true);
|
|
||||||
|
|
||||||
|
sutProvider.GetDependency<IAuthorizationService>()
|
||||||
|
.AuthorizeAsync(
|
||||||
|
Arg.Any<ClaimsPrincipal>(),
|
||||||
|
Arg.Any<object>(),
|
||||||
|
Arg.Is<IEnumerable<IAuthorizationRequirement>>(requirements =>
|
||||||
|
requirements.Cast<CollectionOperationRequirement>().All(operation =>
|
||||||
|
operation.Name == nameof(CollectionOperations.ReadAllWithAccess)
|
||||||
|
&& operation.OrganizationId == organization.Id)))
|
||||||
|
.Returns(AuthorizationResult.Failed());
|
||||||
|
|
||||||
await sutProvider.Sut.GetManyWithDetails(organization.Id);
|
sutProvider.GetDependency<IAuthorizationService>()
|
||||||
|
.AuthorizeAsync(
|
||||||
|
Arg.Any<ClaimsPrincipal>(),
|
||||||
|
Arg.Any<object>(),
|
||||||
|
Arg.Is<IEnumerable<IAuthorizationRequirement>>(requirements =>
|
||||||
|
requirements.Cast<BulkCollectionOperationRequirement>().All(operation =>
|
||||||
|
operation.Name == nameof(BulkCollectionOperations.ReadWithAccess))))
|
||||||
|
.Returns(AuthorizationResult.Failed());
|
||||||
|
|
||||||
await sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs().GetManyByOrganizationIdWithAccessAsync(default);
|
_ = await Assert.ThrowsAsync<NotFoundException>(async () => await sutProvider.Sut.GetManyWithDetails(organization.Id));
|
||||||
await sutProvider.GetDependency<ICollectionRepository>().Received().GetManyByUserIdWithAccessAsync(user.Id, organization.Id);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
[Theory, BitAutoData]
|
[Theory, BitAutoData]
|
||||||
public async Task DeleteMany_Success(Guid orgId, Collection collection1, Collection collection2, SutProvider<CollectionsController> sutProvider)
|
public async Task DeleteMany_Success(Guid orgId, Collection collection1, Collection collection2, SutProvider<CollectionsController> sutProvider)
|
||||||
{
|
{
|
||||||
@ -172,7 +197,7 @@ public class CollectionsControllerTests
|
|||||||
sutProvider.GetDependency<IAuthorizationService>()
|
sutProvider.GetDependency<IAuthorizationService>()
|
||||||
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(),
|
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(),
|
||||||
collections,
|
collections,
|
||||||
Arg.Is<IEnumerable<IAuthorizationRequirement>>(r => r.Contains(CollectionOperations.Delete)))
|
Arg.Is<IEnumerable<IAuthorizationRequirement>>(r => r.Contains(BulkCollectionOperations.Delete)))
|
||||||
.Returns(AuthorizationResult.Success());
|
.Returns(AuthorizationResult.Success());
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
@ -214,7 +239,7 @@ public class CollectionsControllerTests
|
|||||||
sutProvider.GetDependency<IAuthorizationService>()
|
sutProvider.GetDependency<IAuthorizationService>()
|
||||||
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(),
|
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(),
|
||||||
collections,
|
collections,
|
||||||
Arg.Is<IEnumerable<IAuthorizationRequirement>>(r => r.Contains(CollectionOperations.Delete)))
|
Arg.Is<IEnumerable<IAuthorizationRequirement>>(r => r.Contains(BulkCollectionOperations.Delete)))
|
||||||
.Returns(AuthorizationResult.Failed());
|
.Returns(AuthorizationResult.Failed());
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
@ -249,7 +274,7 @@ public class CollectionsControllerTests
|
|||||||
sutProvider.GetDependency<IAuthorizationService>().AuthorizeAsync(
|
sutProvider.GetDependency<IAuthorizationService>().AuthorizeAsync(
|
||||||
Arg.Any<ClaimsPrincipal>(), ExpectedCollectionAccess(),
|
Arg.Any<ClaimsPrincipal>(), ExpectedCollectionAccess(),
|
||||||
Arg.Is<IEnumerable<IAuthorizationRequirement>>(
|
Arg.Is<IEnumerable<IAuthorizationRequirement>>(
|
||||||
r => r.Contains(CollectionOperations.ModifyAccess)
|
r => r.Contains(BulkCollectionOperations.ModifyAccess)
|
||||||
))
|
))
|
||||||
.Returns(AuthorizationResult.Success());
|
.Returns(AuthorizationResult.Success());
|
||||||
|
|
||||||
@ -263,7 +288,7 @@ public class CollectionsControllerTests
|
|||||||
Arg.Any<ClaimsPrincipal>(),
|
Arg.Any<ClaimsPrincipal>(),
|
||||||
ExpectedCollectionAccess(),
|
ExpectedCollectionAccess(),
|
||||||
Arg.Is<IEnumerable<IAuthorizationRequirement>>(
|
Arg.Is<IEnumerable<IAuthorizationRequirement>>(
|
||||||
r => r.Contains(CollectionOperations.ModifyAccess))
|
r => r.Contains(BulkCollectionOperations.ModifyAccess))
|
||||||
);
|
);
|
||||||
await sutProvider.GetDependency<IBulkAddCollectionAccessCommand>().Received()
|
await sutProvider.GetDependency<IBulkAddCollectionAccessCommand>().Received()
|
||||||
.AddAccessAsync(
|
.AddAccessAsync(
|
||||||
@ -325,7 +350,7 @@ public class CollectionsControllerTests
|
|||||||
sutProvider.GetDependency<IAuthorizationService>().AuthorizeAsync(
|
sutProvider.GetDependency<IAuthorizationService>().AuthorizeAsync(
|
||||||
Arg.Any<ClaimsPrincipal>(), ExpectedCollectionAccess(),
|
Arg.Any<ClaimsPrincipal>(), ExpectedCollectionAccess(),
|
||||||
Arg.Is<IEnumerable<IAuthorizationRequirement>>(
|
Arg.Is<IEnumerable<IAuthorizationRequirement>>(
|
||||||
r => r.Contains(CollectionOperations.ModifyAccess)
|
r => r.Contains(BulkCollectionOperations.ModifyAccess)
|
||||||
))
|
))
|
||||||
.Returns(AuthorizationResult.Failed());
|
.Returns(AuthorizationResult.Failed());
|
||||||
|
|
||||||
@ -336,7 +361,7 @@ public class CollectionsControllerTests
|
|||||||
Arg.Any<ClaimsPrincipal>(),
|
Arg.Any<ClaimsPrincipal>(),
|
||||||
ExpectedCollectionAccess(),
|
ExpectedCollectionAccess(),
|
||||||
Arg.Is<IEnumerable<IAuthorizationRequirement>>(
|
Arg.Is<IEnumerable<IAuthorizationRequirement>>(
|
||||||
r => r.Contains(CollectionOperations.ModifyAccess))
|
r => r.Contains(BulkCollectionOperations.ModifyAccess))
|
||||||
);
|
);
|
||||||
await sutProvider.GetDependency<IBulkAddCollectionAccessCommand>().DidNotReceiveWithAnyArgs()
|
await sutProvider.GetDependency<IBulkAddCollectionAccessCommand>().DidNotReceiveWithAnyArgs()
|
||||||
.AddAccessAsync(default, default, default);
|
.AddAccessAsync(default, default, default);
|
||||||
|
@ -0,0 +1,948 @@
|
|||||||
|
using System.Security.Claims;
|
||||||
|
using Bit.Api.Vault.AuthorizationHandlers.Collections;
|
||||||
|
using Bit.Core;
|
||||||
|
using Bit.Core.Context;
|
||||||
|
using Bit.Core.Entities;
|
||||||
|
using Bit.Core.Enums;
|
||||||
|
using Bit.Core.Exceptions;
|
||||||
|
using Bit.Core.Models.Data;
|
||||||
|
using Bit.Core.Repositories;
|
||||||
|
using Bit.Core.Test.AutoFixture;
|
||||||
|
using Bit.Core.Test.Vault.AutoFixture;
|
||||||
|
using Bit.Test.Common.AutoFixture;
|
||||||
|
using Bit.Test.Common.AutoFixture.Attributes;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using NSubstitute;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace Bit.Api.Test.Vault.AuthorizationHandlers;
|
||||||
|
|
||||||
|
[SutProviderCustomize]
|
||||||
|
[FeatureServiceCustomize(FeatureFlagKeys.FlexibleCollections)]
|
||||||
|
public class BulkCollectionAuthorizationHandlerTests
|
||||||
|
{
|
||||||
|
[Theory, CollectionCustomization]
|
||||||
|
[BitAutoData(OrganizationUserType.Admin)]
|
||||||
|
[BitAutoData(OrganizationUserType.Owner)]
|
||||||
|
public async Task CanCreateAsync_WhenAdminOrOwner_Success(
|
||||||
|
OrganizationUserType userType,
|
||||||
|
Guid userId, SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<Collection> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
organization.Type = userType;
|
||||||
|
organization.LimitCollectionCreationDeletion = true;
|
||||||
|
organization.Permissions = new Permissions();
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.Create },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData, CollectionCustomization]
|
||||||
|
public async Task CanCreateAsync_WhenUser_WithLimitCollectionCreationDeletionFalse_Success(
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<Collection> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = OrganizationUserType.User;
|
||||||
|
organization.LimitCollectionCreationDeletion = false;
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.Create },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, CollectionCustomization]
|
||||||
|
[BitAutoData(OrganizationUserType.User)]
|
||||||
|
[BitAutoData(OrganizationUserType.Custom)]
|
||||||
|
public async Task CanCreateAsync_WhenMissingPermissions_NoSuccess(
|
||||||
|
OrganizationUserType userType,
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<Collection> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = userType;
|
||||||
|
organization.LimitCollectionCreationDeletion = true;
|
||||||
|
organization.Permissions = new Permissions
|
||||||
|
{
|
||||||
|
EditAnyCollection = false,
|
||||||
|
DeleteAnyCollection = false,
|
||||||
|
ManageGroups = false,
|
||||||
|
ManageUsers = false
|
||||||
|
};
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.Create },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData, CollectionCustomization]
|
||||||
|
public async Task CanCreateAsync_WhenMissingOrgAccess_NoSuccess(
|
||||||
|
Guid userId,
|
||||||
|
ICollection<Collection> collections,
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider)
|
||||||
|
{
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.Create },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections
|
||||||
|
);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(Arg.Any<Guid>()).Returns((CurrentContextOrganization)null);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, CollectionCustomization]
|
||||||
|
[BitAutoData(OrganizationUserType.Admin)]
|
||||||
|
[BitAutoData(OrganizationUserType.Owner)]
|
||||||
|
public async Task CanReadAsync_WhenAdminOrOwner_Success(
|
||||||
|
OrganizationUserType userType,
|
||||||
|
Guid userId, SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<Collection> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
organization.Type = userType;
|
||||||
|
organization.LimitCollectionCreationDeletion = true;
|
||||||
|
organization.Permissions = new Permissions();
|
||||||
|
|
||||||
|
var operationsToTest = new[]
|
||||||
|
{
|
||||||
|
BulkCollectionOperations.Read, BulkCollectionOperations.ReadAccess
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var op in operationsToTest)
|
||||||
|
{
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.Read },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
|
||||||
|
// Recreate the SUT to reset the mocks/dependencies between tests
|
||||||
|
sutProvider.Recreate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, CollectionCustomization]
|
||||||
|
[BitAutoData(true, false)]
|
||||||
|
[BitAutoData(false, true)]
|
||||||
|
public async Task CanReadAsync_WhenCustomUserWithRequiredPermissions_Success(
|
||||||
|
bool editAnyCollection, bool deleteAnyCollection,
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<Collection> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = OrganizationUserType.Custom;
|
||||||
|
organization.Permissions = new Permissions
|
||||||
|
{
|
||||||
|
EditAnyCollection = editAnyCollection,
|
||||||
|
DeleteAnyCollection = deleteAnyCollection
|
||||||
|
};
|
||||||
|
|
||||||
|
var operationsToTest = new[]
|
||||||
|
{
|
||||||
|
BulkCollectionOperations.Read, BulkCollectionOperations.ReadAccess
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var op in operationsToTest)
|
||||||
|
{
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.Read },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
|
||||||
|
// Recreate the SUT to reset the mocks/dependencies between tests
|
||||||
|
sutProvider.Recreate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData, CollectionCustomization]
|
||||||
|
public async Task CanReadAsync_WhenUserIsAssignedToCollections_Success(
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<CollectionDetails> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = OrganizationUserType.User;
|
||||||
|
organization.LimitCollectionCreationDeletion = false;
|
||||||
|
organization.Permissions = new Permissions();
|
||||||
|
|
||||||
|
var operationsToTest = new[]
|
||||||
|
{
|
||||||
|
BulkCollectionOperations.Read, BulkCollectionOperations.ReadAccess
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var op in operationsToTest)
|
||||||
|
{
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
sutProvider.GetDependency<ICollectionRepository>().GetManyByUserIdAsync(actingUserId).Returns(collections);
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.Read },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
|
||||||
|
// Recreate the SUT to reset the mocks/dependencies between tests
|
||||||
|
sutProvider.Recreate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData, CollectionCustomization]
|
||||||
|
public async Task CanReadAsync_WhenUserIsNotAssignedToCollections_NoSuccess(
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<CollectionDetails> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = OrganizationUserType.User;
|
||||||
|
organization.LimitCollectionCreationDeletion = false;
|
||||||
|
organization.Permissions = new Permissions();
|
||||||
|
|
||||||
|
var operationsToTest = new[]
|
||||||
|
{
|
||||||
|
BulkCollectionOperations.Read, BulkCollectionOperations.ReadAccess
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var op in operationsToTest)
|
||||||
|
{
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.Read },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
|
||||||
|
// Recreate the SUT to reset the mocks/dependencies between tests
|
||||||
|
sutProvider.Recreate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, CollectionCustomization]
|
||||||
|
[BitAutoData(OrganizationUserType.User)]
|
||||||
|
[BitAutoData(OrganizationUserType.Custom)]
|
||||||
|
public async Task CanReadAsync_WhenMissingPermissions_NoSuccess(
|
||||||
|
OrganizationUserType userType,
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<Collection> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = userType;
|
||||||
|
organization.LimitCollectionCreationDeletion = true;
|
||||||
|
organization.Permissions = new Permissions
|
||||||
|
{
|
||||||
|
EditAnyCollection = false,
|
||||||
|
DeleteAnyCollection = false,
|
||||||
|
ManageGroups = false,
|
||||||
|
ManageUsers = false
|
||||||
|
};
|
||||||
|
|
||||||
|
var operationsToTest = new[]
|
||||||
|
{
|
||||||
|
BulkCollectionOperations.Read, BulkCollectionOperations.ReadAccess
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var op in operationsToTest)
|
||||||
|
{
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.Read },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
|
||||||
|
// Recreate the SUT to reset the mocks/dependencies between tests
|
||||||
|
sutProvider.Recreate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData, CollectionCustomization]
|
||||||
|
public async Task CanReadAsync_WhenMissingOrgAccess_NoSuccess(
|
||||||
|
Guid userId,
|
||||||
|
ICollection<Collection> collections,
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider)
|
||||||
|
{
|
||||||
|
var operationsToTest = new[]
|
||||||
|
{
|
||||||
|
BulkCollectionOperations.Read, BulkCollectionOperations.ReadAccess
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var op in operationsToTest)
|
||||||
|
{
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(Arg.Any<Guid>()).Returns((CurrentContextOrganization)null);
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { op },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections
|
||||||
|
);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
|
||||||
|
// Recreate the SUT to reset the mocks/dependencies between tests
|
||||||
|
sutProvider.Recreate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, CollectionCustomization]
|
||||||
|
[BitAutoData(OrganizationUserType.Admin)]
|
||||||
|
[BitAutoData(OrganizationUserType.Owner)]
|
||||||
|
public async Task CanReadWithAccessAsync_WhenAdminOrOwner_Success(
|
||||||
|
OrganizationUserType userType,
|
||||||
|
Guid userId, SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<Collection> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
organization.Type = userType;
|
||||||
|
organization.LimitCollectionCreationDeletion = true;
|
||||||
|
organization.Permissions = new Permissions();
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.ReadWithAccess },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, CollectionCustomization]
|
||||||
|
[BitAutoData(true, false, false)]
|
||||||
|
[BitAutoData(false, true, false)]
|
||||||
|
[BitAutoData(false, false, true)]
|
||||||
|
|
||||||
|
public async Task CanReadWithAccessAsync_WhenCustomUserWithRequiredPermissions_Success(
|
||||||
|
bool editAnyCollection, bool deleteAnyCollection, bool manageUsers,
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<Collection> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = OrganizationUserType.Custom;
|
||||||
|
organization.Permissions = new Permissions
|
||||||
|
{
|
||||||
|
EditAnyCollection = editAnyCollection,
|
||||||
|
DeleteAnyCollection = deleteAnyCollection,
|
||||||
|
ManageUsers = manageUsers
|
||||||
|
};
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.ReadWithAccess },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData, CollectionCustomization]
|
||||||
|
public async Task CanReadWithAccessAsync_WhenUserCanManageCollections_Success(
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<CollectionDetails> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
foreach (var c in collections)
|
||||||
|
{
|
||||||
|
c.Manage = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
organization.Type = OrganizationUserType.User;
|
||||||
|
organization.LimitCollectionCreationDeletion = false;
|
||||||
|
organization.Permissions = new Permissions();
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
sutProvider.GetDependency<ICollectionRepository>().GetManyByUserIdAsync(actingUserId).Returns(collections);
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.ReadWithAccess },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData, CollectionCustomization]
|
||||||
|
public async Task CanReadWithAccessAsync_WhenUserCanNotManageCollections_Success(
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<CollectionDetails> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
foreach (var c in collections)
|
||||||
|
{
|
||||||
|
c.Manage = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
organization.Type = OrganizationUserType.User;
|
||||||
|
organization.LimitCollectionCreationDeletion = false;
|
||||||
|
organization.Permissions = new Permissions();
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
sutProvider.GetDependency<ICollectionRepository>().GetManyByUserIdAsync(actingUserId).Returns(collections);
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.ReadWithAccess },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, CollectionCustomization]
|
||||||
|
[BitAutoData(OrganizationUserType.User)]
|
||||||
|
[BitAutoData(OrganizationUserType.Custom)]
|
||||||
|
public async Task CanReadWithAccessAsync_WhenMissingPermissions_NoSuccess(
|
||||||
|
OrganizationUserType userType,
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<Collection> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = userType;
|
||||||
|
organization.LimitCollectionCreationDeletion = true;
|
||||||
|
organization.Permissions = new Permissions
|
||||||
|
{
|
||||||
|
EditAnyCollection = false,
|
||||||
|
DeleteAnyCollection = false,
|
||||||
|
ManageGroups = false,
|
||||||
|
ManageUsers = false
|
||||||
|
};
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.ReadWithAccess },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData, CollectionCustomization]
|
||||||
|
public async Task CanReadWithAccessAsync_WhenMissingOrgAccess_NoSuccess(
|
||||||
|
Guid userId,
|
||||||
|
ICollection<Collection> collections,
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider)
|
||||||
|
{
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(Arg.Any<Guid>()).Returns((CurrentContextOrganization)null);
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.ReadWithAccess },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections
|
||||||
|
);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, CollectionCustomization]
|
||||||
|
[BitAutoData(OrganizationUserType.Admin)]
|
||||||
|
[BitAutoData(OrganizationUserType.Owner)]
|
||||||
|
public async Task CanUpdateCollection_WhenAdminOrOwner_Success(
|
||||||
|
OrganizationUserType userType,
|
||||||
|
Guid userId, SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<Collection> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
organization.Type = userType;
|
||||||
|
organization.LimitCollectionCreationDeletion = true;
|
||||||
|
organization.Permissions = new Permissions();
|
||||||
|
|
||||||
|
var operationsToTest = new[]
|
||||||
|
{
|
||||||
|
BulkCollectionOperations.Update, BulkCollectionOperations.ModifyAccess
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var op in operationsToTest)
|
||||||
|
{
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { op },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
|
||||||
|
// Recreate the SUT to reset the mocks/dependencies between tests
|
||||||
|
sutProvider.Recreate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData, CollectionCustomization]
|
||||||
|
public async Task CanUpdateCollection_WithEditAnyCollectionPermission_Success(
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<Collection> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = OrganizationUserType.Custom;
|
||||||
|
organization.Permissions = new Permissions
|
||||||
|
{
|
||||||
|
EditAnyCollection = true
|
||||||
|
};
|
||||||
|
|
||||||
|
var operationsToTest = new[]
|
||||||
|
{
|
||||||
|
BulkCollectionOperations.Update, BulkCollectionOperations.ModifyAccess
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var op in operationsToTest)
|
||||||
|
{
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { op },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
|
||||||
|
// Recreate the SUT to reset the mocks/dependencies between tests
|
||||||
|
sutProvider.Recreate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData, CollectionCustomization]
|
||||||
|
public async Task CanUpdateCollection_WithManageCollectionPermission_Success(
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<CollectionDetails> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = OrganizationUserType.User;
|
||||||
|
organization.Permissions = new Permissions();
|
||||||
|
|
||||||
|
foreach (var c in collections)
|
||||||
|
{
|
||||||
|
c.Manage = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
var operationsToTest = new[]
|
||||||
|
{
|
||||||
|
BulkCollectionOperations.Update, BulkCollectionOperations.ModifyAccess
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var op in operationsToTest)
|
||||||
|
{
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
sutProvider.GetDependency<ICollectionRepository>().GetManyByUserIdAsync(actingUserId).Returns(collections);
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { op },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
|
||||||
|
// Recreate the SUT to reset the mocks/dependencies between tests
|
||||||
|
sutProvider.Recreate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, CollectionCustomization]
|
||||||
|
[BitAutoData(OrganizationUserType.User)]
|
||||||
|
[BitAutoData(OrganizationUserType.Custom)]
|
||||||
|
public async Task CanUpdateCollection_WhenMissingPermissions_NoSuccess(
|
||||||
|
OrganizationUserType userType,
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<CollectionDetails> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = userType;
|
||||||
|
organization.LimitCollectionCreationDeletion = false;
|
||||||
|
organization.Permissions = new Permissions
|
||||||
|
{
|
||||||
|
EditAnyCollection = false,
|
||||||
|
DeleteAnyCollection = false,
|
||||||
|
ManageGroups = false,
|
||||||
|
ManageUsers = false
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var collectionDetail in collections)
|
||||||
|
{
|
||||||
|
collectionDetail.Manage = true;
|
||||||
|
}
|
||||||
|
// Simulate one collection missing the manage permission
|
||||||
|
collections.First().Manage = false;
|
||||||
|
|
||||||
|
var operationsToTest = new[]
|
||||||
|
{
|
||||||
|
BulkCollectionOperations.Update, BulkCollectionOperations.ModifyAccess
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var op in operationsToTest)
|
||||||
|
{
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { op },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
|
||||||
|
// Recreate the SUT to reset the mocks/dependencies between tests
|
||||||
|
sutProvider.Recreate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData, CollectionCustomization]
|
||||||
|
public async Task CanUpdateCollection_WhenMissingOrgAccess_NoSuccess(
|
||||||
|
Guid userId,
|
||||||
|
ICollection<Collection> collections,
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider)
|
||||||
|
{
|
||||||
|
var operationsToTest = new[]
|
||||||
|
{
|
||||||
|
BulkCollectionOperations.Update, BulkCollectionOperations.ModifyAccess
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var op in operationsToTest)
|
||||||
|
{
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(Arg.Any<Guid>()).Returns((CurrentContextOrganization)null);
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { op },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections
|
||||||
|
);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
|
||||||
|
// Recreate the SUT to reset the mocks/dependencies between tests
|
||||||
|
sutProvider.Recreate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, CollectionCustomization]
|
||||||
|
[BitAutoData(OrganizationUserType.Admin)]
|
||||||
|
[BitAutoData(OrganizationUserType.Owner)]
|
||||||
|
public async Task CanDeleteAsync_WhenAdminOrOwner_Success(
|
||||||
|
OrganizationUserType userType,
|
||||||
|
Guid userId, SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<Collection> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
organization.Type = userType;
|
||||||
|
organization.LimitCollectionCreationDeletion = true;
|
||||||
|
organization.Permissions = new Permissions();
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.Delete },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData, CollectionCustomization]
|
||||||
|
public async Task CanDeleteAsync_WithDeleteAnyCollectionPermission_Success(
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<Collection> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = OrganizationUserType.Custom;
|
||||||
|
organization.LimitCollectionCreationDeletion = false;
|
||||||
|
organization.Permissions = new Permissions
|
||||||
|
{
|
||||||
|
DeleteAnyCollection = true
|
||||||
|
};
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.Delete },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData, CollectionCustomization]
|
||||||
|
public async Task CanDeleteAsync_WithManageCollectionPermission_Success(
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<CollectionDetails> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = OrganizationUserType.User;
|
||||||
|
organization.Permissions = new Permissions();
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
sutProvider.GetDependency<ICollectionRepository>().GetManyByUserIdAsync(actingUserId).Returns(collections);
|
||||||
|
|
||||||
|
foreach (var c in collections)
|
||||||
|
{
|
||||||
|
c.Manage = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.Delete },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, CollectionCustomization]
|
||||||
|
[BitAutoData(OrganizationUserType.User)]
|
||||||
|
[BitAutoData(OrganizationUserType.Custom)]
|
||||||
|
public async Task CanDeleteAsync_WhenMissingPermissions_NoSuccess(
|
||||||
|
OrganizationUserType userType,
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<Collection> collections,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = userType;
|
||||||
|
organization.LimitCollectionCreationDeletion = true;
|
||||||
|
organization.Permissions = new Permissions
|
||||||
|
{
|
||||||
|
EditAnyCollection = false,
|
||||||
|
DeleteAnyCollection = false,
|
||||||
|
ManageGroups = false,
|
||||||
|
ManageUsers = false
|
||||||
|
};
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.Delete },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData, CollectionCustomization]
|
||||||
|
public async Task CanDeleteAsync_WhenMissingOrgAccess_NoSuccess(
|
||||||
|
Guid userId,
|
||||||
|
ICollection<Collection> collections,
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider)
|
||||||
|
{
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.Delete },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections
|
||||||
|
);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(Arg.Any<Guid>()).Returns((CurrentContextOrganization)null);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData, CollectionCustomization]
|
||||||
|
public async Task HandleRequirementAsync_MissingUserId_Failure(
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<Collection> collections)
|
||||||
|
{
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.Create },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections
|
||||||
|
);
|
||||||
|
|
||||||
|
// Simulate missing user id
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns((Guid?)null);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
Assert.True(context.HasFailed);
|
||||||
|
sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData, CollectionCustomization]
|
||||||
|
public async Task HandleRequirementAsync_TargetCollectionsMultipleOrgs_Exception(
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
IList<Collection> collections)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
// Simulate a collection in a different organization
|
||||||
|
collections.First().OrganizationId = Guid.NewGuid();
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { BulkCollectionOperations.Create },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections
|
||||||
|
);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
|
||||||
|
var exception = await Assert.ThrowsAsync<BadRequestException>(() => sutProvider.Sut.HandleAsync(context));
|
||||||
|
Assert.Equal("Requested collections must belong to the same organization.", exception.Message);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().DidNotReceiveWithAnyArgs().GetOrganization(default);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData, CollectionCustomization]
|
||||||
|
public async Task HandleRequirementAsync_Provider_Success(
|
||||||
|
SutProvider<BulkCollectionAuthorizationHandler> sutProvider,
|
||||||
|
ICollection<Collection> collections)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
var orgId = collections.First().OrganizationId;
|
||||||
|
|
||||||
|
var operationsToTest = new[]
|
||||||
|
{
|
||||||
|
BulkCollectionOperations.Create,
|
||||||
|
BulkCollectionOperations.Read,
|
||||||
|
BulkCollectionOperations.ReadAccess,
|
||||||
|
BulkCollectionOperations.Update,
|
||||||
|
BulkCollectionOperations.ModifyAccess,
|
||||||
|
BulkCollectionOperations.Delete,
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var op in operationsToTest)
|
||||||
|
{
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(orgId).Returns((CurrentContextOrganization)null);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().ProviderUserForOrgAsync(Arg.Any<Guid>()).Returns(true);
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { op },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
collections
|
||||||
|
);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
await sutProvider.GetDependency<ICurrentContext>().Received().ProviderUserForOrgAsync(orgId);
|
||||||
|
|
||||||
|
// Recreate the SUT to reset the mocks/dependencies between tests
|
||||||
|
sutProvider.Recreate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -2,13 +2,9 @@
|
|||||||
using Bit.Api.Vault.AuthorizationHandlers.Collections;
|
using Bit.Api.Vault.AuthorizationHandlers.Collections;
|
||||||
using Bit.Core;
|
using Bit.Core;
|
||||||
using Bit.Core.Context;
|
using Bit.Core.Context;
|
||||||
using Bit.Core.Entities;
|
|
||||||
using Bit.Core.Enums;
|
using Bit.Core.Enums;
|
||||||
using Bit.Core.Exceptions;
|
|
||||||
using Bit.Core.Models.Data;
|
using Bit.Core.Models.Data;
|
||||||
using Bit.Core.Repositories;
|
|
||||||
using Bit.Core.Test.AutoFixture;
|
using Bit.Core.Test.AutoFixture;
|
||||||
using Bit.Core.Test.Vault.AutoFixture;
|
|
||||||
using Bit.Test.Common.AutoFixture;
|
using Bit.Test.Common.AutoFixture;
|
||||||
using Bit.Test.Common.AutoFixture.Attributes;
|
using Bit.Test.Common.AutoFixture.Attributes;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
@ -21,63 +17,80 @@ namespace Bit.Api.Test.Vault.AuthorizationHandlers;
|
|||||||
[FeatureServiceCustomize(FeatureFlagKeys.FlexibleCollections)]
|
[FeatureServiceCustomize(FeatureFlagKeys.FlexibleCollections)]
|
||||||
public class CollectionAuthorizationHandlerTests
|
public class CollectionAuthorizationHandlerTests
|
||||||
{
|
{
|
||||||
[Theory, CollectionCustomization]
|
[Theory]
|
||||||
[BitAutoData(OrganizationUserType.User, false, true)]
|
[BitAutoData(OrganizationUserType.Admin)]
|
||||||
[BitAutoData(OrganizationUserType.Admin, false, false)]
|
[BitAutoData(OrganizationUserType.Owner)]
|
||||||
[BitAutoData(OrganizationUserType.Owner, false, false)]
|
public async Task CanReadAllAsync_WhenAdminOrOwner_Success(
|
||||||
[BitAutoData(OrganizationUserType.Custom, true, false)]
|
OrganizationUserType userType,
|
||||||
[BitAutoData(OrganizationUserType.Owner, true, true)]
|
Guid userId, SutProvider<CollectionAuthorizationHandler> sutProvider,
|
||||||
public async Task CanManageCollectionAccessAsync_Success(
|
CurrentContextOrganization organization)
|
||||||
OrganizationUserType userType, bool editAnyCollection, bool manageCollections,
|
{
|
||||||
|
organization.Type = userType;
|
||||||
|
organization.Permissions = new Permissions();
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { CollectionOperations.ReadAll(organization.Id) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData]
|
||||||
|
public async Task CanReadAllAsync_WhenProviderUser_Success(
|
||||||
|
Guid userId,
|
||||||
|
SutProvider<CollectionAuthorizationHandler> sutProvider, CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
organization.Type = OrganizationUserType.User;
|
||||||
|
organization.Permissions = new Permissions();
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { CollectionOperations.ReadAll(organization.Id) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>()
|
||||||
|
.UserId
|
||||||
|
.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>()
|
||||||
|
.ProviderUserForOrgAsync(organization.Id)
|
||||||
|
.Returns(true);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[BitAutoData(true, false, false, false)]
|
||||||
|
[BitAutoData(false, true, false, false)]
|
||||||
|
[BitAutoData(false, false, true, false)]
|
||||||
|
[BitAutoData(false, false, false, true)]
|
||||||
|
public async Task CanReadAllAsync_WhenCustomUserWithRequiredPermissions_Success(
|
||||||
|
bool editAnyCollection, bool deleteAnyCollection, bool accessImportExport, bool manageGroups,
|
||||||
SutProvider<CollectionAuthorizationHandler> sutProvider,
|
SutProvider<CollectionAuthorizationHandler> sutProvider,
|
||||||
ICollection<Collection> collections,
|
|
||||||
ICollection<CollectionDetails> collectionDetails,
|
|
||||||
CurrentContextOrganization organization)
|
CurrentContextOrganization organization)
|
||||||
{
|
{
|
||||||
var actingUserId = Guid.NewGuid();
|
var actingUserId = Guid.NewGuid();
|
||||||
foreach (var collectionDetail in collectionDetails)
|
|
||||||
|
organization.Type = OrganizationUserType.Custom;
|
||||||
|
organization.Permissions = new Permissions
|
||||||
{
|
{
|
||||||
collectionDetail.Manage = manageCollections;
|
EditAnyCollection = editAnyCollection,
|
||||||
}
|
DeleteAnyCollection = deleteAnyCollection,
|
||||||
|
AccessImportExport = accessImportExport,
|
||||||
organization.Type = userType;
|
ManageGroups = manageGroups
|
||||||
organization.Permissions.EditAnyCollection = editAnyCollection;
|
};
|
||||||
|
|
||||||
var context = new AuthorizationHandlerContext(
|
var context = new AuthorizationHandlerContext(
|
||||||
new[] { CollectionOperations.ModifyAccess },
|
new[] { CollectionOperations.ReadAll(organization.Id) },
|
||||||
new ClaimsPrincipal(),
|
new ClaimsPrincipal(),
|
||||||
collections);
|
null);
|
||||||
|
|
||||||
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
|
||||||
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
|
||||||
sutProvider.GetDependency<ICollectionRepository>().GetManyByUserIdAsync(actingUserId).Returns(collectionDetails);
|
|
||||||
|
|
||||||
await sutProvider.Sut.HandleAsync(context);
|
|
||||||
|
|
||||||
Assert.True(context.HasSucceeded);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory, CollectionCustomization]
|
|
||||||
[BitAutoData(OrganizationUserType.User, false, false)]
|
|
||||||
[BitAutoData(OrganizationUserType.Admin, false, true)]
|
|
||||||
[BitAutoData(OrganizationUserType.Owner, false, true)]
|
|
||||||
[BitAutoData(OrganizationUserType.Custom, true, true)]
|
|
||||||
public async Task CanCreateAsync_Success(
|
|
||||||
OrganizationUserType userType, bool createNewCollection, bool limitCollectionCreateDelete,
|
|
||||||
SutProvider<CollectionAuthorizationHandler> sutProvider,
|
|
||||||
ICollection<Collection> collections,
|
|
||||||
CurrentContextOrganization organization)
|
|
||||||
{
|
|
||||||
var actingUserId = Guid.NewGuid();
|
|
||||||
|
|
||||||
organization.Type = userType;
|
|
||||||
organization.Permissions.CreateNewCollections = createNewCollection;
|
|
||||||
organization.LimitCollectionCreationDeletion = limitCollectionCreateDelete;
|
|
||||||
|
|
||||||
var context = new AuthorizationHandlerContext(
|
|
||||||
new[] { CollectionOperations.Create },
|
|
||||||
new ClaimsPrincipal(),
|
|
||||||
collections);
|
|
||||||
|
|
||||||
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
@ -87,51 +100,177 @@ public class CollectionAuthorizationHandlerTests
|
|||||||
Assert.True(context.HasSucceeded);
|
Assert.True(context.HasSucceeded);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory, CollectionCustomization]
|
[Theory]
|
||||||
[BitAutoData(OrganizationUserType.User, false, false, true)]
|
[BitAutoData(OrganizationUserType.User)]
|
||||||
[BitAutoData(OrganizationUserType.Admin, false, true, false)]
|
[BitAutoData(OrganizationUserType.Custom)]
|
||||||
[BitAutoData(OrganizationUserType.Owner, false, true, false)]
|
public async Task CanReadAllAsync_WhenMissingPermissions_NoSuccess(
|
||||||
[BitAutoData(OrganizationUserType.Custom, true, true, false)]
|
OrganizationUserType userType,
|
||||||
public async Task CanDeleteAsync_Success(
|
|
||||||
OrganizationUserType userType, bool deleteAnyCollection, bool limitCollectionCreateDelete, bool manageCollections,
|
|
||||||
SutProvider<CollectionAuthorizationHandler> sutProvider,
|
SutProvider<CollectionAuthorizationHandler> sutProvider,
|
||||||
ICollection<Collection> collections,
|
|
||||||
ICollection<CollectionDetails> collectionDetails,
|
|
||||||
CurrentContextOrganization organization)
|
CurrentContextOrganization organization)
|
||||||
{
|
{
|
||||||
var actingUserId = Guid.NewGuid();
|
var actingUserId = Guid.NewGuid();
|
||||||
foreach (var collectionDetail in collectionDetails)
|
|
||||||
|
organization.Type = userType;
|
||||||
|
organization.Permissions = new Permissions
|
||||||
{
|
{
|
||||||
collectionDetail.Manage = manageCollections;
|
EditAnyCollection = false,
|
||||||
}
|
DeleteAnyCollection = false,
|
||||||
|
AccessImportExport = false
|
||||||
organization.Type = userType;
|
};
|
||||||
organization.Permissions.DeleteAnyCollection = deleteAnyCollection;
|
|
||||||
organization.LimitCollectionCreationDeletion = limitCollectionCreateDelete;
|
|
||||||
|
|
||||||
var context = new AuthorizationHandlerContext(
|
var context = new AuthorizationHandlerContext(
|
||||||
new[] { CollectionOperations.Delete },
|
new[] { CollectionOperations.ReadAll(organization.Id) },
|
||||||
new ClaimsPrincipal(),
|
new ClaimsPrincipal(),
|
||||||
collections);
|
null);
|
||||||
|
|
||||||
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
sutProvider.GetDependency<ICollectionRepository>().GetManyByUserIdAsync(actingUserId).Returns(collectionDetails);
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[BitAutoData(OrganizationUserType.Admin)]
|
||||||
|
[BitAutoData(OrganizationUserType.Owner)]
|
||||||
|
public async Task CanReadAllWithAccessAsync_WhenAdminOrOwner_Success(
|
||||||
|
OrganizationUserType userType,
|
||||||
|
Guid userId, SutProvider<CollectionAuthorizationHandler> sutProvider,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
organization.Type = userType;
|
||||||
|
organization.Permissions = new Permissions();
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { CollectionOperations.ReadAllWithAccess(organization.Id) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
await sutProvider.Sut.HandleAsync(context);
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
Assert.True(context.HasSucceeded);
|
Assert.True(context.HasSucceeded);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory, BitAutoData, CollectionCustomization]
|
[Theory, BitAutoData]
|
||||||
|
public async Task CanReadAllWithAccessAsync_WhenProviderUser_Success(
|
||||||
|
Guid userId,
|
||||||
|
SutProvider<CollectionAuthorizationHandler> sutProvider, CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
organization.Type = OrganizationUserType.User;
|
||||||
|
organization.Permissions = new Permissions();
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { CollectionOperations.ReadAllWithAccess(organization.Id) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>()
|
||||||
|
.UserId
|
||||||
|
.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>()
|
||||||
|
.ProviderUserForOrgAsync(organization.Id)
|
||||||
|
.Returns(true);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[BitAutoData(true, false, false)]
|
||||||
|
[BitAutoData(false, true, false)]
|
||||||
|
[BitAutoData(false, false, true)]
|
||||||
|
public async Task CanReadAllWithAccessAsync_WhenCustomUserWithRequiredPermissions_Success(
|
||||||
|
bool editAnyCollection, bool deleteAnyCollection, bool manageUsers,
|
||||||
|
SutProvider<CollectionAuthorizationHandler> sutProvider,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = OrganizationUserType.Custom;
|
||||||
|
organization.Permissions = new Permissions
|
||||||
|
{
|
||||||
|
EditAnyCollection = editAnyCollection,
|
||||||
|
DeleteAnyCollection = deleteAnyCollection,
|
||||||
|
ManageUsers = manageUsers
|
||||||
|
};
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { CollectionOperations.ReadAllWithAccess(organization.Id) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[BitAutoData(OrganizationUserType.User)]
|
||||||
|
[BitAutoData(OrganizationUserType.Custom)]
|
||||||
|
public async Task CanReadAllWithAccessAsync_WhenMissingPermissions_NoSuccess(
|
||||||
|
OrganizationUserType userType,
|
||||||
|
SutProvider<CollectionAuthorizationHandler> sutProvider,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = userType;
|
||||||
|
organization.Permissions = new Permissions
|
||||||
|
{
|
||||||
|
EditAnyCollection = false,
|
||||||
|
DeleteAnyCollection = false,
|
||||||
|
AccessImportExport = false
|
||||||
|
};
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { CollectionOperations.ReadAllWithAccess(organization.Id) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData]
|
||||||
|
public async Task HandleRequirementAsync_WhenMissingOrgAccess_NoSuccess(
|
||||||
|
Guid userId,
|
||||||
|
Guid organizationId,
|
||||||
|
SutProvider<CollectionAuthorizationHandler> sutProvider)
|
||||||
|
{
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { CollectionOperations.ReadAll(organizationId) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null
|
||||||
|
);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(Arg.Any<Guid>()).Returns((CurrentContextOrganization)null);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData]
|
||||||
public async Task HandleRequirementAsync_MissingUserId_Failure(
|
public async Task HandleRequirementAsync_MissingUserId_Failure(
|
||||||
SutProvider<CollectionAuthorizationHandler> sutProvider,
|
Guid organizationId,
|
||||||
ICollection<Collection> collections)
|
SutProvider<CollectionAuthorizationHandler> sutProvider)
|
||||||
{
|
{
|
||||||
var context = new AuthorizationHandlerContext(
|
var context = new AuthorizationHandlerContext(
|
||||||
new[] { CollectionOperations.Create },
|
new[] { CollectionOperations.ReadAll(organizationId) },
|
||||||
new ClaimsPrincipal(),
|
new ClaimsPrincipal(),
|
||||||
collections
|
null
|
||||||
);
|
);
|
||||||
|
|
||||||
// Simulate missing user id
|
// Simulate missing user id
|
||||||
@ -139,119 +278,22 @@ public class CollectionAuthorizationHandlerTests
|
|||||||
|
|
||||||
await sutProvider.Sut.HandleAsync(context);
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
Assert.True(context.HasFailed);
|
Assert.True(context.HasFailed);
|
||||||
sutProvider.GetDependency<ICollectionRepository>().DidNotReceiveWithAnyArgs();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory, BitAutoData, CollectionCustomization]
|
[Theory, BitAutoData]
|
||||||
public async Task HandleRequirementAsync_TargetCollectionsMultipleOrgs_Exception(
|
public async Task HandleRequirementAsync_NoSpecifiedOrgId_Failure(
|
||||||
SutProvider<CollectionAuthorizationHandler> sutProvider,
|
SutProvider<CollectionAuthorizationHandler> sutProvider)
|
||||||
IList<Collection> collections)
|
|
||||||
{
|
{
|
||||||
var actingUserId = Guid.NewGuid();
|
|
||||||
|
|
||||||
// Simulate a collection in a different organization
|
|
||||||
collections.First().OrganizationId = Guid.NewGuid();
|
|
||||||
|
|
||||||
var context = new AuthorizationHandlerContext(
|
var context = new AuthorizationHandlerContext(
|
||||||
new[] { CollectionOperations.Create },
|
new[] { CollectionOperations.ReadAll(default) },
|
||||||
new ClaimsPrincipal(),
|
new ClaimsPrincipal(),
|
||||||
collections
|
null
|
||||||
);
|
);
|
||||||
|
|
||||||
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(new Guid());
|
||||||
|
|
||||||
var exception = await Assert.ThrowsAsync<BadRequestException>(() => sutProvider.Sut.HandleAsync(context));
|
|
||||||
Assert.Equal("Requested collections must belong to the same organization.", exception.Message);
|
|
||||||
sutProvider.GetDependency<ICurrentContext>().DidNotReceiveWithAnyArgs().GetOrganization(default);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory, BitAutoData, CollectionCustomization]
|
|
||||||
public async Task HandleRequirementAsync_MissingOrg_NoSuccess(
|
|
||||||
SutProvider<CollectionAuthorizationHandler> sutProvider,
|
|
||||||
ICollection<Collection> collections)
|
|
||||||
{
|
|
||||||
var actingUserId = Guid.NewGuid();
|
|
||||||
|
|
||||||
var context = new AuthorizationHandlerContext(
|
|
||||||
new[] { CollectionOperations.Create },
|
|
||||||
new ClaimsPrincipal(),
|
|
||||||
collections
|
|
||||||
);
|
|
||||||
|
|
||||||
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
|
||||||
sutProvider.GetDependency<ICurrentContext>().GetOrganization(Arg.Any<Guid>()).Returns((CurrentContextOrganization)null);
|
|
||||||
|
|
||||||
await sutProvider.Sut.HandleAsync(context);
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
Assert.False(context.HasSucceeded);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory, BitAutoData, CollectionCustomization]
|
Assert.True(context.HasFailed);
|
||||||
public async Task HandleRequirementAsync_Provider_Success(
|
|
||||||
SutProvider<CollectionAuthorizationHandler> sutProvider,
|
|
||||||
ICollection<Collection> collections)
|
|
||||||
{
|
|
||||||
var operationsToTest = new[]
|
|
||||||
{
|
|
||||||
CollectionOperations.Create, CollectionOperations.Delete, CollectionOperations.ModifyAccess
|
|
||||||
};
|
|
||||||
|
|
||||||
foreach (var op in operationsToTest)
|
|
||||||
{
|
|
||||||
var actingUserId = Guid.NewGuid();
|
|
||||||
var context = new AuthorizationHandlerContext(
|
|
||||||
new[] { op },
|
|
||||||
new ClaimsPrincipal(),
|
|
||||||
collections
|
|
||||||
);
|
|
||||||
var orgId = collections.First().OrganizationId;
|
|
||||||
|
|
||||||
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
|
||||||
sutProvider.GetDependency<ICurrentContext>().GetOrganization(orgId).Returns((CurrentContextOrganization)null);
|
|
||||||
sutProvider.GetDependency<ICurrentContext>().ProviderUserForOrgAsync(Arg.Any<Guid>()).Returns(true);
|
|
||||||
|
|
||||||
await sutProvider.Sut.HandleAsync(context);
|
|
||||||
Assert.True(context.HasSucceeded);
|
|
||||||
await sutProvider.GetDependency<ICurrentContext>().Received().ProviderUserForOrgAsync(orgId);
|
|
||||||
|
|
||||||
// Recreate the SUT to reset the mocks/dependencies between tests
|
|
||||||
sutProvider.Recreate();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory, BitAutoData, CollectionCustomization]
|
|
||||||
public async Task CanManageCollectionAccessAsync_MissingManageCollectionPermission_NoSuccess(
|
|
||||||
SutProvider<CollectionAuthorizationHandler> sutProvider,
|
|
||||||
ICollection<Collection> collections,
|
|
||||||
ICollection<CollectionDetails> collectionDetails,
|
|
||||||
CurrentContextOrganization organization)
|
|
||||||
{
|
|
||||||
var actingUserId = Guid.NewGuid();
|
|
||||||
|
|
||||||
foreach (var collectionDetail in collectionDetails)
|
|
||||||
{
|
|
||||||
collectionDetail.Manage = true;
|
|
||||||
}
|
|
||||||
// Simulate one collection missing the manage permission
|
|
||||||
collectionDetails.First().Manage = false;
|
|
||||||
|
|
||||||
// Ensure the user is not an owner/admin and does not have edit any collection permission
|
|
||||||
organization.Type = OrganizationUserType.User;
|
|
||||||
organization.Permissions.EditAnyCollection = false;
|
|
||||||
|
|
||||||
var context = new AuthorizationHandlerContext(
|
|
||||||
new[] { CollectionOperations.ModifyAccess },
|
|
||||||
new ClaimsPrincipal(),
|
|
||||||
collections
|
|
||||||
);
|
|
||||||
|
|
||||||
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
|
||||||
sutProvider.GetDependency<ICurrentContext>().GetOrganization(Arg.Any<Guid>()).Returns(organization);
|
|
||||||
sutProvider.GetDependency<ICollectionRepository>().GetManyByUserIdAsync(actingUserId).Returns(collectionDetails);
|
|
||||||
|
|
||||||
await sutProvider.Sut.HandleAsync(context);
|
|
||||||
Assert.False(context.HasSucceeded);
|
|
||||||
sutProvider.GetDependency<ICurrentContext>().ReceivedWithAnyArgs().GetOrganization(default);
|
|
||||||
await sutProvider.GetDependency<ICollectionRepository>().ReceivedWithAnyArgs()
|
|
||||||
.GetManyByUserIdAsync(default);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,197 @@
|
|||||||
|
using System.Security.Claims;
|
||||||
|
using Bit.Api.Vault.AuthorizationHandlers.Groups;
|
||||||
|
using Bit.Core;
|
||||||
|
using Bit.Core.Context;
|
||||||
|
using Bit.Core.Enums;
|
||||||
|
using Bit.Core.Models.Data;
|
||||||
|
using Bit.Core.Test.AutoFixture;
|
||||||
|
using Bit.Test.Common.AutoFixture;
|
||||||
|
using Bit.Test.Common.AutoFixture.Attributes;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using NSubstitute;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace Bit.Api.Test.Vault.AuthorizationHandlers;
|
||||||
|
|
||||||
|
[SutProviderCustomize]
|
||||||
|
[FeatureServiceCustomize(FeatureFlagKeys.FlexibleCollections)]
|
||||||
|
public class GroupAuthorizationHandlerTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[BitAutoData(OrganizationUserType.Admin)]
|
||||||
|
[BitAutoData(OrganizationUserType.Owner)]
|
||||||
|
public async Task CanReadAllAsync_WhenAdminOrOwner_Success(
|
||||||
|
OrganizationUserType userType,
|
||||||
|
Guid userId, SutProvider<GroupAuthorizationHandler> sutProvider,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
organization.Type = userType;
|
||||||
|
organization.LimitCollectionCreationDeletion = true;
|
||||||
|
organization.Permissions = new Permissions();
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { GroupOperations.ReadAll(organization.Id) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData]
|
||||||
|
public async Task CanReadAllAsync_WithProviderUser_Success(
|
||||||
|
Guid userId,
|
||||||
|
SutProvider<GroupAuthorizationHandler> sutProvider, CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
organization.Type = OrganizationUserType.User;
|
||||||
|
organization.LimitCollectionCreationDeletion = true;
|
||||||
|
organization.Permissions = new Permissions();
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { GroupOperations.ReadAll(organization.Id) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>()
|
||||||
|
.UserId
|
||||||
|
.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>()
|
||||||
|
.ProviderUserForOrgAsync(organization.Id)
|
||||||
|
.Returns(true);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[BitAutoData(true, false, false, false, true)]
|
||||||
|
[BitAutoData(false, true, false, false, true)]
|
||||||
|
[BitAutoData(false, false, true, false, true)]
|
||||||
|
[BitAutoData(false, false, false, true, true)]
|
||||||
|
[BitAutoData(false, false, false, false, false)]
|
||||||
|
public async Task CanReadAllAsync_WhenCustomUserWithRequiredPermissions_Success(
|
||||||
|
bool editAnyCollection, bool deleteAnyCollection, bool manageGroups,
|
||||||
|
bool manageUsers, bool limitCollectionCreationDeletion,
|
||||||
|
SutProvider<GroupAuthorizationHandler> sutProvider,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = OrganizationUserType.Custom;
|
||||||
|
organization.LimitCollectionCreationDeletion = limitCollectionCreationDeletion;
|
||||||
|
organization.Permissions = new Permissions
|
||||||
|
{
|
||||||
|
EditAnyCollection = editAnyCollection,
|
||||||
|
DeleteAnyCollection = deleteAnyCollection,
|
||||||
|
ManageGroups = manageGroups,
|
||||||
|
ManageUsers = manageUsers
|
||||||
|
};
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { GroupOperations.ReadAll(organization.Id) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[BitAutoData(OrganizationUserType.User)]
|
||||||
|
[BitAutoData(OrganizationUserType.Custom)]
|
||||||
|
public async Task CanReadAllAsync_WhenMissingPermissions_NoSuccess(
|
||||||
|
OrganizationUserType userType,
|
||||||
|
SutProvider<GroupAuthorizationHandler> sutProvider,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = userType;
|
||||||
|
organization.LimitCollectionCreationDeletion = true;
|
||||||
|
organization.Permissions = new Permissions
|
||||||
|
{
|
||||||
|
EditAnyCollection = false,
|
||||||
|
DeleteAnyCollection = false,
|
||||||
|
ManageGroups = false,
|
||||||
|
ManageUsers = false,
|
||||||
|
AccessImportExport = false
|
||||||
|
};
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { GroupOperations.ReadAll(organization.Id) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData]
|
||||||
|
public async Task CanReadAllAsync_WhenMissingOrgAccess_NoSuccess(
|
||||||
|
Guid userId,
|
||||||
|
Guid organizationId,
|
||||||
|
SutProvider<GroupAuthorizationHandler> sutProvider)
|
||||||
|
{
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { GroupOperations.ReadAll(organizationId) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null
|
||||||
|
);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(Arg.Any<Guid>()).Returns((CurrentContextOrganization)null);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData]
|
||||||
|
public async Task HandleRequirementAsync_MissingUserId_Failure(
|
||||||
|
Guid organizationId,
|
||||||
|
SutProvider<GroupAuthorizationHandler> sutProvider)
|
||||||
|
{
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { GroupOperations.ReadAll(organizationId) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null
|
||||||
|
);
|
||||||
|
|
||||||
|
// Simulate missing user id
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns((Guid?)null);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
Assert.True(context.HasFailed);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData]
|
||||||
|
public async Task HandleRequirementAsync_NoSpecifiedOrgId_Failure(
|
||||||
|
SutProvider<GroupAuthorizationHandler> sutProvider)
|
||||||
|
{
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { GroupOperations.ReadAll(default) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null
|
||||||
|
);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(new Guid());
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
Assert.True(context.HasFailed);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,194 @@
|
|||||||
|
using System.Security.Claims;
|
||||||
|
using Bit.Api.Vault.AuthorizationHandlers.OrganizationUsers;
|
||||||
|
using Bit.Core;
|
||||||
|
using Bit.Core.Context;
|
||||||
|
using Bit.Core.Enums;
|
||||||
|
using Bit.Core.Models.Data;
|
||||||
|
using Bit.Core.Test.AutoFixture;
|
||||||
|
using Bit.Test.Common.AutoFixture;
|
||||||
|
using Bit.Test.Common.AutoFixture.Attributes;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using NSubstitute;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace Bit.Api.Test.Vault.AuthorizationHandlers;
|
||||||
|
|
||||||
|
[SutProviderCustomize]
|
||||||
|
[FeatureServiceCustomize(FeatureFlagKeys.FlexibleCollections)]
|
||||||
|
public class OrganizationUserAuthorizationHandlerTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[BitAutoData(OrganizationUserType.Admin)]
|
||||||
|
[BitAutoData(OrganizationUserType.Owner)]
|
||||||
|
public async Task CanReadAllAsync_WhenAdminOrOwner_Success(
|
||||||
|
OrganizationUserType userType,
|
||||||
|
Guid userId, SutProvider<OrganizationUserAuthorizationHandler> sutProvider,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
organization.Type = userType;
|
||||||
|
organization.LimitCollectionCreationDeletion = true;
|
||||||
|
organization.Permissions = new Permissions();
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { OrganizationUserOperations.ReadAll(organization.Id) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData]
|
||||||
|
public async Task CanReadAllAsync_WithProviderUser_Success(
|
||||||
|
Guid userId,
|
||||||
|
SutProvider<OrganizationUserAuthorizationHandler> sutProvider, CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
organization.Type = OrganizationUserType.User;
|
||||||
|
organization.LimitCollectionCreationDeletion = true;
|
||||||
|
organization.Permissions = new Permissions();
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { OrganizationUserOperations.ReadAll(organization.Id) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>()
|
||||||
|
.UserId
|
||||||
|
.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>()
|
||||||
|
.ProviderUserForOrgAsync(organization.Id)
|
||||||
|
.Returns(true);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[BitAutoData(true, false, false, false, true)]
|
||||||
|
[BitAutoData(false, true, false, false, true)]
|
||||||
|
[BitAutoData(false, false, true, false, true)]
|
||||||
|
[BitAutoData(false, false, false, true, true)]
|
||||||
|
[BitAutoData(false, false, false, false, false)]
|
||||||
|
public async Task CanReadAllAsync_WhenCustomUserWithRequiredPermissions_Success(
|
||||||
|
bool editAnyCollection, bool deleteAnyCollection, bool manageGroups,
|
||||||
|
bool manageUsers, bool limitCollectionCreationDeletion,
|
||||||
|
SutProvider<OrganizationUserAuthorizationHandler> sutProvider,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = OrganizationUserType.Custom;
|
||||||
|
organization.LimitCollectionCreationDeletion = limitCollectionCreationDeletion;
|
||||||
|
organization.Permissions = new Permissions
|
||||||
|
{
|
||||||
|
EditAnyCollection = editAnyCollection,
|
||||||
|
DeleteAnyCollection = deleteAnyCollection,
|
||||||
|
ManageGroups = manageGroups,
|
||||||
|
ManageUsers = manageUsers
|
||||||
|
};
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { OrganizationUserOperations.ReadAll(organization.Id) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[BitAutoData(OrganizationUserType.User)]
|
||||||
|
[BitAutoData(OrganizationUserType.Custom)]
|
||||||
|
public async Task CanReadAllAsync_WhenMissingPermissions_NoSuccess(
|
||||||
|
OrganizationUserType userType,
|
||||||
|
SutProvider<OrganizationUserAuthorizationHandler> sutProvider,
|
||||||
|
CurrentContextOrganization organization)
|
||||||
|
{
|
||||||
|
var actingUserId = Guid.NewGuid();
|
||||||
|
|
||||||
|
organization.Type = userType;
|
||||||
|
organization.LimitCollectionCreationDeletion = true;
|
||||||
|
organization.Permissions = new Permissions
|
||||||
|
{
|
||||||
|
EditAnyCollection = false,
|
||||||
|
DeleteAnyCollection = false,
|
||||||
|
ManageGroups = false,
|
||||||
|
ManageUsers = false
|
||||||
|
};
|
||||||
|
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { OrganizationUserOperations.ReadAll(organization.Id) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(actingUserId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organization.Id).Returns(organization);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData]
|
||||||
|
public async Task HandleRequirementAsync_WhenMissingOrgAccess_NoSuccess(
|
||||||
|
Guid userId,
|
||||||
|
Guid organizationId,
|
||||||
|
SutProvider<OrganizationUserAuthorizationHandler> sutProvider)
|
||||||
|
{
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { OrganizationUserOperations.ReadAll(organizationId) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null
|
||||||
|
);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().GetOrganization(Arg.Any<Guid>()).Returns((CurrentContextOrganization)null);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
Assert.False(context.HasSucceeded);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData]
|
||||||
|
public async Task HandleRequirementAsync_MissingUserId_Failure(
|
||||||
|
Guid organizationId,
|
||||||
|
SutProvider<OrganizationUserAuthorizationHandler> sutProvider)
|
||||||
|
{
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { OrganizationUserOperations.ReadAll(organizationId) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null
|
||||||
|
);
|
||||||
|
|
||||||
|
// Simulate missing user id
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns((Guid?)null);
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
Assert.True(context.HasFailed);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory, BitAutoData]
|
||||||
|
public async Task HandleRequirementAsync_NoSpecifiedOrgId_Failure(
|
||||||
|
SutProvider<OrganizationUserAuthorizationHandler> sutProvider)
|
||||||
|
{
|
||||||
|
var context = new AuthorizationHandlerContext(
|
||||||
|
new[] { OrganizationUserOperations.ReadAll(default) },
|
||||||
|
new ClaimsPrincipal(),
|
||||||
|
null
|
||||||
|
);
|
||||||
|
|
||||||
|
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(new Guid());
|
||||||
|
|
||||||
|
await sutProvider.Sut.HandleAsync(context);
|
||||||
|
|
||||||
|
Assert.True(context.HasFailed);
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user