1
0
mirror of https://github.com/bitwarden/server synced 2025-12-25 20:53:16 +00:00

[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
This commit is contained in:
Shane Melton
2023-08-30 14:13:58 -07:00
committed by GitHub
parent e87c20c7a1
commit 5dc3ca85c3
9 changed files with 497 additions and 1 deletions

View File

@@ -137,6 +137,9 @@ public class Startup
services.AddOrganizationSubscriptionServices();
services.AddCoreLocalizationServices();
// Authorization Handlers
services.AddAuthorizationHandlers();
//health check
if (!globalSettings.SelfHosted)
{

View File

@@ -1,7 +1,9 @@
using Bit.Core.IdentityServer;
using Bit.Api.Vault.AuthorizationHandlers;
using Bit.Core.IdentityServer;
using Bit.Core.Settings;
using Bit.Core.Utilities;
using Bit.SharedWeb.Health;
using Microsoft.AspNetCore.Authorization;
using Microsoft.OpenApi.Models;
namespace Bit.Api.Utilities;
@@ -115,4 +117,9 @@ public static class ServiceCollectionExtensions
}
});
}
public static void AddAuthorizationHandlers(this IServiceCollection services)
{
services.AddScoped<IAuthorizationHandler, CollectionAuthorizationHandler>();
}
}

View File

@@ -0,0 +1,90 @@
using Bit.Core.Context;
using Bit.Core.Entities;
using Bit.Core.Enums;
using Bit.Core.Exceptions;
using Bit.Core.Repositories;
using Bit.Core.Utilities;
using Microsoft.AspNetCore.Authorization;
namespace Bit.Api.Vault.AuthorizationHandlers;
public class CollectionAuthorizationHandler : BulkAuthorizationHandler<CollectionOperationRequirement, Collection>
{
private readonly ICurrentContext _currentContext;
private readonly ICollectionRepository _collectionRepository;
private readonly IOrganizationUserRepository _organizationUserRepository;
public CollectionAuthorizationHandler(ICurrentContext currentContext, ICollectionRepository collectionRepository, IOrganizationUserRepository organizationUserRepository)
{
_currentContext = currentContext;
_collectionRepository = collectionRepository;
_organizationUserRepository = organizationUserRepository;
}
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, CollectionOperationRequirement requirement,
ICollection<Collection> resources)
{
switch (requirement)
{
case not null when requirement == CollectionOperation.ModifyAccess:
await CanManageCollectionAccessAsync(context, requirement, resources);
break;
}
}
/// <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)
{
if (!_currentContext.UserId.HasValue)
{
context.Fail();
return;
}
var targetOrganizationId = targetCollections.First().OrganizationId;
// Ensure all target collections belong to the same organization
if (targetCollections.Any(tc => tc.OrganizationId != targetOrganizationId))
{
throw new BadRequestException("Requested collections must belong to the same organization.");
}
var org = (await _currentContext.OrganizationMembershipAsync(_organizationUserRepository, _currentContext.UserId.Value))
.FirstOrDefault(o => targetOrganizationId == o.Id);
// Acting user is not a member of the target organization, fail
if (org == null)
{
context.Fail();
return;
}
// Owners, Admins, Providers, and users with EditAnyCollection permission can always manage collection access
if (
org.Permissions is { EditAnyCollection: true } ||
org.Type is OrganizationUserType.Admin or OrganizationUserType.Owner ||
await _currentContext.ProviderUserForOrgAsync(org.Id))
{
context.Succeed(requirement);
return;
}
// List of collection Ids the acting user is allowed to manage
var manageableCollectionIds =
(await _collectionRepository.GetManyByUserIdAsync(_currentContext.UserId.Value))
.Where(c => c.Manage && c.OrganizationId == targetOrganizationId)
.Select(c => c.Id)
.ToHashSet();
// The acting user does not have permission to manage all target collections, fail
if (targetCollections.Any(tc => !manageableCollectionIds.Contains(tc.Id)))
{
context.Fail();
return;
}
context.Succeed(requirement);
}
}

View File

@@ -0,0 +1,15 @@
using Microsoft.AspNetCore.Authorization.Infrastructure;
namespace Bit.Api.Vault.AuthorizationHandlers;
public class CollectionOperationRequirement : OperationAuthorizationRequirement { }
public static class CollectionOperation
{
/// <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 CollectionOperationRequirement ModifyAccess = new() { Name = nameof(ModifyAccess) };
}

View File

@@ -0,0 +1,40 @@
using Microsoft.AspNetCore.Authorization;
namespace Bit.Core.Utilities;
/// <summary>
/// Allows a single authorization handler implementation to handle requirements for
/// both singular or bulk operations on single or multiple resources.
/// </summary>
/// <typeparam name="TRequirement">The type of the requirement to evaluate.</typeparam>
/// <typeparam name="TResource">The type of the resource(s) that will be evaluated.</typeparam>
public abstract class BulkAuthorizationHandler<TRequirement, TResource> : AuthorizationHandler<TRequirement>
where TRequirement : IAuthorizationRequirement
{
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement)
{
// Attempt to get the resource(s) from the context
var bulkResources = GetBulkResourceFromContext(context);
// No resources of the expected type were found in the context, nothing to evaluate
if (bulkResources == null)
{
return;
}
await HandleRequirementAsync(context, requirement, bulkResources);
}
private static ICollection<TResource> GetBulkResourceFromContext(AuthorizationHandlerContext context)
{
return context.Resource switch
{
TResource resource => new List<TResource> { resource },
IEnumerable<TResource> resources => resources.ToList(),
_ => null
};
}
protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement,
ICollection<TResource> resources);
}