1
0
mirror of https://github.com/bitwarden/server.git synced 2025-06-30 07:36:14 -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

@ -4,6 +4,7 @@ using Bit.Core.AdminConsole.OrganizationFeatures.Groups.Authorization;
using Bit.Core.IdentityServer;
using Bit.Core.Settings;
using Bit.Core.Utilities;
using Bit.Core.Vault.Authorization.SecurityTasks;
using Bit.SharedWeb.Health;
using Bit.SharedWeb.Swagger;
using Microsoft.AspNetCore.Authorization;
@ -104,5 +105,7 @@ public static class ServiceCollectionExtensions
services.AddScoped<IAuthorizationHandler, CollectionAuthorizationHandler>();
services.AddScoped<IAuthorizationHandler, GroupAuthorizationHandler>();
services.AddScoped<IAuthorizationHandler, VaultExportAuthorizationHandler>();
services.AddScoped<IAuthorizationHandler, SecurityTaskAuthorizationHandler>();
services.AddScoped<IAuthorizationHandler, SecurityTaskOrganizationAuthorizationHandler>();
}
}

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>();
}
}

View File

@ -309,6 +309,20 @@ public class CipherRepository : Repository<Cipher, Guid>, ICipherRepository
}
}
public async Task<ICollection<OrganizationCipherPermission>> GetCipherPermissionsForOrganizationAsync(
Guid organizationId, Guid userId)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.QueryAsync<OrganizationCipherPermission>(
$"[{Schema}].[CipherOrganizationPermissions_GetManyByOrganizationId]",
new { OrganizationId = organizationId, UserId = userId },
commandType: CommandType.StoredProcedure);
return results.ToList();
}
}
/// <inheritdoc />
public UpdateEncryptedDataForKeyRotation UpdateForKeyRotation(
Guid userId, IEnumerable<Cipher> ciphers)

View File

@ -302,6 +302,52 @@ public class CipherRepository : Repository<Core.Vault.Entities.Cipher, Cipher, G
}
}
public async Task<ICollection<OrganizationCipherPermission>>
GetCipherPermissionsForOrganizationAsync(Guid organizationId, Guid userId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var query = new CipherOrganizationPermissionsQuery(organizationId, userId).Run(dbContext);
ICollection<OrganizationCipherPermission> permissions;
// SQLite does not support the GROUP BY clause
if (dbContext.Database.IsSqlite())
{
permissions = (await query.ToListAsync())
.GroupBy(c => new { c.Id, c.OrganizationId })
.Select(g => new OrganizationCipherPermission
{
Id = g.Key.Id,
OrganizationId = g.Key.OrganizationId,
Read = Convert.ToBoolean(g.Max(c => Convert.ToInt32(c.Read))),
ViewPassword = Convert.ToBoolean(g.Max(c => Convert.ToInt32(c.ViewPassword))),
Edit = Convert.ToBoolean(g.Max(c => Convert.ToInt32(c.Edit))),
Manage = Convert.ToBoolean(g.Max(c => Convert.ToInt32(c.Manage))),
}).ToList();
}
else
{
var groupByQuery = from p in query
group p by new { p.Id, p.OrganizationId }
into g
select new OrganizationCipherPermission
{
Id = g.Key.Id,
OrganizationId = g.Key.OrganizationId,
Read = Convert.ToBoolean(g.Max(c => Convert.ToInt32(c.Read))),
ViewPassword = Convert.ToBoolean(g.Max(c => Convert.ToInt32(c.ViewPassword))),
Edit = Convert.ToBoolean(g.Max(c => Convert.ToInt32(c.Edit))),
Manage = Convert.ToBoolean(g.Max(c => Convert.ToInt32(c.Manage))),
};
permissions = await groupByQuery.ToListAsync();
}
return permissions;
}
}
public async Task<CipherDetails> GetByIdAsync(Guid id, Guid userId)
{
using (var scope = ServiceScopeFactory.CreateScope())

View File

@ -0,0 +1,63 @@
using Bit.Core.Vault.Models.Data;
using Bit.Infrastructure.EntityFramework.Repositories;
using Bit.Infrastructure.EntityFramework.Repositories.Queries;
namespace Bit.Infrastructure.EntityFramework.Vault.Repositories.Queries;
public class CipherOrganizationPermissionsQuery : IQuery<OrganizationCipherPermission>
{
private readonly Guid _organizationId;
private readonly Guid _userId;
public CipherOrganizationPermissionsQuery(Guid organizationId, Guid userId)
{
_organizationId = organizationId;
_userId = userId;
}
public IQueryable<OrganizationCipherPermission> Run(DatabaseContext dbContext)
{
return from c in dbContext.Ciphers
join ou in dbContext.OrganizationUsers
on new { CipherUserId = c.UserId, c.OrganizationId, UserId = (Guid?)_userId } equals
new { CipherUserId = (Guid?)null, OrganizationId = (Guid?)ou.OrganizationId, ou.UserId, }
join o in dbContext.Organizations
on new { c.OrganizationId, OuOrganizationId = ou.OrganizationId, Enabled = true } equals
new { OrganizationId = (Guid?)o.Id, OuOrganizationId = o.Id, o.Enabled }
join cc in dbContext.CollectionCiphers
on c.Id equals cc.CipherId into cc_g
from cc in cc_g.DefaultIfEmpty()
join cu in dbContext.CollectionUsers
on new { cc.CollectionId, OrganizationUserId = ou.Id } equals
new { cu.CollectionId, cu.OrganizationUserId } into cu_g
from cu in cu_g.DefaultIfEmpty()
join gu in dbContext.GroupUsers
on new { CollectionId = (Guid?)cu.CollectionId, OrganizationUserId = ou.Id } equals
new { CollectionId = (Guid?)null, gu.OrganizationUserId } into gu_g
from gu in gu_g.DefaultIfEmpty()
join g in dbContext.Groups
on gu.GroupId equals g.Id into g_g
from g in g_g.DefaultIfEmpty()
join cg in dbContext.CollectionGroups
on new { cc.CollectionId, gu.GroupId } equals
new { cg.CollectionId, cg.GroupId } into cg_g
from cg in cg_g.DefaultIfEmpty()
select new OrganizationCipherPermission()
{
Id = c.Id,
OrganizationId = o.Id,
Read = cu != null || cg != null,
ViewPassword = !((bool?)cu.HidePasswords ?? (bool?)cg.HidePasswords ?? true),
Edit = !((bool?)cu.ReadOnly ?? (bool?)cg.ReadOnly ?? true),
Manage = (bool?)cu.Manage ?? (bool?)cg.Manage ?? false,
};
}
}

View File

@ -0,0 +1,76 @@
CREATE PROCEDURE [dbo].[CipherOrganizationPermissions_GetManyByOrganizationId]
@OrganizationId UNIQUEIDENTIFIER,
@UserId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON
;WITH BaseCiphers AS (
SELECT C.[Id], C.[OrganizationId]
FROM [dbo].[CipherDetails](@UserId) C
INNER JOIN [OrganizationUser] OU ON
C.[UserId] IS NULL
AND C.[OrganizationId] = @OrganizationId
AND OU.[UserId] = @UserId
INNER JOIN [dbo].[Organization] O ON
O.[Id] = OU.[OrganizationId]
AND O.[Id] = C.[OrganizationId]
AND O.[Enabled] = 1
),
UserPermissions AS (
SELECT DISTINCT
CC.[CipherId],
CASE WHEN CC.[CollectionId] IS NULL THEN 0 ELSE 1 END as [Read],
CASE WHEN CU.[HidePasswords] = 0 THEN 1 ELSE 0 END as [ViewPassword],
CASE WHEN CU.[ReadOnly] = 0 THEN 1 ELSE 0 END as [Edit],
COALESCE(CU.[Manage], 0) as [Manage]
FROM [dbo].[CollectionCipher] CC
INNER JOIN [dbo].[CollectionUser] CU ON
CU.[CollectionId] = CC.[CollectionId]
AND CU.[OrganizationUserId] = (
SELECT [Id] FROM [OrganizationUser]
WHERE [UserId] = @UserId
AND [OrganizationId] = @OrganizationId
)
),
GroupPermissions AS (
SELECT DISTINCT
CC.[CipherId],
CASE WHEN CC.[CollectionId] IS NULL THEN 0 ELSE 1 END as [Read],
CASE WHEN CG.[HidePasswords] = 0 THEN 1 ELSE 0 END as [ViewPassword],
CASE WHEN CG.[ReadOnly] = 0 THEN 1 ELSE 0 END as [Edit],
COALESCE(CG.[Manage], 0) as [Manage]
FROM [dbo].[CollectionCipher] CC
INNER JOIN [dbo].[CollectionGroup] CG ON
CG.[CollectionId] = CC.[CollectionId]
INNER JOIN [dbo].[GroupUser] GU ON
GU.[GroupId] = CG.[GroupId]
AND GU.[OrganizationUserId] = (
SELECT [Id] FROM [OrganizationUser]
WHERE [UserId] = @UserId
AND [OrganizationId] = @OrganizationId
)
WHERE NOT EXISTS (
SELECT 1
FROM UserPermissions UP
WHERE UP.[CipherId] = CC.[CipherId]
)
),
CombinedPermissions AS (
SELECT CipherId, [Read], ViewPassword, Edit, Manage
FROM UserPermissions
UNION ALL
SELECT CipherId, [Read], ViewPassword, Edit, Manage
FROM GroupPermissions
)
SELECT
C.[Id],
C.[OrganizationId],
ISNULL(MAX(P.[Read]), 0) as [Read],
ISNULL(MAX(P.[ViewPassword]), 0) as [ViewPassword],
ISNULL(MAX(P.[Edit]), 0) as [Edit],
ISNULL(MAX(P.[Manage]), 0) as [Manage]
FROM BaseCiphers C
LEFT JOIN CombinedPermissions P ON P.CipherId = C.[Id]
GROUP BY C.[Id], C.[OrganizationId]
END