1
0
mirror of https://github.com/bitwarden/server.git synced 2025-07-04 09:32:48 -05:00

[PM-14378] SecurityTask Authorization Handler (#5039)

* [PM-14378] Introduce GetCipherPermissionsForOrganization query for Dapper CipherRepository

* [PM-14378] Introduce GetCipherPermissionsForOrganization method for Entity Framework

* [PM-14378] Add integration tests for new repository method

* [PM-14378] Introduce IGetCipherPermissionsForUserQuery CQRS query

* [PM-14378] Introduce SecurityTaskOperationRequirement

* [PM-14378] Introduce SecurityTaskAuthorizationHandler.cs

* [PM-14378] Introduce SecurityTaskOrganizationAuthorizationHandler.cs

* [PM-14378] Register new authorization handlers

* [PM-14378] Formatting

* [PM-14378] Add unit tests for GetCipherPermissionsForUserQuery

* [PM-15378] Cleanup SecurityTaskAuthorizationHandler and add tests

* [PM-14378] Add tests for SecurityTaskOrganizationAuthorizationHandler

* [PM-14378] Formatting

* [PM-14378] Update date in migration file

* [PM-14378] Add missing awaits

* [PM-14378] Bump migration script date

* [PM-14378] Remove Unassigned property from OrganizationCipherPermission as it was making the query too complicated

* [PM-14378] Update sproc to use Union All to improve query performance

* [PM-14378] Bump migration script date
This commit is contained in:
Shane Melton
2025-01-09 12:14:24 -08:00
committed by GitHub
parent fd195e7cf3
commit a99f82dddd
18 changed files with 1669 additions and 0 deletions

View File

@ -0,0 +1,142 @@
using Bit.Core.Context;
using Bit.Core.Enums;
using Bit.Core.Vault.Entities;
using Bit.Core.Vault.Models.Data;
using Bit.Core.Vault.Queries;
using Microsoft.AspNetCore.Authorization;
namespace Bit.Core.Vault.Authorization.SecurityTasks;
public class SecurityTaskAuthorizationHandler : AuthorizationHandler<SecurityTaskOperationRequirement, SecurityTask>
{
private readonly ICurrentContext _currentContext;
private readonly IGetCipherPermissionsForUserQuery _getCipherPermissionsForUserQuery;
private readonly Dictionary<Guid, IDictionary<Guid, OrganizationCipherPermission>> _cipherPermissionCache = new();
public SecurityTaskAuthorizationHandler(ICurrentContext currentContext, IGetCipherPermissionsForUserQuery getCipherPermissionsForUserQuery)
{
_currentContext = currentContext;
_getCipherPermissionsForUserQuery = getCipherPermissionsForUserQuery;
}
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context,
SecurityTaskOperationRequirement requirement,
SecurityTask task)
{
if (!_currentContext.UserId.HasValue)
{
return;
}
var org = _currentContext.GetOrganization(task.OrganizationId);
if (org == null)
{
// User must be a member of the organization
return;
}
var authorized = requirement switch
{
not null when requirement == SecurityTaskOperations.Read => await CanReadAsync(task, org),
not null when requirement == SecurityTaskOperations.Create => await CanCreateAsync(task, org),
not null when requirement == SecurityTaskOperations.Update => await CanUpdateAsync(task, org),
_ => throw new ArgumentOutOfRangeException(nameof(requirement), requirement, null)
};
if (authorized)
{
context.Succeed(requirement);
}
}
private async Task<bool> CanReadAsync(SecurityTask task, CurrentContextOrganization org)
{
if (!task.CipherId.HasValue)
{
// Tasks without cipher IDs are not possible currently
return false;
}
if (HasAdminAccessToSecurityTasks(org))
{
// Admins can read any task for ciphers in the organization
return await CipherBelongsToOrgAsync(org, task.CipherId.Value);
}
return await CanReadCipherForOrgAsync(org, task.CipherId.Value);
}
private async Task<bool> CanCreateAsync(SecurityTask task, CurrentContextOrganization org)
{
if (!task.CipherId.HasValue)
{
// Tasks without cipher IDs are not possible currently
return false;
}
if (!HasAdminAccessToSecurityTasks(org))
{
// User must be an Admin/Owner or have custom permissions for reporting
return false;
}
return await CipherBelongsToOrgAsync(org, task.CipherId.Value);
}
private async Task<bool> CanUpdateAsync(SecurityTask task, CurrentContextOrganization org)
{
if (!task.CipherId.HasValue)
{
// Tasks without cipher IDs are not possible currently
return false;
}
// Only users that can edit the cipher can update the task
return await CanEditCipherForOrgAsync(org, task.CipherId.Value);
}
private async Task<bool> CanEditCipherForOrgAsync(CurrentContextOrganization org, Guid cipherId)
{
var ciphers = await GetCipherPermissionsForOrgAsync(org);
return ciphers.TryGetValue(cipherId, out var cipher) && cipher.Edit;
}
private async Task<bool> CanReadCipherForOrgAsync(CurrentContextOrganization org, Guid cipherId)
{
var ciphers = await GetCipherPermissionsForOrgAsync(org);
return ciphers.TryGetValue(cipherId, out var cipher) && cipher.Read;
}
private async Task<bool> CipherBelongsToOrgAsync(CurrentContextOrganization org, Guid cipherId)
{
var ciphers = await GetCipherPermissionsForOrgAsync(org);
return ciphers.ContainsKey(cipherId);
}
private bool HasAdminAccessToSecurityTasks(CurrentContextOrganization org)
{
return org is
{ Type: OrganizationUserType.Admin or OrganizationUserType.Owner } or
{ Type: OrganizationUserType.Custom, Permissions.AccessReports: true };
}
private async Task<IDictionary<Guid, OrganizationCipherPermission>> GetCipherPermissionsForOrgAsync(CurrentContextOrganization organization)
{
// Re-use permissions we've already fetched for the organization
if (_cipherPermissionCache.TryGetValue(organization.Id, out var cachedCiphers))
{
return cachedCiphers;
}
var cipherPermissions = await _getCipherPermissionsForUserQuery.GetByOrganization(organization.Id);
_cipherPermissionCache.Add(organization.Id, cipherPermissions);
return cipherPermissions;
}
}

View File

@ -0,0 +1,27 @@
using Microsoft.AspNetCore.Authorization.Infrastructure;
namespace Bit.Core.Vault.Authorization.SecurityTasks;
public class SecurityTaskOperationRequirement : OperationAuthorizationRequirement
{
public SecurityTaskOperationRequirement(string name)
{
Name = name;
}
}
public static class SecurityTaskOperations
{
public static readonly SecurityTaskOperationRequirement Read = new SecurityTaskOperationRequirement(nameof(Read));
public static readonly SecurityTaskOperationRequirement Create = new SecurityTaskOperationRequirement(nameof(Create));
public static readonly SecurityTaskOperationRequirement Update = new SecurityTaskOperationRequirement(nameof(Update));
/// <summary>
/// List all security tasks for a specific organization.
/// <example><code>
/// var orgContext = _currentContext.GetOrganization(organizationId);
/// _authorizationService.AuthorizeOrThrowAsync(User, SecurityTaskOperations.ListAllForOrganization, orgContext);
/// </code></example>
/// </summary>
public static readonly SecurityTaskOperationRequirement ListAllForOrganization = new SecurityTaskOperationRequirement(nameof(ListAllForOrganization));
}

View File

@ -0,0 +1,47 @@
using Bit.Core.Context;
using Bit.Core.Enums;
using Microsoft.AspNetCore.Authorization;
namespace Bit.Core.Vault.Authorization.SecurityTasks;
public class
SecurityTaskOrganizationAuthorizationHandler : AuthorizationHandler<SecurityTaskOperationRequirement,
CurrentContextOrganization>
{
private readonly ICurrentContext _currentContext;
public SecurityTaskOrganizationAuthorizationHandler(ICurrentContext currentContext)
{
_currentContext = currentContext;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
SecurityTaskOperationRequirement requirement,
CurrentContextOrganization resource)
{
if (!_currentContext.UserId.HasValue)
{
return Task.CompletedTask;
}
var authorized = requirement switch
{
not null when requirement == SecurityTaskOperations.ListAllForOrganization => CanListAllTasksForOrganization(resource),
_ => throw new ArgumentOutOfRangeException(nameof(requirement), requirement, null)
};
if (authorized)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
private static bool CanListAllTasksForOrganization(CurrentContextOrganization org)
{
return org is
{ Type: OrganizationUserType.Admin or OrganizationUserType.Owner } or
{ Type: OrganizationUserType.Custom, Permissions.AccessReports: true };
}
}

View File

@ -0,0 +1,40 @@
namespace Bit.Core.Vault.Models.Data;
/// <summary>
/// Data model that represents a Users permissions for a given cipher
/// that belongs to an organization.
/// To be used internally for authorization.
/// </summary>
public class OrganizationCipherPermission
{
/// <summary>
/// The cipher Id
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// The organization Id that the cipher belongs to.
/// </summary>
public Guid OrganizationId { get; set; }
/// <summary>
/// The user can read the cipher.
/// See <see cref="ViewPassword"/> for password visibility.
/// </summary>
public bool Read { get; set; }
/// <summary>
/// The user has permission to view the password of the cipher.
/// </summary>
public bool ViewPassword { get; set; }
/// <summary>
/// The user has permission to edit the cipher.
/// </summary>
public bool Edit { get; set; }
/// <summary>
/// The user has manage level access to the cipher.
/// </summary>
public bool Manage { get; set; }
}

View File

@ -0,0 +1,97 @@
using Bit.Core.Context;
using Bit.Core.Enums;
using Bit.Core.Exceptions;
using Bit.Core.Services;
using Bit.Core.Vault.Models.Data;
using Bit.Core.Vault.Repositories;
namespace Bit.Core.Vault.Queries;
public class GetCipherPermissionsForUserQuery : IGetCipherPermissionsForUserQuery
{
private readonly ICurrentContext _currentContext;
private readonly ICipherRepository _cipherRepository;
private readonly IApplicationCacheService _applicationCacheService;
public GetCipherPermissionsForUserQuery(ICurrentContext currentContext, ICipherRepository cipherRepository, IApplicationCacheService applicationCacheService)
{
_currentContext = currentContext;
_cipherRepository = cipherRepository;
_applicationCacheService = applicationCacheService;
}
public async Task<IDictionary<Guid, OrganizationCipherPermission>> GetByOrganization(Guid organizationId)
{
var org = _currentContext.GetOrganization(organizationId);
var userId = _currentContext.UserId;
if (org == null || !userId.HasValue)
{
throw new NotFoundException();
}
var cipherPermissions =
(await _cipherRepository.GetCipherPermissionsForOrganizationAsync(organizationId, userId.Value))
.ToList()
.ToDictionary(c => c.Id);
if (await CanEditAllCiphersAsync(org))
{
foreach (var cipher in cipherPermissions)
{
cipher.Value.Read = true;
cipher.Value.Edit = true;
cipher.Value.Manage = true;
cipher.Value.ViewPassword = true;
}
}
else if (await CanAccessUnassignedCiphersAsync(org))
{
var unassignedCiphers = await _cipherRepository.GetManyUnassignedOrganizationDetailsByOrganizationIdAsync(organizationId);
foreach (var unassignedCipher in unassignedCiphers)
{
if (cipherPermissions.TryGetValue(unassignedCipher.Id, out var p))
{
p.Read = true;
p.Edit = true;
p.Manage = true;
p.ViewPassword = true;
}
}
}
return cipherPermissions;
}
private async Task<bool> CanEditAllCiphersAsync(CurrentContextOrganization org)
{
// Custom users with EditAnyCollection permissions can always edit all ciphers
if (org is { Type: OrganizationUserType.Custom, Permissions.EditAnyCollection: true })
{
return true;
}
var orgAbility = await _applicationCacheService.GetOrganizationAbilityAsync(org.Id);
// Owners/Admins can only edit all ciphers if the organization has the setting enabled
if (orgAbility is { AllowAdminAccessToAllCollectionItems: true } && org is
{ Type: OrganizationUserType.Admin or OrganizationUserType.Owner })
{
return true;
}
return false;
}
private async Task<bool> CanAccessUnassignedCiphersAsync(CurrentContextOrganization org)
{
if (org is
{ Type: OrganizationUserType.Owner or OrganizationUserType.Admin } or
{ Permissions.EditAnyCollection: true })
{
return true;
}
return false;
}
}

View File

@ -0,0 +1,19 @@
using Bit.Core.Vault.Models.Data;
namespace Bit.Core.Vault.Queries;
public interface IGetCipherPermissionsForUserQuery
{
/// <summary>
/// Retrieves the permissions of every organization cipher (including unassigned) for the
/// ICurrentContext's user.
///
/// It considers the Collection Management setting for allowing Admin/Owners access to all ciphers.
/// </summary>
/// <remarks>
/// The primary use case of this query is internal cipher authorization logic.
/// </remarks>
/// <param name="organizationId"></param>
/// <returns>A dictionary of CipherIds and a corresponding OrganizationCipherPermission</returns>
public Task<IDictionary<Guid, OrganizationCipherPermission>> GetByOrganization(Guid organizationId);
}

View File

@ -39,6 +39,16 @@ public interface ICipherRepository : IRepository<Cipher, Guid>
Task<DateTime> RestoreByIdsOrganizationIdAsync(IEnumerable<Guid> ids, Guid organizationId);
Task DeleteDeletedAsync(DateTime deletedDateBefore);
/// <summary>
/// Low-level query to get all cipher permissions for a user in an organization. DOES NOT consider the user's
/// organization role, any collection management settings on the organization, or special unassigned cipher
/// permissions.
///
/// Recommended to use <see cref="IGetCipherPermissionsForUserQuery"/> instead to handle those cases.
/// </summary>
Task<ICollection<OrganizationCipherPermission>> GetCipherPermissionsForOrganizationAsync(Guid organizationId,
Guid userId);
/// <summary>
/// Updates encrypted data for ciphers during a key rotation
/// </summary>

View File

@ -19,5 +19,6 @@ public static class VaultServiceCollectionExtensions
services.AddScoped<IOrganizationCiphersQuery, OrganizationCiphersQuery>();
services.AddScoped<IGetTaskDetailsForUserQuery, GetTaskDetailsForUserQuery>();
services.AddScoped<IMarkTaskAsCompleteCommand, MarkTaskAsCompletedCommand>();
services.AddScoped<IGetCipherPermissionsForUserQuery, GetCipherPermissionsForUserQuery>();
}
}