1
0
mirror of https://github.com/bitwarden/server.git synced 2025-01-21 21:41:21 +01:00

Merge branch 'main' into ephemeral-environment-api-env

This commit is contained in:
Micaiah Martin 2024-10-03 14:48:31 -06:00
commit 6c82aab635
69 changed files with 19861 additions and 228 deletions

View File

@ -1,102 +0,0 @@
---
name: Container registry purge
on:
schedule:
- cron: "0 0 * * SUN"
workflow_dispatch:
inputs: {}
jobs:
purge:
name: Purge old images
runs-on: ubuntu-22.04
steps:
- name: Log in to Azure
uses: Azure/login@e15b166166a8746d1a47596803bd8c1b595455cf # v1.6.0
with:
creds: ${{ secrets.AZURE_PROD_KV_CREDENTIALS }}
- name: Purge images
env:
REGISTRY: bitwardenprod
AGO_DUR_VER: "180d"
AGO_DUR: "30d"
run: |
REPO_LIST=$(az acr repository list -n $REGISTRY -o tsv)
for REPO in $REPO_LIST
do
PURGE_LATEST=""
PURGE_VERSION=""
PURGE_ELSE=""
TAG_LIST=$(az acr repository show-tags -n $REGISTRY --repository $REPO -o tsv)
for TAG in $TAG_LIST
do
if [ $TAG = "latest" ] || [ $TAG = "dev" ]; then
PURGE_LATEST+="--filter '$REPO:$TAG' "
elif [[ $TAG =~ [0-9]+\.[0-9]+\.[0-9]+ ]]; then
PURGE_VERSION+="--filter '$REPO:$TAG' "
else
PURGE_ELSE+="--filter '$REPO:$TAG' "
fi
done
if [ ! -z "$PURGE_LATEST" ]
then
PURGE_LATEST_CMD="acr purge $PURGE_LATEST --ago $AGO_DUR_VER --untagged --keep 1"
az acr run --cmd "$PURGE_LATEST_CMD" --registry $REGISTRY /dev/null &
fi
if [ ! -z "$PURGE_VERSION" ]
then
PURGE_VERSION_CMD="acr purge $PURGE_VERSION --ago $AGO_DUR_VER --untagged"
az acr run --cmd "$PURGE_VERSION_CMD" --registry $REGISTRY /dev/null &
fi
if [ ! -z "$PURGE_ELSE" ]
then
PURGE_ELSE_CMD="acr purge $PURGE_ELSE --ago $AGO_DUR --untagged"
az acr run --cmd "$PURGE_ELSE_CMD" --registry $REGISTRY /dev/null &
fi
wait
done
check-failures:
name: Check for failures
if: always()
runs-on: ubuntu-22.04
needs: [purge]
steps:
- name: Check if any job failed
if: |
(github.ref == 'refs/heads/main'
|| github.ref == 'refs/heads/rc'
|| github.ref == 'refs/heads/hotfix-rc')
&& contains(needs.*.result, 'failure')
run: exit 1
- name: Log in to Azure - CI subscription
uses: Azure/login@e15b166166a8746d1a47596803bd8c1b595455cf # v1.6.0
if: failure()
with:
creds: ${{ secrets.AZURE_KV_CI_SERVICE_PRINCIPAL }}
- name: Retrieve secrets
id: retrieve-secrets
uses: bitwarden/gh-actions/get-keyvault-secrets@main
if: failure()
with:
keyvault: "bitwarden-ci"
secrets: "devops-alerts-slack-webhook-url"
- name: Notify Slack on failure
uses: act10ns/slack@44541246747a30eb3102d87f7a4cc5471b0ffb7d # v2.1.0
if: failure()
env:
SLACK_WEBHOOK_URL: ${{ steps.retrieve-secrets.outputs.devops-alerts-slack-webhook-url }}
with:
status: ${{ job.status }}

View File

@ -174,18 +174,15 @@
<div class="d-flex mt-4">
<button type="submit" class="btn btn-primary" form="edit-form">Save</button>
@if (FeatureService.IsEnabled(FeatureFlagKeys.EnableDeleteProvider))
{
<div class="ml-auto d-flex">
<button class="btn btn-danger" onclick="openRequestDeleteModal(@Model.ProviderOrganizations.Count())">Request Delete</button>
<button id="requestDeletionBtn" hidden="hidden" data-toggle="modal" data-target="#requestDeletionModal"></button>
<div class="ml-auto d-flex">
<button class="btn btn-danger" onclick="openRequestDeleteModal(@Model.ProviderOrganizations.Count())">Request Delete</button>
<button id="requestDeletionBtn" hidden="hidden" data-toggle="modal" data-target="#requestDeletionModal"></button>
<button class="btn btn-outline-danger ml-2" onclick="openDeleteModal(@Model.ProviderOrganizations.Count())">Delete</button>
<button id="deleteBtn" hidden="hidden" data-toggle="modal" data-target="#DeleteModal"></button>
<button class="btn btn-outline-danger ml-2" onclick="openDeleteModal(@Model.ProviderOrganizations.Count())">Delete</button>
<button id="deleteBtn" hidden="hidden" data-toggle="modal" data-target="#DeleteModal"></button>
<button id="linkAccWarningBtn" hidden="hidden" data-toggle="modal" data-target="#linkedWarningModal"></button>
<button id="linkAccWarningBtn" hidden="hidden" data-toggle="modal" data-target="#linkedWarningModal"></button>
</div>
}
</div>
</div>
}

View File

@ -94,6 +94,7 @@ public class Organization : ITableObject<Guid>, IStorableSubscriber, IRevisable,
/// they have Can Manage permissions for.
/// </summary>
public bool LimitCollectionCreationDeletion { get; set; }
/// <summary>
/// If set to true, admins, owners, and some custom users can read/write all collections and items in the Admin Console.
/// If set to false, users generally need collection-level permissions to read/write a collection or its items.

View File

@ -110,7 +110,6 @@ public static class FeatureFlagKeys
public const string AC2101UpdateTrialInitiationEmail = "AC-2101-update-trial-initiation-email";
public const string EnableConsolidatedBilling = "enable-consolidated-billing";
public const string AC1795_UpdatedSubscriptionStatusSection = "AC-1795_updated-subscription-status-section";
public const string EnableDeleteProvider = "AC-1218-delete-provider";
public const string EmailVerification = "email-verification";
public const string EmailVerificationDisableTimingDelays = "email-verification-disable-timing-delays";
public const string AnhFcmv1Migration = "anh-fcmv1-migration";
@ -144,6 +143,7 @@ public static class FeatureFlagKeys
public const string StorageReseedRefactor = "storage-reseed-refactor";
public const string TrialPayment = "PM-8163-trial-payment";
public const string Pm3478RefactorOrganizationUserApi = "pm-3478-refactor-organizationuser-api";
public const string RemoveServerVersionHeader = "remove-server-version-header";
public static List<string> GetAllKeys()
{

View File

@ -0,0 +1,68 @@
#nullable enable
using Bit.Core.Context;
using Bit.Core.NotificationCenter.Entities;
using Microsoft.AspNetCore.Authorization;
namespace Bit.Core.NotificationCenter.Authorization;
public class NotificationAuthorizationHandler : AuthorizationHandler<NotificationOperationsRequirement, Notification>
{
private readonly ICurrentContext _currentContext;
public NotificationAuthorizationHandler(ICurrentContext currentContext)
{
_currentContext = currentContext;
}
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context,
NotificationOperationsRequirement requirement,
Notification notification)
{
if (!_currentContext.UserId.HasValue)
{
return;
}
var authorized = requirement switch
{
not null when requirement == NotificationOperations.Read => CanRead(notification),
not null when requirement == NotificationOperations.Create => await CanCreate(notification),
not null when requirement == NotificationOperations.Update => await CanUpdate(notification),
_ => throw new ArgumentException("Unsupported operation requirement type provided.", nameof(requirement))
};
if (authorized)
{
context.Succeed(requirement);
}
}
private bool CanRead(Notification notification)
{
var userMatching = !notification.UserId.HasValue || notification.UserId.Value == _currentContext.UserId!.Value;
var organizationMatching = !notification.OrganizationId.HasValue ||
_currentContext.GetOrganization(notification.OrganizationId.Value) != null;
return notification.Global || (userMatching && organizationMatching);
}
private async Task<bool> CanCreate(Notification notification)
{
var organizationPermissionsMatching = !notification.OrganizationId.HasValue ||
await _currentContext.AccessReports(notification.OrganizationId.Value);
var userNoOrganizationMatching = !notification.UserId.HasValue || notification.OrganizationId.HasValue ||
notification.UserId.Value == _currentContext.UserId!.Value;
return !notification.Global && organizationPermissionsMatching && userNoOrganizationMatching;
}
private async Task<bool> CanUpdate(Notification notification)
{
var organizationPermissionsMatching = !notification.OrganizationId.HasValue ||
await _currentContext.AccessReports(notification.OrganizationId.Value);
var userNoOrganizationMatching = !notification.UserId.HasValue || notification.OrganizationId.HasValue ||
notification.UserId.Value == _currentContext.UserId!.Value;
return !notification.Global && organizationPermissionsMatching && userNoOrganizationMatching;
}
}

View File

@ -0,0 +1,19 @@
#nullable enable
using Microsoft.AspNetCore.Authorization.Infrastructure;
namespace Bit.Core.NotificationCenter.Authorization;
public class NotificationOperationsRequirement : OperationAuthorizationRequirement
{
public NotificationOperationsRequirement(string name)
{
Name = name;
}
}
public static class NotificationOperations
{
public static readonly NotificationOperationsRequirement Read = new(nameof(Read));
public static readonly NotificationOperationsRequirement Create = new(nameof(Create));
public static readonly NotificationOperationsRequirement Update = new(nameof(Update));
}

View File

@ -0,0 +1,57 @@
#nullable enable
using Bit.Core.Context;
using Bit.Core.NotificationCenter.Entities;
using Microsoft.AspNetCore.Authorization;
namespace Bit.Core.NotificationCenter.Authorization;
public class NotificationStatusAuthorizationHandler : AuthorizationHandler<NotificationStatusOperationsRequirement,
NotificationStatus>
{
private readonly ICurrentContext _currentContext;
public NotificationStatusAuthorizationHandler(ICurrentContext currentContext)
{
_currentContext = currentContext;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
NotificationStatusOperationsRequirement requirement,
NotificationStatus notificationStatus)
{
if (!_currentContext.UserId.HasValue)
{
return Task.CompletedTask;
}
var authorized = requirement switch
{
not null when requirement == NotificationStatusOperations.Read => CanRead(notificationStatus),
not null when requirement == NotificationStatusOperations.Create => CanCreate(notificationStatus),
not null when requirement == NotificationStatusOperations.Update => CanUpdate(notificationStatus),
_ => throw new ArgumentException("Unsupported operation requirement type provided.", nameof(requirement))
};
if (authorized)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
private bool CanRead(NotificationStatus notificationStatus)
{
return notificationStatus.UserId == _currentContext.UserId!.Value;
}
private bool CanCreate(NotificationStatus notificationStatus)
{
return notificationStatus.UserId == _currentContext.UserId!.Value;
}
private bool CanUpdate(NotificationStatus notificationStatus)
{
return notificationStatus.UserId == _currentContext.UserId!.Value;
}
}

View File

@ -0,0 +1,19 @@
#nullable enable
using Microsoft.AspNetCore.Authorization.Infrastructure;
namespace Bit.Core.NotificationCenter.Authorization;
public class NotificationStatusOperationsRequirement : OperationAuthorizationRequirement
{
public NotificationStatusOperationsRequirement(string name)
{
Name = name;
}
}
public static class NotificationStatusOperations
{
public static readonly NotificationStatusOperationsRequirement Read = new(nameof(Read));
public static readonly NotificationStatusOperationsRequirement Create = new(nameof(Create));
public static readonly NotificationStatusOperationsRequirement Update = new(nameof(Update));
}

View File

@ -0,0 +1,36 @@
#nullable enable
using Bit.Core.Context;
using Bit.Core.NotificationCenter.Authorization;
using Bit.Core.NotificationCenter.Commands.Interfaces;
using Bit.Core.NotificationCenter.Entities;
using Bit.Core.NotificationCenter.Repositories;
using Bit.Core.Utilities;
using Microsoft.AspNetCore.Authorization;
namespace Bit.Core.NotificationCenter.Commands;
public class CreateNotificationCommand : ICreateNotificationCommand
{
private readonly ICurrentContext _currentContext;
private readonly IAuthorizationService _authorizationService;
private readonly INotificationRepository _notificationRepository;
public CreateNotificationCommand(ICurrentContext currentContext,
IAuthorizationService authorizationService,
INotificationRepository notificationRepository)
{
_currentContext = currentContext;
_authorizationService = authorizationService;
_notificationRepository = notificationRepository;
}
public async Task<Notification> CreateAsync(Notification notification)
{
notification.CreationDate = notification.RevisionDate = DateTime.UtcNow;
await _authorizationService.AuthorizeOrThrowAsync(_currentContext.HttpContext.User, notification,
NotificationOperations.Create);
return await _notificationRepository.CreateAsync(notification);
}
}

View File

@ -0,0 +1,47 @@
#nullable enable
using Bit.Core.Context;
using Bit.Core.Exceptions;
using Bit.Core.NotificationCenter.Authorization;
using Bit.Core.NotificationCenter.Commands.Interfaces;
using Bit.Core.NotificationCenter.Entities;
using Bit.Core.NotificationCenter.Repositories;
using Bit.Core.Utilities;
using Microsoft.AspNetCore.Authorization;
namespace Bit.Core.NotificationCenter.Commands;
public class CreateNotificationStatusCommand : ICreateNotificationStatusCommand
{
private readonly ICurrentContext _currentContext;
private readonly IAuthorizationService _authorizationService;
private readonly INotificationRepository _notificationRepository;
private readonly INotificationStatusRepository _notificationStatusRepository;
public CreateNotificationStatusCommand(ICurrentContext currentContext,
IAuthorizationService authorizationService,
INotificationRepository notificationRepository,
INotificationStatusRepository notificationStatusRepository)
{
_currentContext = currentContext;
_authorizationService = authorizationService;
_notificationRepository = notificationRepository;
_notificationStatusRepository = notificationStatusRepository;
}
public async Task<NotificationStatus> CreateAsync(NotificationStatus notificationStatus)
{
var notification = await _notificationRepository.GetByIdAsync(notificationStatus.NotificationId);
if (notification == null)
{
throw new NotFoundException();
}
await _authorizationService.AuthorizeOrThrowAsync(_currentContext.HttpContext.User, notification,
NotificationOperations.Read);
await _authorizationService.AuthorizeOrThrowAsync(_currentContext.HttpContext.User, notificationStatus,
NotificationStatusOperations.Create);
return await _notificationStatusRepository.CreateAsync(notificationStatus);
}
}

View File

@ -0,0 +1,9 @@
#nullable enable
using Bit.Core.NotificationCenter.Entities;
namespace Bit.Core.NotificationCenter.Commands.Interfaces;
public interface ICreateNotificationCommand
{
Task<Notification> CreateAsync(Notification notification);
}

View File

@ -0,0 +1,9 @@
#nullable enable
using Bit.Core.NotificationCenter.Entities;
namespace Bit.Core.NotificationCenter.Commands.Interfaces;
public interface ICreateNotificationStatusCommand
{
Task<NotificationStatus> CreateAsync(NotificationStatus notificationStatus);
}

View File

@ -0,0 +1,7 @@
#nullable enable
namespace Bit.Core.NotificationCenter.Commands.Interfaces;
public interface IMarkNotificationDeletedCommand
{
Task MarkDeletedAsync(Guid notificationId);
}

View File

@ -0,0 +1,7 @@
#nullable enable
namespace Bit.Core.NotificationCenter.Commands.Interfaces;
public interface IMarkNotificationReadCommand
{
Task MarkReadAsync(Guid notificationId);
}

View File

@ -0,0 +1,9 @@
#nullable enable
using Bit.Core.NotificationCenter.Entities;
namespace Bit.Core.NotificationCenter.Commands.Interfaces;
public interface IUpdateNotificationCommand
{
Task UpdateAsync(Notification notification);
}

View File

@ -0,0 +1,74 @@
#nullable enable
using Bit.Core.Context;
using Bit.Core.Exceptions;
using Bit.Core.NotificationCenter.Authorization;
using Bit.Core.NotificationCenter.Commands.Interfaces;
using Bit.Core.NotificationCenter.Entities;
using Bit.Core.NotificationCenter.Repositories;
using Bit.Core.Utilities;
using Microsoft.AspNetCore.Authorization;
namespace Bit.Core.NotificationCenter.Commands;
public class MarkNotificationDeletedCommand : IMarkNotificationDeletedCommand
{
private readonly ICurrentContext _currentContext;
private readonly IAuthorizationService _authorizationService;
private readonly INotificationRepository _notificationRepository;
private readonly INotificationStatusRepository _notificationStatusRepository;
public MarkNotificationDeletedCommand(ICurrentContext currentContext,
IAuthorizationService authorizationService,
INotificationRepository notificationRepository,
INotificationStatusRepository notificationStatusRepository)
{
_currentContext = currentContext;
_authorizationService = authorizationService;
_notificationRepository = notificationRepository;
_notificationStatusRepository = notificationStatusRepository;
}
public async Task MarkDeletedAsync(Guid notificationId)
{
if (!_currentContext.UserId.HasValue)
{
throw new NotFoundException();
}
var notification = await _notificationRepository.GetByIdAsync(notificationId);
if (notification == null)
{
throw new NotFoundException();
}
await _authorizationService.AuthorizeOrThrowAsync(_currentContext.HttpContext.User, notification,
NotificationOperations.Read);
var notificationStatus = await _notificationStatusRepository.GetByNotificationIdAndUserIdAsync(notificationId,
_currentContext.UserId.Value);
if (notificationStatus == null)
{
notificationStatus = new NotificationStatus()
{
NotificationId = notificationId,
UserId = _currentContext.UserId.Value,
DeletedDate = DateTime.Now
};
await _authorizationService.AuthorizeOrThrowAsync(_currentContext.HttpContext.User, notificationStatus,
NotificationStatusOperations.Create);
await _notificationStatusRepository.CreateAsync(notificationStatus);
}
else
{
await _authorizationService.AuthorizeOrThrowAsync(_currentContext.HttpContext.User, notificationStatus,
NotificationStatusOperations.Update);
notificationStatus.DeletedDate = DateTime.UtcNow;
await _notificationStatusRepository.UpdateAsync(notificationStatus);
}
}
}

View File

@ -0,0 +1,74 @@
#nullable enable
using Bit.Core.Context;
using Bit.Core.Exceptions;
using Bit.Core.NotificationCenter.Authorization;
using Bit.Core.NotificationCenter.Commands.Interfaces;
using Bit.Core.NotificationCenter.Entities;
using Bit.Core.NotificationCenter.Repositories;
using Bit.Core.Utilities;
using Microsoft.AspNetCore.Authorization;
namespace Bit.Core.NotificationCenter.Commands;
public class MarkNotificationReadCommand : IMarkNotificationReadCommand
{
private readonly ICurrentContext _currentContext;
private readonly IAuthorizationService _authorizationService;
private readonly INotificationRepository _notificationRepository;
private readonly INotificationStatusRepository _notificationStatusRepository;
public MarkNotificationReadCommand(ICurrentContext currentContext,
IAuthorizationService authorizationService,
INotificationRepository notificationRepository,
INotificationStatusRepository notificationStatusRepository)
{
_currentContext = currentContext;
_authorizationService = authorizationService;
_notificationRepository = notificationRepository;
_notificationStatusRepository = notificationStatusRepository;
}
public async Task MarkReadAsync(Guid notificationId)
{
if (!_currentContext.UserId.HasValue)
{
throw new NotFoundException();
}
var notification = await _notificationRepository.GetByIdAsync(notificationId);
if (notification == null)
{
throw new NotFoundException();
}
await _authorizationService.AuthorizeOrThrowAsync(_currentContext.HttpContext.User, notification,
NotificationOperations.Read);
var notificationStatus = await _notificationStatusRepository.GetByNotificationIdAndUserIdAsync(notificationId,
_currentContext.UserId.Value);
if (notificationStatus == null)
{
notificationStatus = new NotificationStatus()
{
NotificationId = notificationId,
UserId = _currentContext.UserId.Value,
ReadDate = DateTime.Now
};
await _authorizationService.AuthorizeOrThrowAsync(_currentContext.HttpContext.User, notificationStatus,
NotificationStatusOperations.Create);
await _notificationStatusRepository.CreateAsync(notificationStatus);
}
else
{
await _authorizationService.AuthorizeOrThrowAsync(_currentContext.HttpContext.User,
notificationStatus, NotificationStatusOperations.Update);
notificationStatus.ReadDate = DateTime.UtcNow;
await _notificationStatusRepository.UpdateAsync(notificationStatus);
}
}
}

View File

@ -0,0 +1,47 @@
#nullable enable
using Bit.Core.Context;
using Bit.Core.Exceptions;
using Bit.Core.NotificationCenter.Authorization;
using Bit.Core.NotificationCenter.Commands.Interfaces;
using Bit.Core.NotificationCenter.Entities;
using Bit.Core.NotificationCenter.Repositories;
using Bit.Core.Utilities;
using Microsoft.AspNetCore.Authorization;
namespace Bit.Core.NotificationCenter.Commands;
public class UpdateNotificationCommand : IUpdateNotificationCommand
{
private readonly ICurrentContext _currentContext;
private readonly IAuthorizationService _authorizationService;
private readonly INotificationRepository _notificationRepository;
public UpdateNotificationCommand(ICurrentContext currentContext,
IAuthorizationService authorizationService,
INotificationRepository notificationRepository)
{
_currentContext = currentContext;
_authorizationService = authorizationService;
_notificationRepository = notificationRepository;
}
public async Task UpdateAsync(Notification notificationToUpdate)
{
var notification = await _notificationRepository.GetByIdAsync(notificationToUpdate.Id);
if (notification == null)
{
throw new NotFoundException();
}
await _authorizationService.AuthorizeOrThrowAsync(_currentContext.HttpContext.User,
notification, NotificationOperations.Update);
notification.Priority = notificationToUpdate.Priority;
notification.ClientType = notificationToUpdate.ClientType;
notification.Title = notificationToUpdate.Title;
notification.Body = notificationToUpdate.Body;
notification.RevisionDate = DateTime.UtcNow;
await _notificationRepository.ReplaceAsync(notification);
}
}

View File

@ -0,0 +1,25 @@
#nullable enable
using System.ComponentModel.DataAnnotations;
using Bit.Core.Enums;
using Bit.Core.NotificationCenter.Enums;
namespace Bit.Core.NotificationCenter.Models.Data;
public class NotificationStatusDetails
{
// Notification fields
public Guid Id { get; set; }
public Priority Priority { get; set; }
public bool Global { get; set; }
public ClientType ClientType { get; set; }
public Guid? UserId { get; set; }
public Guid? OrganizationId { get; set; }
[MaxLength(256)]
public string? Title { get; set; }
public string? Body { get; set; }
public DateTime CreationDate { get; set; }
public DateTime RevisionDate { get; set; }
// Notification Status fields
public DateTime? ReadDate { get; set; }
public DateTime? DeletedDate { get; set; }
}

View File

@ -0,0 +1,38 @@
#nullable enable
using Bit.Core.Context;
using Bit.Core.Exceptions;
using Bit.Core.NotificationCenter.Models.Data;
using Bit.Core.NotificationCenter.Models.Filter;
using Bit.Core.NotificationCenter.Queries.Interfaces;
using Bit.Core.NotificationCenter.Repositories;
using Bit.Core.Utilities;
namespace Bit.Core.NotificationCenter.Queries;
public class GetNotificationStatusDetailsForUserQuery : IGetNotificationStatusDetailsForUserQuery
{
private readonly ICurrentContext _currentContext;
private readonly INotificationRepository _notificationRepository;
public GetNotificationStatusDetailsForUserQuery(ICurrentContext currentContext,
INotificationRepository notificationRepository)
{
_currentContext = currentContext;
_notificationRepository = notificationRepository;
}
public async Task<IEnumerable<NotificationStatusDetails>> GetByUserIdStatusFilterAsync(
NotificationStatusFilter statusFilter)
{
if (!_currentContext.UserId.HasValue)
{
throw new NotFoundException();
}
var clientType = DeviceTypes.ToClientType(_currentContext.DeviceType);
// Note: only returns the user's notifications - no authorization check needed
return await _notificationRepository.GetByUserIdAndStatusAsync(_currentContext.UserId.Value, clientType,
statusFilter);
}
}

View File

@ -0,0 +1,47 @@
#nullable enable
using Bit.Core.Context;
using Bit.Core.Exceptions;
using Bit.Core.NotificationCenter.Authorization;
using Bit.Core.NotificationCenter.Entities;
using Bit.Core.NotificationCenter.Queries.Interfaces;
using Bit.Core.NotificationCenter.Repositories;
using Bit.Core.Utilities;
using Microsoft.AspNetCore.Authorization;
namespace Bit.Core.NotificationCenter.Queries;
public class GetNotificationStatusForUserQuery : IGetNotificationStatusForUserQuery
{
private readonly ICurrentContext _currentContext;
private readonly IAuthorizationService _authorizationService;
private readonly INotificationStatusRepository _notificationStatusRepository;
public GetNotificationStatusForUserQuery(ICurrentContext currentContext,
IAuthorizationService authorizationService,
INotificationStatusRepository notificationStatusRepository)
{
_currentContext = currentContext;
_authorizationService = authorizationService;
_notificationStatusRepository = notificationStatusRepository;
}
public async Task<NotificationStatus> GetByNotificationIdAndUserIdAsync(Guid notificationId)
{
if (!_currentContext.UserId.HasValue)
{
throw new NotFoundException();
}
var notificationStatus = await _notificationStatusRepository.GetByNotificationIdAndUserIdAsync(notificationId,
_currentContext.UserId.Value);
if (notificationStatus == null)
{
throw new NotFoundException();
}
await _authorizationService.AuthorizeOrThrowAsync(_currentContext.HttpContext.User,
notificationStatus, NotificationStatusOperations.Read);
return notificationStatus;
}
}

View File

@ -0,0 +1,10 @@
#nullable enable
using Bit.Core.NotificationCenter.Models.Data;
using Bit.Core.NotificationCenter.Models.Filter;
namespace Bit.Core.NotificationCenter.Queries.Interfaces;
public interface IGetNotificationStatusDetailsForUserQuery
{
Task<IEnumerable<NotificationStatusDetails>> GetByUserIdStatusFilterAsync(NotificationStatusFilter statusFilter);
}

View File

@ -0,0 +1,9 @@
#nullable enable
using Bit.Core.NotificationCenter.Entities;
namespace Bit.Core.NotificationCenter.Queries.Interfaces;
public interface IGetNotificationStatusForUserQuery
{
Task<NotificationStatus> GetByNotificationIdAndUserIdAsync(Guid notificationId);
}

View File

@ -1,6 +1,7 @@
#nullable enable
using Bit.Core.Enums;
using Bit.Core.NotificationCenter.Entities;
using Bit.Core.NotificationCenter.Models.Data;
using Bit.Core.NotificationCenter.Models.Filter;
using Bit.Core.Repositories;
@ -23,7 +24,8 @@ public interface INotificationRepository : IRepository<Notification, Guid>
/// </param>
/// <returns>
/// Ordered by priority (highest to lowest) and creation date (descending).
/// Includes all fields from <see cref="Notification"/> and <see cref="NotificationStatus"/>
/// </returns>
Task<IEnumerable<Notification>> GetByUserIdAndStatusAsync(Guid userId, ClientType clientType,
Task<IEnumerable<NotificationStatusDetails>> GetByUserIdAndStatusAsync(Guid userId, ClientType clientType,
NotificationStatusFilter? statusFilter);
}

View File

@ -2,6 +2,7 @@
using System.Data;
using Bit.Core.Enums;
using Bit.Core.NotificationCenter.Entities;
using Bit.Core.NotificationCenter.Models.Data;
using Bit.Core.NotificationCenter.Models.Filter;
using Bit.Core.NotificationCenter.Repositories;
using Bit.Core.Settings;
@ -23,12 +24,12 @@ public class NotificationRepository : Repository<Notification, Guid>, INotificat
{
}
public async Task<IEnumerable<Notification>> GetByUserIdAndStatusAsync(Guid userId,
public async Task<IEnumerable<NotificationStatusDetails>> GetByUserIdAndStatusAsync(Guid userId,
ClientType clientType, NotificationStatusFilter? statusFilter)
{
await using var connection = new SqlConnection(ConnectionString);
var results = await connection.QueryAsync<Notification>(
var results = await connection.QueryAsync<NotificationStatusDetails>(
"[dbo].[Notification_ReadByUserIdAndStatus]",
new { UserId = userId, ClientType = clientType, statusFilter?.Read, statusFilter?.Deleted },
commandType: CommandType.StoredProcedure);

View File

@ -12,10 +12,6 @@ public class OrganizationEntityTypeConfiguration : IEntityTypeConfiguration<Orga
.Property(o => o.Id)
.ValueGeneratedNever();
builder.Property(c => c.LimitCollectionCreationDeletion)
.ValueGeneratedNever()
.HasDefaultValue(true);
builder.Property(c => c.AllowAdminAccessToAllCollectionItems)
.ValueGeneratedNever()
.HasDefaultValue(true);

View File

@ -9,6 +9,10 @@ namespace Bit.Infrastructure.EntityFramework.AdminConsole.Models;
public class Organization : Core.AdminConsole.Entities.Organization
{
// Shadow properties - to be introduced by https://bitwarden.atlassian.net/browse/PM-10863
public bool LimitCollectionCreation { get => LimitCollectionCreationDeletion; set => LimitCollectionCreationDeletion = value; }
public bool LimitCollectionDeletion { get => LimitCollectionCreationDeletion; set => LimitCollectionCreationDeletion = value; }
public virtual ICollection<Cipher> Ciphers { get; set; }
public virtual ICollection<OrganizationUser> OrganizationUsers { get; set; }
public virtual ICollection<Group> Groups { get; set; }
@ -38,6 +42,9 @@ public class OrganizationMapperProfile : Profile
.ForMember(org => org.ApiKeys, opt => opt.Ignore())
.ForMember(org => org.Connections, opt => opt.Ignore())
.ForMember(org => org.Domains, opt => opt.Ignore())
// Shadow properties - to be introduced by https://bitwarden.atlassian.net/browse/PM-10863
.ForMember(org => org.LimitCollectionCreation, opt => opt.Ignore())
.ForMember(org => org.LimitCollectionDeletion, opt => opt.Ignore())
.ReverseMap();
CreateProjection<Organization, SelfHostedOrganizationDetails>()

View File

@ -1,9 +1,11 @@
#nullable enable
using AutoMapper;
using Bit.Core.Enums;
using Bit.Core.NotificationCenter.Models.Data;
using Bit.Core.NotificationCenter.Models.Filter;
using Bit.Core.NotificationCenter.Repositories;
using Bit.Infrastructure.EntityFramework.NotificationCenter.Models;
using Bit.Infrastructure.EntityFramework.NotificationCenter.Repositories.Queries;
using Bit.Infrastructure.EntityFramework.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
@ -20,34 +22,13 @@ public class NotificationRepository : Repository<Core.NotificationCenter.Entitie
public async Task<IEnumerable<Core.NotificationCenter.Entities.Notification>> GetByUserIdAsync(Guid userId,
ClientType clientType)
{
return await GetByUserIdAndStatusAsync(userId, clientType, new NotificationStatusFilter());
}
public async Task<IEnumerable<Core.NotificationCenter.Entities.Notification>> GetByUserIdAndStatusAsync(Guid userId,
ClientType clientType, NotificationStatusFilter? statusFilter)
{
await using var scope = ServiceScopeFactory.CreateAsyncScope();
var dbContext = GetDatabaseContext(scope);
var notificationQuery = BuildNotificationQuery(dbContext, userId, clientType);
var notificationStatusDetailsViewQuery = new NotificationStatusDetailsViewQuery(userId, clientType);
if (statusFilter != null && (statusFilter.Read != null || statusFilter.Deleted != null))
{
notificationQuery = from n in notificationQuery
join ns in dbContext.NotificationStatuses on n.Id equals ns.NotificationId
where
ns.UserId == userId &&
(
statusFilter.Read == null ||
(statusFilter.Read == true ? ns.ReadDate != null : ns.ReadDate == null) ||
statusFilter.Deleted == null ||
(statusFilter.Deleted == true ? ns.DeletedDate != null : ns.DeletedDate == null)
)
select n;
}
var notifications = await notificationQuery
var notifications = await notificationStatusDetailsViewQuery.Run(dbContext)
.OrderByDescending(n => n.Priority)
.ThenByDescending(n => n.CreationDate)
.ToListAsync();
@ -55,38 +36,28 @@ public class NotificationRepository : Repository<Core.NotificationCenter.Entitie
return Mapper.Map<List<Core.NotificationCenter.Entities.Notification>>(notifications);
}
private static IQueryable<Notification> BuildNotificationQuery(DatabaseContext dbContext, Guid userId,
ClientType clientType)
public async Task<IEnumerable<NotificationStatusDetails>> GetByUserIdAndStatusAsync(Guid userId,
ClientType clientType, NotificationStatusFilter? statusFilter)
{
var clientTypes = new[] { ClientType.All };
if (clientType != ClientType.All)
await using var scope = ServiceScopeFactory.CreateAsyncScope();
var dbContext = GetDatabaseContext(scope);
var notificationStatusDetailsViewQuery = new NotificationStatusDetailsViewQuery(userId, clientType);
var query = notificationStatusDetailsViewQuery.Run(dbContext);
if (statusFilter != null && (statusFilter.Read != null || statusFilter.Deleted != null))
{
clientTypes = [ClientType.All, clientType];
query = from n in query
where statusFilter.Read == null ||
(statusFilter.Read == true ? n.ReadDate != null : n.ReadDate == null) ||
statusFilter.Deleted == null ||
(statusFilter.Deleted == true ? n.DeletedDate != null : n.DeletedDate == null)
select n;
}
return from n in dbContext.Notifications
join ou in dbContext.OrganizationUsers.Where(ou => ou.UserId == userId)
on n.OrganizationId equals ou.OrganizationId into grouping
from ou in grouping.DefaultIfEmpty()
where
clientTypes.Contains(n.ClientType) &&
(
(
n.Global &&
n.UserId == null &&
n.OrganizationId == null
) ||
(
!n.Global &&
n.UserId == userId &&
(n.OrganizationId == null || ou != null)
) ||
(
!n.Global &&
n.UserId == null &&
ou != null
)
)
select n;
return await query
.OrderByDescending(n => n.Priority)
.ThenByDescending(n => n.CreationDate)
.ToListAsync();
}
}

View File

@ -0,0 +1,63 @@
#nullable enable
using Bit.Core.Enums;
using Bit.Core.NotificationCenter.Models.Data;
using Bit.Infrastructure.EntityFramework.Repositories;
using Bit.Infrastructure.EntityFramework.Repositories.Queries;
namespace Bit.Infrastructure.EntityFramework.NotificationCenter.Repositories.Queries;
public class NotificationStatusDetailsViewQuery(Guid userId, ClientType clientType) : IQuery<NotificationStatusDetails>
{
public IQueryable<NotificationStatusDetails> Run(DatabaseContext dbContext)
{
var clientTypes = new[] { ClientType.All };
if (clientType != ClientType.All)
{
clientTypes = [ClientType.All, clientType];
}
var query = from n in dbContext.Notifications
join ou in dbContext.OrganizationUsers.Where(ou => ou.UserId == userId)
on n.OrganizationId equals ou.OrganizationId into groupingOrganizationUsers
from ou in groupingOrganizationUsers.DefaultIfEmpty()
join ns in dbContext.NotificationStatuses.Where(ns => ns.UserId == userId) on n.Id equals ns.NotificationId
into groupingNotificationStatus
from ns in groupingNotificationStatus.DefaultIfEmpty()
where
clientTypes.Contains(n.ClientType) &&
(
(
n.Global &&
n.UserId == null &&
n.OrganizationId == null
) ||
(
!n.Global &&
n.UserId == userId &&
(n.OrganizationId == null || ou != null)
) ||
(
!n.Global &&
n.UserId == null &&
ou != null
)
)
select new { n, ns };
return query.Select(x => new NotificationStatusDetails
{
Id = x.n.Id,
Priority = x.n.Priority,
Global = x.n.Global,
ClientType = x.n.ClientType,
UserId = x.n.UserId,
OrganizationId = x.n.OrganizationId,
Title = x.n.Title,
Body = x.n.Body,
CreationDate = x.n.CreationDate,
RevisionDate = x.n.RevisionDate,
ReadDate = x.ns != null ? x.ns.ReadDate : null,
DeletedDate = x.ns != null ? x.ns.DeletedDate : null,
});
}
}

View File

@ -0,0 +1,117 @@
using System.Collections;
using Bit.Core;
using Bit.Core.Services;
using Bit.Core.Settings;
using Bit.Core.Utilities;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
#nullable enable
namespace Bit.SharedWeb.Utilities;
public sealed class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestLoggingMiddleware> _logger;
private readonly GlobalSettings _globalSettings;
public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger, GlobalSettings globalSettings)
{
_next = next;
_logger = logger;
_globalSettings = globalSettings;
}
public Task Invoke(HttpContext context, IFeatureService featureService)
{
if (!featureService.IsEnabled(FeatureFlagKeys.RemoveServerVersionHeader))
{
context.Response.OnStarting(() =>
{
context.Response.Headers.Append("Server-Version", AssemblyHelpers.GetVersion());
return Task.CompletedTask;
});
}
using (_logger.BeginScope(
new RequestLogScope(context.GetIpAddress(_globalSettings),
GetHeaderValue(context, "user-agent"),
GetHeaderValue(context, "device-type"),
GetHeaderValue(context, "device-type"))))
{
return _next(context);
}
static string? GetHeaderValue(HttpContext httpContext, string header)
{
if (httpContext.Request.Headers.TryGetValue(header, out var value))
{
return value;
}
return null;
}
}
private sealed class RequestLogScope : IReadOnlyList<KeyValuePair<string, object?>>
{
private string? _cachedToString;
public RequestLogScope(string? ipAddress, string? userAgent, string? deviceType, string? origin)
{
IpAddress = ipAddress;
UserAgent = userAgent;
DeviceType = deviceType;
Origin = origin;
}
public KeyValuePair<string, object?> this[int index]
{
get
{
if (index == 0)
{
return new KeyValuePair<string, object?>(nameof(IpAddress), IpAddress);
}
else if (index == 1)
{
return new KeyValuePair<string, object?>(nameof(UserAgent), UserAgent);
}
else if (index == 2)
{
return new KeyValuePair<string, object?>(nameof(DeviceType), DeviceType);
}
else if (index == 3)
{
return new KeyValuePair<string, object?>(nameof(Origin), Origin);
}
throw new ArgumentOutOfRangeException(nameof(index));
}
}
public int Count => 4;
public string? IpAddress { get; }
public string? UserAgent { get; }
public string? DeviceType { get; }
public string? Origin { get; }
public IEnumerator<KeyValuePair<string, object?>> GetEnumerator()
{
for (var i = 0; i < Count; i++)
{
yield return this[i];
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public override string ToString()
{
_cachedToString ??= $"IpAddress:{IpAddress} UserAgent:{UserAgent} DeviceType:{DeviceType} Origin:{Origin}";
return _cachedToString;
}
}
}

View File

@ -48,7 +48,6 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Localization;
@ -60,7 +59,6 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Serilog.Context;
using StackExchange.Redis;
using NoopRepos = Bit.Core.Repositories.Noop;
using Role = Bit.Core.Entities.Role;
@ -540,31 +538,7 @@ public static class ServiceCollectionExtensions
public static void UseDefaultMiddleware(this IApplicationBuilder app,
IWebHostEnvironment env, GlobalSettings globalSettings)
{
string GetHeaderValue(HttpContext httpContext, string header)
{
if (httpContext.Request.Headers.ContainsKey(header))
{
return httpContext.Request.Headers[header];
}
return null;
}
// Add version information to response headers
app.Use(async (httpContext, next) =>
{
using (LogContext.PushProperty("IPAddress", httpContext.GetIpAddress(globalSettings)))
using (LogContext.PushProperty("UserAgent", GetHeaderValue(httpContext, "user-agent")))
using (LogContext.PushProperty("DeviceType", GetHeaderValue(httpContext, "device-type")))
using (LogContext.PushProperty("Origin", GetHeaderValue(httpContext, "origin")))
{
httpContext.Response.OnStarting((state) =>
{
httpContext.Response.Headers.Append("Server-Version", AssemblyHelpers.GetVersion());
return Task.FromResult(0);
}, null);
await next.Invoke();
}
});
app.UseMiddleware<RequestLoggingMiddleware>();
}
public static void UseForwardedHeaders(this IApplicationBuilder app, IGlobalSettings globalSettings)

View File

@ -8,12 +8,11 @@ BEGIN
SET NOCOUNT ON
SELECT n.*
FROM [dbo].[NotificationView] n
FROM [dbo].[NotificationStatusDetailsView] n
LEFT JOIN [dbo].[OrganizationUserView] ou ON n.[OrganizationId] = ou.[OrganizationId]
AND ou.[UserId] = @UserId
LEFT JOIN [dbo].[NotificationStatusView] ns ON n.[Id] = ns.[NotificationId]
AND ns.[UserId] = @UserId
WHERE [ClientType] IN (0, CASE WHEN @ClientType != 0 THEN @ClientType END)
WHERE (n.[NotificationStatusUserId] IS NULL OR n.[NotificationStatusUserId] = @UserId)
AND [ClientType] IN (0, CASE WHEN @ClientType != 0 THEN @ClientType END)
AND ([Global] = 1
OR (n.[UserId] = @UserId
AND (n.[OrganizationId] IS NULL
@ -21,14 +20,14 @@ BEGIN
OR (n.[UserId] IS NULL
AND ou.[OrganizationId] IS NOT NULL))
AND ((@Read IS NULL AND @Deleted IS NULL)
OR (ns.[NotificationId] IS NOT NULL
OR (n.[NotificationStatusUserId] IS NOT NULL
AND ((@Read IS NULL
OR IIF((@Read = 1 AND ns.[ReadDate] IS NOT NULL) OR
(@Read = 0 AND ns.[ReadDate] IS NULL),
OR IIF((@Read = 1 AND n.[ReadDate] IS NOT NULL) OR
(@Read = 0 AND n.[ReadDate] IS NULL),
1, 0) = 1)
OR (@Deleted IS NULL
OR IIF((@Deleted = 1 AND ns.[DeletedDate] IS NOT NULL) OR
(@Deleted = 0 AND ns.[DeletedDate] IS NULL),
OR IIF((@Deleted = 1 AND n.[DeletedDate] IS NOT NULL) OR
(@Deleted = 0 AND n.[DeletedDate] IS NULL),
1, 0) = 1))))
ORDER BY [Priority] DESC, n.[CreationDate] DESC
END

View File

@ -0,0 +1,13 @@
CREATE VIEW [dbo].[NotificationStatusDetailsView]
AS
SELECT
N.*,
NS.UserId AS NotificationStatusUserId,
NS.ReadDate,
NS.DeletedDate
FROM
[dbo].[Notification] AS N
LEFT JOIN
[dbo].[NotificationStatus] as NS
ON
N.[Id] = NS.[NotificationId]

View File

@ -1,4 +1,4 @@
CREATE PROCEDURE [dbo].[Organization_Create]
CREATE PROCEDURE [dbo].[Organization_Create]
@Id UNIQUEIDENTIFIER OUTPUT,
@Identifier NVARCHAR(50),
@Name NVARCHAR(50),
@ -51,12 +51,17 @@
@MaxAutoscaleSmSeats INT= null,
@MaxAutoscaleSmServiceAccounts INT = null,
@SecretsManagerBeta BIT = 0,
@LimitCollectionCreationDeletion BIT = 0,
@LimitCollectionCreationDeletion BIT = NULL, -- Deprecated https://bitwarden.atlassian.net/browse/PM-10863
@LimitCollectionCreation BIT = NULL,
@LimitCollectionDeletion BIT = NULL,
@AllowAdminAccessToAllCollectionItems BIT = 0
AS
BEGIN
SET NOCOUNT ON
SET @LimitCollectionCreation = COALESCE(@LimitCollectionCreation, @LimitCollectionCreationDeletion, 0);
SET @LimitCollectionDeletion = COALESCE(@LimitCollectionDeletion, @LimitCollectionCreationDeletion, 0);
INSERT INTO [dbo].[Organization]
(
[Id],
@ -111,7 +116,9 @@ BEGIN
[MaxAutoscaleSmSeats],
[MaxAutoscaleSmServiceAccounts],
[SecretsManagerBeta],
[LimitCollectionCreationDeletion],
[LimitCollectionCreationDeletion], -- Deprecated https://bitwarden.atlassian.net/browse/PM-10863
[LimitCollectionCreation],
[LimitCollectionDeletion],
[AllowAdminAccessToAllCollectionItems]
)
VALUES
@ -168,7 +175,9 @@ BEGIN
@MaxAutoscaleSmSeats,
@MaxAutoscaleSmServiceAccounts,
@SecretsManagerBeta,
@LimitCollectionCreationDeletion,
COALESCE(@LimitCollectionCreation, @LimitCollectionDeletion, 0), -- Deprecated https://bitwarden.atlassian.net/browse/PM-10863)
@LimitCollectionCreation,
@LimitCollectionDeletion,
@AllowAdminAccessToAllCollectionItems
)
END

View File

@ -1,4 +1,4 @@
CREATE PROCEDURE [dbo].[Organization_ReadAbilities]
CREATE PROCEDURE [dbo].[Organization_ReadAbilities]
AS
BEGIN
SET NOCOUNT ON
@ -21,7 +21,9 @@ BEGIN
[UseResetPassword],
[UsePolicies],
[Enabled],
[LimitCollectionCreationDeletion],
[LimitCollectionCreationDeletion], -- Deprecated https://bitwarden.atlassian.net/browse/PM-10863
[LimitCollectionCreation],
[LimitCollectionDeletion],
[AllowAdminAccessToAllCollectionItems]
FROM
[dbo].[Organization]

View File

@ -1,4 +1,4 @@
CREATE PROCEDURE [dbo].[Organization_Update]
CREATE PROCEDURE [dbo].[Organization_Update]
@Id UNIQUEIDENTIFIER,
@Identifier NVARCHAR(50),
@Name NVARCHAR(50),
@ -51,12 +51,17 @@
@MaxAutoscaleSmSeats INT = null,
@MaxAutoscaleSmServiceAccounts INT = null,
@SecretsManagerBeta BIT = 0,
@LimitCollectionCreationDeletion BIT = 0,
@LimitCollectionCreationDeletion BIT = null, -- Deprecated https://bitwarden.atlassian.net/browse/PM-10863
@LimitCollectionCreation BIT = null,
@LimitCollectionDeletion BIT = null,
@AllowAdminAccessToAllCollectionItems BIT = 0
AS
BEGIN
SET NOCOUNT ON
SET @LimitCollectionCreation = COALESCE(@LimitCollectionCreation, @LimitCollectionCreationDeletion, 0);
SET @LimitCollectionDeletion = COALESCE(@LimitCollectionDeletion, @LimitCollectionCreationDeletion, 0);
UPDATE
[dbo].[Organization]
SET
@ -111,7 +116,9 @@ BEGIN
[MaxAutoscaleSmSeats] = @MaxAutoscaleSmSeats,
[MaxAutoscaleSmServiceAccounts] = @MaxAutoscaleSmServiceAccounts,
[SecretsManagerBeta] = @SecretsManagerBeta,
[LimitCollectionCreationDeletion] = @LimitCollectionCreationDeletion,
[LimitCollectionCreationDeletion] = COALESCE(@LimitCollectionCreation, @LimitCollectionDeletion, 0),
[LimitCollectionCreation] = @LimitCollectionCreation,
[LimitCollectionDeletion] = @LimitCollectionDeletion,
[AllowAdminAccessToAllCollectionItems] = @AllowAdminAccessToAllCollectionItems
WHERE
[Id] = @Id

View File

@ -1,4 +1,4 @@
CREATE TABLE [dbo].[Organization] (
CREATE TABLE [dbo].[Organization] (
[Id] UNIQUEIDENTIFIER NOT NULL,
[Identifier] NVARCHAR (50) NULL,
[Name] NVARCHAR (50) NOT NULL,
@ -52,6 +52,8 @@
[MaxAutoscaleSmServiceAccounts] INT NULL,
[SecretsManagerBeta] BIT NOT NULL CONSTRAINT [DF_Organization_SecretsManagerBeta] DEFAULT (0),
[LimitCollectionCreationDeletion] BIT NOT NULL CONSTRAINT [DF_Organization_LimitCollectionCreationDeletion] DEFAULT (0),
[LimitCollectionCreation] BIT NOT NULL CONSTRAINT [DF_Organization_LimitCollectionCreation] DEFAULT (0),
[LimitCollectionDeletion] BIT NOT NULL CONSTRAINT [DF_Organization_LimitCollectionDeletion] DEFAULT (0),
[AllowAdminAccessToAllCollectionItems] BIT NOT NULL CONSTRAINT [DF_Organization_AllowAdminAccessToAllCollectionItems] DEFAULT (0),
CONSTRAINT [PK_Organization] PRIMARY KEY CLUSTERED ([Id] ASC)
);

View File

@ -1,4 +1,4 @@
CREATE VIEW [dbo].[OrganizationUserOrganizationDetailsView]
CREATE VIEW [dbo].[OrganizationUserOrganizationDetailsView]
AS
SELECT
OU.[UserId],
@ -46,7 +46,9 @@ SELECT
O.[UsePasswordManager],
O.[SmSeats],
O.[SmServiceAccounts],
O.[LimitCollectionCreationDeletion],
O.[LimitCollectionCreationDeletion], -- Deprecated https://bitwarden.atlassian.net/browse/PM-10863
O.[LimitCollectionCreation],
O.[LimitCollectionDeletion],
O.[AllowAdminAccessToAllCollectionItems]
FROM
[dbo].[OrganizationUser] OU

View File

@ -1,4 +1,4 @@
CREATE VIEW [dbo].[ProviderUserProviderOrganizationDetailsView]
CREATE VIEW [dbo].[ProviderUserProviderOrganizationDetailsView]
AS
SELECT
PU.[UserId],
@ -32,7 +32,9 @@ SELECT
PU.[Id] ProviderUserId,
P.[Name] ProviderName,
O.[PlanType],
O.[LimitCollectionCreationDeletion],
O.[LimitCollectionCreationDeletion], -- Deprecated https://bitwarden.atlassian.net/browse/PM-10863
O.[LimitCollectionCreation],
O.[LimitCollectionDeletion],
O.[AllowAdminAccessToAllCollectionItems]
FROM
[dbo].[ProviderUser] PU

View File

@ -0,0 +1,419 @@
#nullable enable
using Bit.Core.Context;
using Bit.Core.Test.NotificationCenter.AutoFixture;
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
namespace Bit.Core.Test.NotificationCenter.Authorization;
using System.Security.Claims;
using Bit.Core.NotificationCenter.Authorization;
using Bit.Core.NotificationCenter.Entities;
using Microsoft.AspNetCore.Authorization;
using NSubstitute;
using Xunit;
[SutProviderCustomize]
[NotificationCustomize]
public class NotificationAuthorizationHandlerTests
{
private static void SetupUserPermission(SutProvider<NotificationAuthorizationHandler> sutProvider,
Guid? userId = null, Guid? organizationId = null, bool canAccessReports = false)
{
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
sutProvider.GetDependency<ICurrentContext>().GetOrganization(organizationId.GetValueOrDefault(Guid.NewGuid()))
.Returns(new CurrentContextOrganization());
sutProvider.GetDependency<ICurrentContext>().AccessReports(organizationId.GetValueOrDefault(Guid.NewGuid()))
.Returns(canAccessReports);
}
[Theory]
[BitAutoData]
public async Task HandleAsync_UnsupportedNotificationOperationRequirement_Throws(
SutProvider<NotificationAuthorizationHandler> sutProvider,
Notification notification, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, Guid.NewGuid());
var requirement = new NotificationOperationsRequirement("UnsupportedOperation");
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notification);
await Assert.ThrowsAsync<ArgumentException>(() => sutProvider.Sut.HandleAsync(context));
}
[Theory]
[BitAutoData(nameof(NotificationOperations.Read))]
[BitAutoData(nameof(NotificationOperations.Create))]
[BitAutoData(nameof(NotificationOperations.Update))]
public async Task HandleAsync_NotLoggedIn_Unauthorized(
string requirementName,
SutProvider<NotificationAuthorizationHandler> sutProvider,
Notification notification, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, userId: null);
var requirement = new NotificationOperationsRequirement(requirementName);
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notification);
await sutProvider.Sut.HandleAsync(context);
Assert.False(context.HasSucceeded);
}
[Theory]
[BitAutoData(nameof(NotificationOperations.Read))]
[BitAutoData(nameof(NotificationOperations.Create))]
[BitAutoData(nameof(NotificationOperations.Update))]
public async Task HandleAsync_ResourceEmpty_Unauthorized(
string requirementName,
SutProvider<NotificationAuthorizationHandler> sutProvider,
ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, Guid.NewGuid());
var requirement = new NotificationOperationsRequirement(requirementName);
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, null);
await sutProvider.Sut.HandleAsync(context);
Assert.False(context.HasSucceeded);
}
[Theory]
[BitAutoData]
[NotificationCustomize(global: true)]
public async Task HandleAsync_ReadRequirementGlobalNotification_Authorized(
SutProvider<NotificationAuthorizationHandler> sutProvider,
Notification notification, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, Guid.NewGuid());
var requirement = NotificationOperations.Read;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notification);
await sutProvider.Sut.HandleAsync(context);
Assert.True(context.HasSucceeded);
}
[Theory]
[BitAutoData(false)]
[BitAutoData(true)]
[NotificationCustomize(global: false)]
public async Task HandleAsync_ReadRequirementUserNotMatching_Unauthorized(
bool hasOrganizationId,
SutProvider<NotificationAuthorizationHandler> sutProvider,
Notification notification, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, Guid.NewGuid(), notification.OrganizationId);
if (!hasOrganizationId)
{
notification.OrganizationId = null;
}
var requirement = NotificationOperations.Read;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notification);
await sutProvider.Sut.HandleAsync(context);
Assert.False(context.HasSucceeded);
}
[Theory]
[BitAutoData]
[BitAutoData(false)]
[BitAutoData(true)]
[NotificationCustomize(global: false)]
public async Task HandleAsync_ReadRequirementOrganizationNotMatching_Unauthorized(
bool hasUserId,
SutProvider<NotificationAuthorizationHandler> sutProvider,
Notification notification, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, notification.UserId, Guid.NewGuid());
if (!hasUserId)
{
notification.UserId = null;
}
var requirement = NotificationOperations.Read;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notification);
await sutProvider.Sut.HandleAsync(context);
Assert.False(context.HasSucceeded);
}
[Theory]
[BitAutoData(false, true)]
[BitAutoData(true, false)]
[BitAutoData(true, true)]
[NotificationCustomize(global: false)]
public async Task HandleAsync_ReadRequirement_Authorized(
bool hasUserId,
bool hasOrganizationId,
SutProvider<NotificationAuthorizationHandler> sutProvider,
Notification notification, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, notification.UserId, notification.OrganizationId);
if (!hasUserId)
{
notification.UserId = null;
}
if (!hasOrganizationId)
{
notification.OrganizationId = null;
}
var requirement = NotificationOperations.Read;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notification);
await sutProvider.Sut.HandleAsync(context);
Assert.True(context.HasSucceeded);
}
[Theory]
[BitAutoData]
[NotificationCustomize(global: true)]
public async Task HandleAsync_CreateRequirementGlobalNotification_Unauthorized(
SutProvider<NotificationAuthorizationHandler> sutProvider,
Notification notification, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, Guid.NewGuid());
var requirement = NotificationOperations.Create;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notification);
await sutProvider.Sut.HandleAsync(context);
Assert.False(context.HasSucceeded);
}
[Theory]
[BitAutoData]
[NotificationCustomize(global: false)]
public async Task HandleAsync_CreateRequirementUserNotMatching_Unauthorized(
SutProvider<NotificationAuthorizationHandler> sutProvider,
Notification notification, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, Guid.NewGuid(), notification.OrganizationId);
notification.OrganizationId = null;
var requirement = NotificationOperations.Create;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notification);
await sutProvider.Sut.HandleAsync(context);
Assert.False(context.HasSucceeded);
}
[Theory]
[BitAutoData]
[NotificationCustomize(global: false)]
public async Task HandleAsync_CreateRequirementOrganizationNotMatching_Unauthorized(
SutProvider<NotificationAuthorizationHandler> sutProvider,
Notification notification, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, notification.UserId, Guid.NewGuid());
var requirement = NotificationOperations.Create;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notification);
await sutProvider.Sut.HandleAsync(context);
Assert.False(context.HasSucceeded);
}
[Theory]
[BitAutoData]
[NotificationCustomize(global: false)]
public async Task HandleAsync_CreateRequirementOrganizationUserNoAccessReportsPermission_Unauthorized(
SutProvider<NotificationAuthorizationHandler> sutProvider,
Notification notification, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, notification.UserId, notification.OrganizationId, canAccessReports: false);
var requirement = NotificationOperations.Create;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notification);
await sutProvider.Sut.HandleAsync(context);
Assert.False(context.HasSucceeded);
}
[Theory]
[BitAutoData]
[NotificationCustomize(global: false)]
public async Task HandleAsync_CreateRequirementUserNotPartOfOrganization_Authorized(
SutProvider<NotificationAuthorizationHandler> sutProvider,
Notification notification, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, notification.UserId);
notification.OrganizationId = null;
var requirement = NotificationOperations.Create;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notification);
await sutProvider.Sut.HandleAsync(context);
Assert.True(context.HasSucceeded);
}
[Theory]
[BitAutoData(false)]
[BitAutoData(true)]
[NotificationCustomize(global: false)]
public async Task HandleAsync_CreateRequirementOrganizationUserCanAccessReports_Authorized(
bool hasUserId,
SutProvider<NotificationAuthorizationHandler> sutProvider,
Notification notification, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, notification.UserId, notification.OrganizationId, true);
if (!hasUserId)
{
notification.UserId = null;
}
var requirement = NotificationOperations.Create;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notification);
await sutProvider.Sut.HandleAsync(context);
Assert.True(context.HasSucceeded);
}
// TODO
[Theory]
[BitAutoData]
[NotificationCustomize(global: true)]
public async Task HandleAsync_UpdateRequirementGlobalNotification_Unauthorized(
SutProvider<NotificationAuthorizationHandler> sutProvider,
Notification notification, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, Guid.NewGuid());
var requirement = NotificationOperations.Update;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notification);
await sutProvider.Sut.HandleAsync(context);
Assert.False(context.HasSucceeded);
}
[Theory]
[BitAutoData]
[NotificationCustomize(global: false)]
public async Task HandleAsync_UpdateRequirementUserNotMatching_Unauthorized(
SutProvider<NotificationAuthorizationHandler> sutProvider,
Notification notification, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, Guid.NewGuid(), notification.OrganizationId);
notification.OrganizationId = null;
var requirement = NotificationOperations.Update;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notification);
await sutProvider.Sut.HandleAsync(context);
Assert.False(context.HasSucceeded);
}
[Theory]
[BitAutoData]
[NotificationCustomize(global: false)]
public async Task HandleAsync_UpdateRequirementOrganizationNotMatching_Unauthorized(
SutProvider<NotificationAuthorizationHandler> sutProvider,
Notification notification, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, notification.UserId, Guid.NewGuid());
var requirement = NotificationOperations.Update;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notification);
await sutProvider.Sut.HandleAsync(context);
Assert.False(context.HasSucceeded);
}
[Theory]
[BitAutoData]
[NotificationCustomize(global: false)]
public async Task HandleAsync_UpdateRequirementOrganizationUserNoAccessReportsPermission_Unauthorized(
SutProvider<NotificationAuthorizationHandler> sutProvider,
Notification notification, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, notification.UserId, notification.OrganizationId, canAccessReports: false);
var requirement = NotificationOperations.Update;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notification);
await sutProvider.Sut.HandleAsync(context);
Assert.False(context.HasSucceeded);
}
[Theory]
[BitAutoData]
[NotificationCustomize(global: false)]
public async Task HandleAsync_UpdateRequirementUserNotPartOfOrganization_Authorized(
SutProvider<NotificationAuthorizationHandler> sutProvider,
Notification notification, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, notification.UserId);
notification.OrganizationId = null;
var requirement = NotificationOperations.Update;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notification);
await sutProvider.Sut.HandleAsync(context);
Assert.True(context.HasSucceeded);
}
[Theory]
[BitAutoData(false)]
[BitAutoData(true)]
[NotificationCustomize(global: false)]
public async Task HandleAsync_UpdateRequirementOrganizationUserCanAccessReports_Authorized(
bool hasUserId,
SutProvider<NotificationAuthorizationHandler> sutProvider,
Notification notification, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, notification.UserId, notification.OrganizationId, true);
if (!hasUserId)
{
notification.UserId = null;
}
var requirement = NotificationOperations.Update;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notification);
await sutProvider.Sut.HandleAsync(context);
Assert.True(context.HasSucceeded);
}
}

View File

@ -0,0 +1,179 @@
#nullable enable
using Bit.Core.Context;
using Bit.Core.Test.NotificationCenter.AutoFixture;
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
namespace Bit.Core.Test.NotificationCenter.Authorization;
using System.Security.Claims;
using Bit.Core.NotificationCenter.Authorization;
using Bit.Core.NotificationCenter.Entities;
using Microsoft.AspNetCore.Authorization;
using NSubstitute;
using Xunit;
[SutProviderCustomize]
[NotificationStatusCustomize]
public class NotificationStatusAuthorizationHandlerTests
{
private static void SetupUserPermission(SutProvider<NotificationStatusAuthorizationHandler> sutProvider,
Guid? userId = null)
{
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
}
[Theory]
[BitAutoData]
public async Task HandleAsync_UnsupportedNotificationOperationRequirement_Throws(
SutProvider<NotificationStatusAuthorizationHandler> sutProvider,
NotificationStatus notificationStatus, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, Guid.NewGuid());
var requirement = new NotificationStatusOperationsRequirement("UnsupportedOperation");
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notificationStatus);
await Assert.ThrowsAsync<ArgumentException>(() => sutProvider.Sut.HandleAsync(context));
}
[Theory]
[BitAutoData(nameof(NotificationStatusOperations.Read))]
[BitAutoData(nameof(NotificationStatusOperations.Create))]
[BitAutoData(nameof(NotificationStatusOperations.Update))]
public async Task HandleAsync_NotLoggedIn_Unauthorized(
string requirementName,
SutProvider<NotificationStatusAuthorizationHandler> sutProvider,
NotificationStatus notificationStatus, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, userId: null);
var requirement = new NotificationStatusOperationsRequirement(requirementName);
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notificationStatus);
await sutProvider.Sut.HandleAsync(context);
Assert.False(context.HasSucceeded);
}
[Theory]
[BitAutoData(nameof(NotificationStatusOperations.Read))]
[BitAutoData(nameof(NotificationStatusOperations.Create))]
[BitAutoData(nameof(NotificationStatusOperations.Update))]
public async Task HandleAsync_ResourceEmpty_Unauthorized(
string requirementName,
SutProvider<NotificationStatusAuthorizationHandler> sutProvider,
ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, Guid.NewGuid());
var requirement = new NotificationStatusOperationsRequirement(requirementName);
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, null);
await sutProvider.Sut.HandleAsync(context);
Assert.False(context.HasSucceeded);
}
[Theory]
[BitAutoData]
public async Task HandleAsync_ReadRequirementUserNotMatching_Unauthorized(
SutProvider<NotificationStatusAuthorizationHandler> sutProvider,
NotificationStatus notificationStatus, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, Guid.NewGuid());
var requirement = NotificationStatusOperations.Read;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notificationStatus);
await sutProvider.Sut.HandleAsync(context);
Assert.False(context.HasSucceeded);
}
[Theory]
[BitAutoData]
public async Task HandleAsync_ReadRequirement_Authorized(
SutProvider<NotificationStatusAuthorizationHandler> sutProvider,
NotificationStatus notificationStatus, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, notificationStatus.UserId);
var requirement = NotificationStatusOperations.Read;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notificationStatus);
await sutProvider.Sut.HandleAsync(context);
Assert.True(context.HasSucceeded);
}
[Theory]
[BitAutoData]
public async Task HandleAsync_CreateRequirementUserNotMatching_Unauthorized(
SutProvider<NotificationStatusAuthorizationHandler> sutProvider,
NotificationStatus notificationStatus, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, Guid.NewGuid());
var requirement = NotificationStatusOperations.Create;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notificationStatus);
await sutProvider.Sut.HandleAsync(context);
Assert.False(context.HasSucceeded);
}
[Theory]
[BitAutoData]
public async Task HandleAsync_CreateRequirement_Authorized(
SutProvider<NotificationStatusAuthorizationHandler> sutProvider,
NotificationStatus notificationStatus, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, notificationStatus.UserId);
var requirement = NotificationStatusOperations.Create;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notificationStatus);
await sutProvider.Sut.HandleAsync(context);
Assert.True(context.HasSucceeded);
}
[Theory]
[BitAutoData]
public async Task HandleAsync_UpdateRequirementUserNotMatching_Unauthorized(
SutProvider<NotificationStatusAuthorizationHandler> sutProvider,
NotificationStatus notificationStatus, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, Guid.NewGuid());
var requirement = NotificationStatusOperations.Update;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notificationStatus);
await sutProvider.Sut.HandleAsync(context);
Assert.False(context.HasSucceeded);
}
[Theory]
[BitAutoData]
public async Task HandleAsync_UpdateRequirement_Authorized(
SutProvider<NotificationStatusAuthorizationHandler> sutProvider,
NotificationStatus notificationStatus, ClaimsPrincipal claimsPrincipal)
{
SetupUserPermission(sutProvider, notificationStatus.UserId);
var requirement = NotificationStatusOperations.Update;
var context = new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement },
claimsPrincipal, notificationStatus);
await sutProvider.Sut.HandleAsync(context);
Assert.True(context.HasSucceeded);
}
}

View File

@ -0,0 +1,31 @@
#nullable enable
using AutoFixture;
using Bit.Core.NotificationCenter.Entities;
using Bit.Test.Common.AutoFixture.Attributes;
namespace Bit.Core.Test.NotificationCenter.AutoFixture;
public class NotificationCustomization(bool global) : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<Notification>(composer =>
{
var postprocessComposer = composer.With(n => n.Id, Guid.NewGuid())
.With(n => n.Global, global);
postprocessComposer = global
? postprocessComposer.Without(n => n.UserId)
: postprocessComposer.With(n => n.UserId, Guid.NewGuid());
return global
? postprocessComposer.Without(n => n.OrganizationId)
: postprocessComposer.With(n => n.OrganizationId, Guid.NewGuid());
});
}
}
public class NotificationCustomizeAttribute(bool global = true) : BitCustomizeAttribute
{
public override ICustomization GetCustomization() => new NotificationCustomization(global);
}

View File

@ -0,0 +1,21 @@
#nullable enable
using AutoFixture;
using Bit.Core.NotificationCenter.Models.Data;
using Bit.Test.Common.AutoFixture.Attributes;
namespace Bit.Core.Test.NotificationCenter.AutoFixture;
public class NotificationStatusDetailsCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<NotificationStatusDetails>(composer => composer.With(n => n.Id, Guid.NewGuid())
.With(n => n.UserId, Guid.NewGuid())
.With(n => n.OrganizationId, Guid.NewGuid()));
}
}
public class NotificationStatusDetailsCustomizeAttribute : BitCustomizeAttribute
{
public override ICustomization GetCustomization() => new NotificationStatusDetailsCustomization();
}

View File

@ -0,0 +1,20 @@
#nullable enable
using AutoFixture;
using Bit.Core.NotificationCenter.Entities;
using Bit.Test.Common.AutoFixture.Attributes;
namespace Bit.Core.Test.NotificationCenter.AutoFixture;
public class NotificationStatusCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<NotificationStatus>(composer => composer.With(ns => ns.NotificationId, Guid.NewGuid())
.With(ns => ns.UserId, Guid.NewGuid()));
}
}
public class NotificationStatusCustomizeAttribute : BitCustomizeAttribute
{
public override ICustomization GetCustomization() => new NotificationStatusCustomization();
}

View File

@ -0,0 +1,59 @@
#nullable enable
using System.Security.Claims;
using Bit.Core.Exceptions;
using Bit.Core.NotificationCenter.Authorization;
using Bit.Core.NotificationCenter.Commands;
using Bit.Core.NotificationCenter.Entities;
using Bit.Core.NotificationCenter.Repositories;
using Bit.Core.Test.NotificationCenter.AutoFixture;
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
using Microsoft.AspNetCore.Authorization;
using NSubstitute;
using Xunit;
namespace Bit.Core.Test.NotificationCenter.Commands;
[SutProviderCustomize]
[NotificationCustomize]
public class CreateNotificationCommandTest
{
private static void Setup(SutProvider<CreateNotificationCommand> sutProvider,
Notification notification, bool authorized = false)
{
sutProvider.GetDependency<INotificationRepository>()
.CreateAsync(notification)
.Returns(notification);
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), notification,
Arg.Is<IEnumerable<IAuthorizationRequirement>>(reqs =>
reqs.Contains(NotificationOperations.Create)))
.Returns(authorized ? AuthorizationResult.Success() : AuthorizationResult.Failed());
}
[Theory]
[BitAutoData]
public async Task CreateAsync_AuthorizationFailed_NotFoundException(
SutProvider<CreateNotificationCommand> sutProvider,
Notification notification)
{
Setup(sutProvider, notification, authorized: false);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.CreateAsync(notification));
}
[Theory]
[BitAutoData]
public async Task CreateAsync_Authorized_NotificationCreated(
SutProvider<CreateNotificationCommand> sutProvider,
Notification notification)
{
Setup(sutProvider, notification, true);
var newNotification = await sutProvider.Sut.CreateAsync(notification);
Assert.Equal(notification, newNotification);
Assert.Equal(DateTime.UtcNow, notification.CreationDate, TimeSpan.FromMinutes(1));
Assert.Equal(notification.CreationDate, notification.RevisionDate);
}
}

View File

@ -0,0 +1,89 @@
#nullable enable
using System.Security.Claims;
using Bit.Core.Exceptions;
using Bit.Core.NotificationCenter.Authorization;
using Bit.Core.NotificationCenter.Commands;
using Bit.Core.NotificationCenter.Entities;
using Bit.Core.NotificationCenter.Repositories;
using Bit.Core.Test.NotificationCenter.AutoFixture;
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
using Microsoft.AspNetCore.Authorization;
using NSubstitute;
using Xunit;
namespace Bit.Core.Test.NotificationCenter.Commands;
[SutProviderCustomize]
[NotificationCustomize]
[NotificationStatusCustomize]
public class CreateNotificationStatusCommandTest
{
private static void Setup(SutProvider<CreateNotificationStatusCommand> sutProvider,
Notification? notification, NotificationStatus notificationStatus,
bool authorizedNotification = false, bool authorizedCreate = false)
{
sutProvider.GetDependency<INotificationRepository>()
.GetByIdAsync(notificationStatus.NotificationId)
.Returns(notification);
sutProvider.GetDependency<INotificationStatusRepository>()
.CreateAsync(notificationStatus)
.Returns(notificationStatus);
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), notification ?? Arg.Any<Notification>(),
Arg.Is<IEnumerable<IAuthorizationRequirement>>(reqs =>
reqs.Contains(NotificationOperations.Read)))
.Returns(authorizedNotification ? AuthorizationResult.Success() : AuthorizationResult.Failed());
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), notificationStatus,
Arg.Is<IEnumerable<IAuthorizationRequirement>>(reqs =>
reqs.Contains(NotificationStatusOperations.Create)))
.Returns(authorizedCreate ? AuthorizationResult.Success() : AuthorizationResult.Failed());
}
[Theory]
[BitAutoData]
public async Task CreateAsync_NotificationNotFound_NotFoundException(
SutProvider<CreateNotificationStatusCommand> sutProvider,
NotificationStatus notificationStatus)
{
Setup(sutProvider, notification: null, notificationStatus, true, true);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.CreateAsync(notificationStatus));
}
[Theory]
[BitAutoData]
public async Task CreateAsync_NotificationReadNotAuthorized_NotFoundException(
SutProvider<CreateNotificationStatusCommand> sutProvider,
Notification notification, NotificationStatus notificationStatus)
{
Setup(sutProvider, notification, notificationStatus, authorizedNotification: false, true);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.CreateAsync(notificationStatus));
}
[Theory]
[BitAutoData]
public async Task CreateAsync_CreateNotAuthorized_NotFoundException(
SutProvider<CreateNotificationStatusCommand> sutProvider,
Notification notification, NotificationStatus notificationStatus)
{
Setup(sutProvider, notification, notificationStatus, true, authorizedCreate: false);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.CreateAsync(notificationStatus));
}
[Theory]
[BitAutoData]
public async Task CreateAsync_NotificationFoundAuthorized_NotificationStatusCreated(
SutProvider<CreateNotificationStatusCommand> sutProvider,
Notification notification, NotificationStatus notificationStatus)
{
Setup(sutProvider, notification, notificationStatus, true, true);
var newNotificationStatus = await sutProvider.Sut.CreateAsync(notificationStatus);
Assert.Equal(notificationStatus, newNotificationStatus);
}
}

View File

@ -0,0 +1,151 @@
#nullable enable
using System.Security.Claims;
using Bit.Core.Context;
using Bit.Core.Exceptions;
using Bit.Core.NotificationCenter.Authorization;
using Bit.Core.NotificationCenter.Commands;
using Bit.Core.NotificationCenter.Entities;
using Bit.Core.NotificationCenter.Repositories;
using Bit.Core.Test.NotificationCenter.AutoFixture;
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
using Microsoft.AspNetCore.Authorization;
using NSubstitute;
using Xunit;
namespace Bit.Core.Test.NotificationCenter.Commands;
[SutProviderCustomize]
[NotificationCustomize]
[NotificationStatusCustomize]
public class MarkNotificationDeletedCommandTest
{
private static void Setup(SutProvider<MarkNotificationDeletedCommand> sutProvider,
Guid notificationId, Guid? userId, Notification? notification, NotificationStatus? notificationStatus,
bool authorizedNotification = false, bool authorizedCreate = false, bool authorizedUpdate = false)
{
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
sutProvider.GetDependency<INotificationRepository>()
.GetByIdAsync(notificationId)
.Returns(notification);
sutProvider.GetDependency<INotificationStatusRepository>()
.GetByNotificationIdAndUserIdAsync(notificationId, userId ?? Arg.Any<Guid>())
.Returns(notificationStatus);
sutProvider.GetDependency<INotificationStatusRepository>()
.CreateAsync(Arg.Any<NotificationStatus>());
sutProvider.GetDependency<INotificationStatusRepository>()
.UpdateAsync(notificationStatus ?? Arg.Any<NotificationStatus>());
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), notification ?? Arg.Any<Notification>(),
Arg.Is<IEnumerable<IAuthorizationRequirement>>(reqs =>
reqs.Contains(NotificationOperations.Read)))
.Returns(authorizedNotification ? AuthorizationResult.Success() : AuthorizationResult.Failed());
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), notificationStatus ?? Arg.Any<NotificationStatus>(),
Arg.Is<IEnumerable<IAuthorizationRequirement>>(reqs =>
reqs.Contains(NotificationStatusOperations.Create)))
.Returns(authorizedCreate ? AuthorizationResult.Success() : AuthorizationResult.Failed());
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), notificationStatus ?? Arg.Any<NotificationStatus>(),
Arg.Is<IEnumerable<IAuthorizationRequirement>>(reqs =>
reqs.Contains(NotificationStatusOperations.Update)))
.Returns(authorizedUpdate ? AuthorizationResult.Success() : AuthorizationResult.Failed());
sutProvider.GetDependency<INotificationStatusRepository>().ClearReceivedCalls();
}
[Theory]
[BitAutoData]
public async Task MarkDeletedAsync_NotLoggedIn_NotFoundException(
SutProvider<MarkNotificationDeletedCommand> sutProvider,
Guid notificationId, Notification notification, NotificationStatus notificationStatus)
{
Setup(sutProvider, notificationId, userId: null, notification, notificationStatus, true, true, true);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.MarkDeletedAsync(notificationId));
}
[Theory]
[BitAutoData]
public async Task MarkDeletedAsync_NotificationNotFound_NotFoundException(
SutProvider<MarkNotificationDeletedCommand> sutProvider,
Guid notificationId, Guid userId, NotificationStatus notificationStatus)
{
Setup(sutProvider, notificationId, userId, notification: null, notificationStatus, true, true, true);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.MarkDeletedAsync(notificationId));
}
[Theory]
[BitAutoData]
public async Task MarkDeletedAsync_ReadRequirementNotificationNotAuthorized_NotFoundException(
SutProvider<MarkNotificationDeletedCommand> sutProvider,
Guid notificationId, Guid userId, Notification notification, NotificationStatus notificationStatus)
{
Setup(sutProvider, notificationId, userId, notification, notificationStatus, authorizedNotification: false,
true, true);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.MarkDeletedAsync(notificationId));
}
[Theory]
[BitAutoData]
public async Task MarkDeletedAsync_CreateRequirementNotAuthorized_NotFoundException(
SutProvider<MarkNotificationDeletedCommand> sutProvider,
Guid notificationId, Guid userId, Notification notification)
{
Setup(sutProvider, notificationId, userId, notification, notificationStatus: null, true,
authorizedCreate: false, true);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.MarkDeletedAsync(notificationId));
}
[Theory]
[BitAutoData]
public async Task MarkDeletedAsync_UpdateRequirementNotAuthorized_NotFoundException(
SutProvider<MarkNotificationDeletedCommand> sutProvider,
Guid notificationId, Guid userId, Notification notification, NotificationStatus notificationStatus)
{
Setup(sutProvider, notificationId, userId, notification, notificationStatus, true, true,
authorizedUpdate: false);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.MarkDeletedAsync(notificationId));
}
[Theory]
[BitAutoData]
public async Task MarkDeletedAsync_NotificationStatusNotFoundCreateAuthorized_NotificationStatusCreated(
SutProvider<MarkNotificationDeletedCommand> sutProvider,
Guid notificationId, Guid userId, Notification notification)
{
Setup(sutProvider, notificationId, userId, notification, notificationStatus: null, true, true, true);
await sutProvider.Sut.MarkDeletedAsync(notificationId);
await sutProvider.GetDependency<INotificationStatusRepository>().Received(1)
.CreateAsync(Arg.Is<NotificationStatus>(ns =>
ns.NotificationId == notificationId && ns.UserId == userId && !ns.ReadDate.HasValue &&
ns.DeletedDate.HasValue && DateTime.UtcNow - ns.DeletedDate.Value < TimeSpan.FromMinutes(1)));
}
[Theory]
[BitAutoData]
public async Task MarkDeletedAsync_NotificationStatusFoundCreateAuthorized_NotificationStatusUpdated(
SutProvider<MarkNotificationDeletedCommand> sutProvider,
Guid notificationId, Guid userId, Notification notification, NotificationStatus notificationStatus)
{
var deletedDate = notificationStatus.DeletedDate;
Setup(sutProvider, notificationId, userId, notification, notificationStatus, true, true, true);
await sutProvider.Sut.MarkDeletedAsync(notificationId);
await sutProvider.GetDependency<INotificationStatusRepository>().Received(1)
.UpdateAsync(Arg.Is<NotificationStatus>(ns =>
ns.Equals(notificationStatus) &&
ns.NotificationId == notificationStatus.NotificationId && ns.UserId == notificationStatus.UserId &&
ns.ReadDate == notificationStatus.ReadDate && ns.DeletedDate != deletedDate &&
ns.DeletedDate.HasValue &&
DateTime.UtcNow - ns.DeletedDate.Value < TimeSpan.FromMinutes(1)));
}
}

View File

@ -0,0 +1,151 @@
#nullable enable
using System.Security.Claims;
using Bit.Core.Context;
using Bit.Core.Exceptions;
using Bit.Core.NotificationCenter.Authorization;
using Bit.Core.NotificationCenter.Commands;
using Bit.Core.NotificationCenter.Entities;
using Bit.Core.NotificationCenter.Repositories;
using Bit.Core.Test.NotificationCenter.AutoFixture;
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
using Microsoft.AspNetCore.Authorization;
using NSubstitute;
using Xunit;
namespace Bit.Core.Test.NotificationCenter.Commands;
[SutProviderCustomize]
[NotificationCustomize]
[NotificationStatusCustomize]
public class MarkNotificationReadCommandTest
{
private static void Setup(SutProvider<MarkNotificationReadCommand> sutProvider,
Guid notificationId, Guid? userId, Notification? notification, NotificationStatus? notificationStatus,
bool authorizedNotification = false, bool authorizedCreate = false, bool authorizedUpdate = false)
{
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
sutProvider.GetDependency<INotificationRepository>()
.GetByIdAsync(notificationId)
.Returns(notification);
sutProvider.GetDependency<INotificationStatusRepository>()
.GetByNotificationIdAndUserIdAsync(notificationId, userId ?? Arg.Any<Guid>())
.Returns(notificationStatus);
sutProvider.GetDependency<INotificationStatusRepository>()
.CreateAsync(Arg.Any<NotificationStatus>());
sutProvider.GetDependency<INotificationStatusRepository>()
.UpdateAsync(notificationStatus ?? Arg.Any<NotificationStatus>());
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), notification ?? Arg.Any<Notification>(),
Arg.Is<IEnumerable<IAuthorizationRequirement>>(reqs =>
reqs.Contains(NotificationOperations.Read)))
.Returns(authorizedNotification ? AuthorizationResult.Success() : AuthorizationResult.Failed());
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), notificationStatus ?? Arg.Any<NotificationStatus>(),
Arg.Is<IEnumerable<IAuthorizationRequirement>>(reqs =>
reqs.Contains(NotificationStatusOperations.Create)))
.Returns(authorizedCreate ? AuthorizationResult.Success() : AuthorizationResult.Failed());
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), notificationStatus ?? Arg.Any<NotificationStatus>(),
Arg.Is<IEnumerable<IAuthorizationRequirement>>(reqs =>
reqs.Contains(NotificationStatusOperations.Update)))
.Returns(authorizedUpdate ? AuthorizationResult.Success() : AuthorizationResult.Failed());
sutProvider.GetDependency<INotificationStatusRepository>().ClearReceivedCalls();
}
[Theory]
[BitAutoData]
public async Task MarkReadAsync_NotLoggedIn_NotFoundException(
SutProvider<MarkNotificationReadCommand> sutProvider,
Guid notificationId, Notification notification, NotificationStatus notificationStatus)
{
Setup(sutProvider, notificationId, userId: null, notification, notificationStatus, true, true, true);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.MarkReadAsync(notificationId));
}
[Theory]
[BitAutoData]
public async Task MarkReadAsync_NotificationNotFound_NotFoundException(
SutProvider<MarkNotificationReadCommand> sutProvider,
Guid notificationId, Guid userId, NotificationStatus notificationStatus)
{
Setup(sutProvider, notificationId, userId, notification: null, notificationStatus, true, true, true);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.MarkReadAsync(notificationId));
}
[Theory]
[BitAutoData]
public async Task MarkReadAsync_ReadRequirementNotificationNotAuthorized_NotFoundException(
SutProvider<MarkNotificationReadCommand> sutProvider,
Guid notificationId, Guid userId, Notification notification, NotificationStatus notificationStatus)
{
Setup(sutProvider, notificationId, userId, notification, notificationStatus, authorizedNotification: false,
true, true);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.MarkReadAsync(notificationId));
}
[Theory]
[BitAutoData]
public async Task MarkReadAsync_CreateRequirementNotAuthorized_NotFoundException(
SutProvider<MarkNotificationReadCommand> sutProvider,
Guid notificationId, Guid userId, Notification notification)
{
Setup(sutProvider, notificationId, userId, notification, notificationStatus: null, true,
authorizedCreate: false, true);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.MarkReadAsync(notificationId));
}
[Theory]
[BitAutoData]
public async Task MarkReadAsync_UpdateRequirementNotAuthorized_NotFoundException(
SutProvider<MarkNotificationReadCommand> sutProvider,
Guid notificationId, Guid userId, Notification notification, NotificationStatus notificationStatus)
{
Setup(sutProvider, notificationId, userId, notification, notificationStatus, true, true,
authorizedUpdate: false);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.MarkReadAsync(notificationId));
}
[Theory]
[BitAutoData]
public async Task MarkReadAsync_NotificationStatusNotFoundCreateAuthorized_NotificationStatusCreated(
SutProvider<MarkNotificationReadCommand> sutProvider,
Guid notificationId, Guid userId, Notification notification)
{
Setup(sutProvider, notificationId, userId, notification, notificationStatus: null, true, true, true);
await sutProvider.Sut.MarkReadAsync(notificationId);
await sutProvider.GetDependency<INotificationStatusRepository>().Received(1)
.CreateAsync(Arg.Is<NotificationStatus>(ns =>
ns.NotificationId == notificationId && ns.UserId == userId && !ns.DeletedDate.HasValue &&
ns.ReadDate.HasValue && DateTime.UtcNow - ns.ReadDate.Value < TimeSpan.FromMinutes(1)));
}
[Theory]
[BitAutoData]
public async Task MarkReadAsync_NotificationStatusFoundCreateAuthorized_NotificationStatusUpdated(
SutProvider<MarkNotificationReadCommand> sutProvider,
Guid notificationId, Guid userId, Notification notification, NotificationStatus notificationStatus)
{
var readDate = notificationStatus.ReadDate;
Setup(sutProvider, notificationId, userId, notification, notificationStatus, true, true, true);
await sutProvider.Sut.MarkReadAsync(notificationId);
await sutProvider.GetDependency<INotificationStatusRepository>().Received(1)
.UpdateAsync(Arg.Is<NotificationStatus>(ns =>
ns.Equals(notificationStatus) &&
ns.NotificationId == notificationStatus.NotificationId && ns.UserId == notificationStatus.UserId &&
ns.DeletedDate == notificationStatus.DeletedDate && ns.ReadDate != readDate &&
ns.ReadDate.HasValue &&
DateTime.UtcNow - ns.ReadDate.Value < TimeSpan.FromMinutes(1)));
}
}

View File

@ -0,0 +1,95 @@
#nullable enable
using System.Security.Claims;
using Bit.Core.Enums;
using Bit.Core.Exceptions;
using Bit.Core.NotificationCenter.Authorization;
using Bit.Core.NotificationCenter.Commands;
using Bit.Core.NotificationCenter.Entities;
using Bit.Core.NotificationCenter.Enums;
using Bit.Core.NotificationCenter.Repositories;
using Bit.Core.Test.NotificationCenter.AutoFixture;
using Bit.Core.Utilities;
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
using Microsoft.AspNetCore.Authorization;
using NSubstitute;
using Xunit;
namespace Bit.Core.Test.NotificationCenter.Commands;
[SutProviderCustomize]
[NotificationCustomize]
public class UpdateNotificationCommandTest
{
private static void Setup(SutProvider<UpdateNotificationCommand> sutProvider,
Guid notificationId, Notification? notification, bool authorized = false)
{
sutProvider.GetDependency<INotificationRepository>()
.GetByIdAsync(notificationId)
.Returns(notification);
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), notification ?? Arg.Any<Notification>(),
Arg.Is<IEnumerable<IAuthorizationRequirement>>(reqs =>
reqs.Contains(NotificationOperations.Update)))
.Returns(authorized ? AuthorizationResult.Success() : AuthorizationResult.Failed());
sutProvider.GetDependency<INotificationRepository>().ClearReceivedCalls();
}
[Theory]
[BitAutoData]
public async Task UpdateAsync_NotificationNotFound_NotFoundException(
SutProvider<UpdateNotificationCommand> sutProvider,
Notification notification)
{
Setup(sutProvider, notification.Id, notification: null, true);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.UpdateAsync(notification));
}
[Theory]
[BitAutoData]
public async Task UpdateAsync_AuthorizationFailed_NotFoundException(
SutProvider<UpdateNotificationCommand> sutProvider,
Notification notification)
{
Setup(sutProvider, notification.Id, notification, authorized: false);
await Assert.ThrowsAsync<NotFoundException>(() => sutProvider.Sut.UpdateAsync(notification));
}
[Theory]
[BitAutoData]
public async Task UpdateAsync_Authorized_NotificationCreated(
SutProvider<UpdateNotificationCommand> sutProvider,
Notification notification)
{
notification.Priority = Priority.Medium;
notification.ClientType = ClientType.Web;
notification.Title = "Title";
notification.Body = "Body";
notification.RevisionDate = DateTime.UtcNow.AddMinutes(-60);
Setup(sutProvider, notification.Id, notification, true);
var notificationToUpdate = CoreHelpers.CloneObject(notification);
notificationToUpdate.Priority = Priority.High;
notificationToUpdate.ClientType = ClientType.Mobile;
notificationToUpdate.Title = "Updated Title";
notificationToUpdate.Body = "Updated Body";
notificationToUpdate.RevisionDate = DateTime.UtcNow.AddMinutes(-30);
await sutProvider.Sut.UpdateAsync(notificationToUpdate);
await sutProvider.GetDependency<INotificationRepository>().Received(1)
.ReplaceAsync(Arg.Is<Notification>(n =>
// Not updated fields
n.Id == notificationToUpdate.Id && n.Global == notificationToUpdate.Global &&
n.UserId == notificationToUpdate.UserId && n.OrganizationId == notificationToUpdate.OrganizationId &&
n.CreationDate == notificationToUpdate.CreationDate &&
// Updated fields
n.Priority == notificationToUpdate.Priority && n.ClientType == notificationToUpdate.ClientType &&
n.Title == notificationToUpdate.Title && n.Body == notificationToUpdate.Body &&
DateTime.UtcNow - n.RevisionDate < TimeSpan.FromMinutes(1)));
}
}

View File

@ -0,0 +1,55 @@
#nullable enable
using Bit.Core.Context;
using Bit.Core.Enums;
using Bit.Core.Exceptions;
using Bit.Core.NotificationCenter.Models.Data;
using Bit.Core.NotificationCenter.Models.Filter;
using Bit.Core.NotificationCenter.Queries;
using Bit.Core.NotificationCenter.Repositories;
using Bit.Core.Test.NotificationCenter.AutoFixture;
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
using NSubstitute;
using Xunit;
namespace Bit.Core.Test.NotificationCenter.Queries;
[SutProviderCustomize]
[NotificationStatusDetailsCustomize]
public class GetNotificationStatusDetailsForUserQueryTest
{
private static void Setup(SutProvider<GetNotificationStatusDetailsForUserQuery> sutProvider,
List<NotificationStatusDetails> notificationsStatusDetails, NotificationStatusFilter statusFilter, Guid? userId)
{
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
sutProvider.GetDependency<INotificationRepository>().GetByUserIdAndStatusAsync(
userId.GetValueOrDefault(Guid.NewGuid()), Arg.Any<ClientType>(), statusFilter)
.Returns(notificationsStatusDetails);
}
[Theory]
[BitAutoData]
public async Task GetByUserIdStatusFilterAsync_NotLoggedIn_NotFoundException(
SutProvider<GetNotificationStatusDetailsForUserQuery> sutProvider,
List<NotificationStatusDetails> notificationsStatusDetails, NotificationStatusFilter notificationStatusFilter)
{
Setup(sutProvider, notificationsStatusDetails, notificationStatusFilter, userId: null);
await Assert.ThrowsAsync<NotFoundException>(() =>
sutProvider.Sut.GetByUserIdStatusFilterAsync(notificationStatusFilter));
}
[Theory]
[BitAutoData]
public async Task GetByUserIdStatusFilterAsync_NotificationsFound_Returned(
SutProvider<GetNotificationStatusDetailsForUserQuery> sutProvider,
List<NotificationStatusDetails> notificationsStatusDetails, NotificationStatusFilter notificationStatusFilter)
{
Setup(sutProvider, notificationsStatusDetails, notificationStatusFilter, Guid.NewGuid());
var actualNotificationsStatusDetails =
await sutProvider.Sut.GetByUserIdStatusFilterAsync(notificationStatusFilter);
Assert.Equal(notificationsStatusDetails, actualNotificationsStatusDetails);
}
}

View File

@ -0,0 +1,85 @@
#nullable enable
using Bit.Core.Context;
using Bit.Core.Exceptions;
using Bit.Core.NotificationCenter.Queries;
using Bit.Core.NotificationCenter.Repositories;
using Bit.Core.Test.NotificationCenter.AutoFixture;
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
namespace Bit.Core.Test.NotificationCenter.Queries;
using System.Security.Claims;
using Bit.Core.NotificationCenter.Authorization;
using Bit.Core.NotificationCenter.Entities;
using Microsoft.AspNetCore.Authorization;
using NSubstitute;
using Xunit;
[SutProviderCustomize]
[NotificationStatusCustomize]
public class GetNotificationStatusForUserQueryTest
{
private static void Setup(SutProvider<GetNotificationStatusForUserQuery> sutProvider,
Guid notificationId, NotificationStatus? notificationStatus, Guid? userId, bool authorized = false)
{
sutProvider.GetDependency<ICurrentContext>().UserId.Returns(userId);
sutProvider.GetDependency<INotificationStatusRepository>()
.GetByNotificationIdAndUserIdAsync(notificationId, userId.GetValueOrDefault(Guid.NewGuid()))
.Returns(notificationStatus);
sutProvider.GetDependency<IAuthorizationService>()
.AuthorizeAsync(Arg.Any<ClaimsPrincipal>(), notificationStatus ?? Arg.Any<NotificationStatus>(),
Arg.Is<IEnumerable<IAuthorizationRequirement>>(reqs =>
reqs.Contains(NotificationStatusOperations.Read)))
.Returns(authorized ? AuthorizationResult.Success() : AuthorizationResult.Failed());
}
[Theory]
[BitAutoData]
public async Task GetByUserIdStatusFilterAsync_UserNotLoggedIn_NotFoundException(
SutProvider<GetNotificationStatusForUserQuery> sutProvider,
Guid notificationId, NotificationStatus notificationStatus)
{
Setup(sutProvider, notificationId, notificationStatus, userId: null, true);
await Assert.ThrowsAsync<NotFoundException>(() =>
sutProvider.Sut.GetByNotificationIdAndUserIdAsync(notificationId));
}
[Theory]
[BitAutoData]
public async Task GetByUserIdStatusFilterAsync_NotificationStatusNotFound_NotFoundException(
SutProvider<GetNotificationStatusForUserQuery> sutProvider,
Guid notificationId)
{
Setup(sutProvider, notificationId, notificationStatus: null, Guid.NewGuid(), true);
await Assert.ThrowsAsync<NotFoundException>(() =>
sutProvider.Sut.GetByNotificationIdAndUserIdAsync(notificationId));
}
[Theory]
[BitAutoData]
public async Task GetByUserIdStatusFilterAsync_AuthorizationFailed_NotFoundException(
SutProvider<GetNotificationStatusForUserQuery> sutProvider,
Guid notificationId, NotificationStatus notificationStatus)
{
Setup(sutProvider, notificationId, notificationStatus, Guid.NewGuid(), authorized: false);
await Assert.ThrowsAsync<NotFoundException>(() =>
sutProvider.Sut.GetByNotificationIdAndUserIdAsync(notificationId));
}
[Theory]
[BitAutoData]
public async Task GetByUserIdStatusFilterAsync_NotificationFoundAuthorized_Returned(
SutProvider<GetNotificationStatusForUserQuery> sutProvider,
Guid notificationId, NotificationStatus notificationStatus)
{
Setup(sutProvider, notificationId, notificationStatus, Guid.NewGuid(), true);
var actualNotificationStatus = await sutProvider.Sut.GetByNotificationIdAndUserIdAsync(notificationId);
Assert.Equal(notificationStatus, actualNotificationStatus);
}
}

View File

@ -0,0 +1,486 @@
-- Add Columns
IF COL_LENGTH('[dbo].[Organization]', 'LimitCollectionCreation') IS NULL
BEGIN
ALTER TABLE
[dbo].[Organization]
ADD
[LimitCollectionCreation] BIT NOT NULL CONSTRAINT [DF_Organization_LimitCollectionCreation] DEFAULT (0)
END
GO
IF COL_LENGTH('[dbo].[Organization]', 'LimitCollectionDeletion') IS NULL
BEGIN
ALTER TABLE
[dbo].[Organization]
ADD
[LimitCollectionDeletion] BIT NOT NULL CONSTRAINT [DF_Organization_LimitCollectionDeletion] DEFAULT (0)
END
GO
-- Refresh Views
CREATE OR ALTER VIEW [dbo].[ProviderUserProviderOrganizationDetailsView]
AS
SELECT
PU.[UserId],
PO.[OrganizationId],
O.[Name],
O.[Enabled],
O.[UsePolicies],
O.[UseSso],
O.[UseKeyConnector],
O.[UseScim],
O.[UseGroups],
O.[UseDirectory],
O.[UseEvents],
O.[UseTotp],
O.[Use2fa],
O.[UseApi],
O.[UseResetPassword],
O.[SelfHost],
O.[UsersGetPremium],
O.[UseCustomPermissions],
O.[Seats],
O.[MaxCollections],
O.[MaxStorageGb],
O.[Identifier],
PO.[Key],
O.[PublicKey],
O.[PrivateKey],
PU.[Status],
PU.[Type],
PO.[ProviderId],
PU.[Id] ProviderUserId,
P.[Name] ProviderName,
O.[PlanType],
O.[LimitCollectionCreationDeletion], -- Deprecated https://bitwarden.atlassian.net/browse/PM-10863
O.[LimitCollectionCreation],
O.[LimitCollectionDeletion],
O.[AllowAdminAccessToAllCollectionItems]
FROM
[dbo].[ProviderUser] PU
INNER JOIN
[dbo].[ProviderOrganization] PO ON PO.[ProviderId] = PU.[ProviderId]
INNER JOIN
[dbo].[Organization] O ON O.[Id] = PO.[OrganizationId]
INNER JOIN
[dbo].[Provider] P ON P.[Id] = PU.[ProviderId]
GO
CREATE OR ALTER VIEW [dbo].[OrganizationUserOrganizationDetailsView]
AS
SELECT
OU.[UserId],
OU.[OrganizationId],
OU.[Id] OrganizationUserId,
O.[Name],
O.[Enabled],
O.[PlanType],
O.[UsePolicies],
O.[UseSso],
O.[UseKeyConnector],
O.[UseScim],
O.[UseGroups],
O.[UseDirectory],
O.[UseEvents],
O.[UseTotp],
O.[Use2fa],
O.[UseApi],
O.[UseResetPassword],
O.[SelfHost],
O.[UsersGetPremium],
O.[UseCustomPermissions],
O.[UseSecretsManager],
O.[Seats],
O.[MaxCollections],
O.[MaxStorageGb],
O.[Identifier],
OU.[Key],
OU.[ResetPasswordKey],
O.[PublicKey],
O.[PrivateKey],
OU.[Status],
OU.[Type],
SU.[ExternalId] SsoExternalId,
OU.[Permissions],
PO.[ProviderId],
P.[Name] ProviderName,
P.[Type] ProviderType,
SS.[Data] SsoConfig,
OS.[FriendlyName] FamilySponsorshipFriendlyName,
OS.[LastSyncDate] FamilySponsorshipLastSyncDate,
OS.[ToDelete] FamilySponsorshipToDelete,
OS.[ValidUntil] FamilySponsorshipValidUntil,
OU.[AccessSecretsManager],
O.[UsePasswordManager],
O.[SmSeats],
O.[SmServiceAccounts],
O.[LimitCollectionCreationDeletion], -- Deprecated https://bitwarden.atlassian.net/browse/PM-10863
O.[LimitCollectionCreation],
O.[LimitCollectionDeletion],
O.[AllowAdminAccessToAllCollectionItems]
FROM
[dbo].[OrganizationUser] OU
LEFT JOIN
[dbo].[Organization] O ON O.[Id] = OU.[OrganizationId]
LEFT JOIN
[dbo].[SsoUser] SU ON SU.[UserId] = OU.[UserId] AND SU.[OrganizationId] = OU.[OrganizationId]
LEFT JOIN
[dbo].[ProviderOrganization] PO ON PO.[OrganizationId] = O.[Id]
LEFT JOIN
[dbo].[Provider] P ON P.[Id] = PO.[ProviderId]
LEFT JOIN
[dbo].[SsoConfig] SS ON SS.[OrganizationId] = OU.[OrganizationId]
LEFT JOIN
[dbo].[OrganizationSponsorship] OS ON OS.[SponsoringOrganizationUserID] = OU.[Id]
GO
IF OBJECT_ID('[dbo].[OrganizationView]') IS NOT NULL
BEGIN
EXECUTE sp_refreshview N'[dbo].[OrganizationView]';
END
GO
-- Refresh Stored Procedures
CREATE OR ALTER PROCEDURE [dbo].[Organization_Create]
@Id UNIQUEIDENTIFIER OUTPUT,
@Identifier NVARCHAR(50),
@Name NVARCHAR(50),
@BusinessName NVARCHAR(50),
@BusinessAddress1 NVARCHAR(50),
@BusinessAddress2 NVARCHAR(50),
@BusinessAddress3 NVARCHAR(50),
@BusinessCountry VARCHAR(2),
@BusinessTaxNumber NVARCHAR(30),
@BillingEmail NVARCHAR(256),
@Plan NVARCHAR(50),
@PlanType TINYINT,
@Seats INT,
@MaxCollections SMALLINT,
@UsePolicies BIT,
@UseSso BIT,
@UseGroups BIT,
@UseDirectory BIT,
@UseEvents BIT,
@UseTotp BIT,
@Use2fa BIT,
@UseApi BIT,
@UseResetPassword BIT,
@SelfHost BIT,
@UsersGetPremium BIT,
@Storage BIGINT,
@MaxStorageGb SMALLINT,
@Gateway TINYINT,
@GatewayCustomerId VARCHAR(50),
@GatewaySubscriptionId VARCHAR(50),
@ReferenceData VARCHAR(MAX),
@Enabled BIT,
@LicenseKey VARCHAR(100),
@PublicKey VARCHAR(MAX),
@PrivateKey VARCHAR(MAX),
@TwoFactorProviders NVARCHAR(MAX),
@ExpirationDate DATETIME2(7),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@OwnersNotifiedOfAutoscaling DATETIME2(7),
@MaxAutoscaleSeats INT,
@UseKeyConnector BIT = 0,
@UseScim BIT = 0,
@UseCustomPermissions BIT = 0,
@UseSecretsManager BIT = 0,
@Status TINYINT = 0,
@UsePasswordManager BIT = 1,
@SmSeats INT = null,
@SmServiceAccounts INT = null,
@MaxAutoscaleSmSeats INT= null,
@MaxAutoscaleSmServiceAccounts INT = null,
@SecretsManagerBeta BIT = 0,
@LimitCollectionCreationDeletion BIT = NULL, -- Deprecated https://bitwarden.atlassian.net/browse/PM-10863
@LimitCollectionCreation BIT = NULL,
@LimitCollectionDeletion BIT = NULL,
@AllowAdminAccessToAllCollectionItems BIT = 0
AS
BEGIN
SET NOCOUNT ON
SET @LimitCollectionCreation = COALESCE(@LimitCollectionCreation, @LimitCollectionCreationDeletion, 0);
SET @LimitCollectionDeletion = COALESCE(@LimitCollectionDeletion, @LimitCollectionCreationDeletion, 0);
INSERT INTO [dbo].[Organization]
(
[Id],
[Identifier],
[Name],
[BusinessName],
[BusinessAddress1],
[BusinessAddress2],
[BusinessAddress3],
[BusinessCountry],
[BusinessTaxNumber],
[BillingEmail],
[Plan],
[PlanType],
[Seats],
[MaxCollections],
[UsePolicies],
[UseSso],
[UseGroups],
[UseDirectory],
[UseEvents],
[UseTotp],
[Use2fa],
[UseApi],
[UseResetPassword],
[SelfHost],
[UsersGetPremium],
[Storage],
[MaxStorageGb],
[Gateway],
[GatewayCustomerId],
[GatewaySubscriptionId],
[ReferenceData],
[Enabled],
[LicenseKey],
[PublicKey],
[PrivateKey],
[TwoFactorProviders],
[ExpirationDate],
[CreationDate],
[RevisionDate],
[OwnersNotifiedOfAutoscaling],
[MaxAutoscaleSeats],
[UseKeyConnector],
[UseScim],
[UseCustomPermissions],
[UseSecretsManager],
[Status],
[UsePasswordManager],
[SmSeats],
[SmServiceAccounts],
[MaxAutoscaleSmSeats],
[MaxAutoscaleSmServiceAccounts],
[SecretsManagerBeta],
[LimitCollectionCreationDeletion], -- Deprecated https://bitwarden.atlassian.net/browse/PM-10863
[LimitCollectionCreation],
[LimitCollectionDeletion],
[AllowAdminAccessToAllCollectionItems]
)
VALUES
(
@Id,
@Identifier,
@Name,
@BusinessName,
@BusinessAddress1,
@BusinessAddress2,
@BusinessAddress3,
@BusinessCountry,
@BusinessTaxNumber,
@BillingEmail,
@Plan,
@PlanType,
@Seats,
@MaxCollections,
@UsePolicies,
@UseSso,
@UseGroups,
@UseDirectory,
@UseEvents,
@UseTotp,
@Use2fa,
@UseApi,
@UseResetPassword,
@SelfHost,
@UsersGetPremium,
@Storage,
@MaxStorageGb,
@Gateway,
@GatewayCustomerId,
@GatewaySubscriptionId,
@ReferenceData,
@Enabled,
@LicenseKey,
@PublicKey,
@PrivateKey,
@TwoFactorProviders,
@ExpirationDate,
@CreationDate,
@RevisionDate,
@OwnersNotifiedOfAutoscaling,
@MaxAutoscaleSeats,
@UseKeyConnector,
@UseScim,
@UseCustomPermissions,
@UseSecretsManager,
@Status,
@UsePasswordManager,
@SmSeats,
@SmServiceAccounts,
@MaxAutoscaleSmSeats,
@MaxAutoscaleSmServiceAccounts,
@SecretsManagerBeta,
COALESCE(@LimitCollectionCreation, @LimitCollectionDeletion, 0), -- Deprecated https://bitwarden.atlassian.net/browse/PM-10863
@LimitCollectionCreation,
@LimitCollectionDeletion,
@AllowAdminAccessToAllCollectionItems
)
END
GO
CREATE OR ALTER PROCEDURE [dbo].[Organization_ReadAbilities]
AS
BEGIN
SET NOCOUNT ON
SELECT
[Id],
[UseEvents],
[Use2fa],
CASE
WHEN [Use2fa] = 1 AND [TwoFactorProviders] IS NOT NULL AND [TwoFactorProviders] != '{}' THEN
1
ELSE
0
END AS [Using2fa],
[UsersGetPremium],
[UseCustomPermissions],
[UseSso],
[UseKeyConnector],
[UseScim],
[UseResetPassword],
[UsePolicies],
[Enabled],
[LimitCollectionCreationDeletion], -- Deprecated https://bitwarden.atlassian.net/browse/PM-10863
[LimitCollectionCreation],
[LimitCollectionDeletion],
[AllowAdminAccessToAllCollectionItems]
FROM
[dbo].[Organization]
END
GO
CREATE OR ALTER PROCEDURE [dbo].[Organization_Update]
@Id UNIQUEIDENTIFIER,
@Identifier NVARCHAR(50),
@Name NVARCHAR(50),
@BusinessName NVARCHAR(50),
@BusinessAddress1 NVARCHAR(50),
@BusinessAddress2 NVARCHAR(50),
@BusinessAddress3 NVARCHAR(50),
@BusinessCountry VARCHAR(2),
@BusinessTaxNumber NVARCHAR(30),
@BillingEmail NVARCHAR(256),
@Plan NVARCHAR(50),
@PlanType TINYINT,
@Seats INT,
@MaxCollections SMALLINT,
@UsePolicies BIT,
@UseSso BIT,
@UseGroups BIT,
@UseDirectory BIT,
@UseEvents BIT,
@UseTotp BIT,
@Use2fa BIT,
@UseApi BIT,
@UseResetPassword BIT,
@SelfHost BIT,
@UsersGetPremium BIT,
@Storage BIGINT,
@MaxStorageGb SMALLINT,
@Gateway TINYINT,
@GatewayCustomerId VARCHAR(50),
@GatewaySubscriptionId VARCHAR(50),
@ReferenceData VARCHAR(MAX),
@Enabled BIT,
@LicenseKey VARCHAR(100),
@PublicKey VARCHAR(MAX),
@PrivateKey VARCHAR(MAX),
@TwoFactorProviders NVARCHAR(MAX),
@ExpirationDate DATETIME2(7),
@CreationDate DATETIME2(7),
@RevisionDate DATETIME2(7),
@OwnersNotifiedOfAutoscaling DATETIME2(7),
@MaxAutoscaleSeats INT,
@UseKeyConnector BIT = 0,
@UseScim BIT = 0,
@UseCustomPermissions BIT = 0,
@UseSecretsManager BIT = 0,
@Status TINYINT = 0,
@UsePasswordManager BIT = 1,
@SmSeats INT = null,
@SmServiceAccounts INT = null,
@MaxAutoscaleSmSeats INT = null,
@MaxAutoscaleSmServiceAccounts INT = null,
@SecretsManagerBeta BIT = 0,
@LimitCollectionCreationDeletion BIT = null, -- Deprecated https://bitwarden.atlassian.net/browse/PM-10863
@LimitCollectionCreation BIT = null,
@LimitCollectionDeletion BIT = null,
@AllowAdminAccessToAllCollectionItems BIT = 0
AS
BEGIN
SET NOCOUNT ON
SET @LimitCollectionCreation = COALESCE(@LimitCollectionCreation, @LimitCollectionCreationDeletion, 0);
SET @LimitCollectionDeletion = COALESCE(@LimitCollectionDeletion, @LimitCollectionCreationDeletion, 0);
UPDATE
[dbo].[Organization]
SET
[Identifier] = @Identifier,
[Name] = @Name,
[BusinessName] = @BusinessName,
[BusinessAddress1] = @BusinessAddress1,
[BusinessAddress2] = @BusinessAddress2,
[BusinessAddress3] = @BusinessAddress3,
[BusinessCountry] = @BusinessCountry,
[BusinessTaxNumber] = @BusinessTaxNumber,
[BillingEmail] = @BillingEmail,
[Plan] = @Plan,
[PlanType] = @PlanType,
[Seats] = @Seats,
[MaxCollections] = @MaxCollections,
[UsePolicies] = @UsePolicies,
[UseSso] = @UseSso,
[UseGroups] = @UseGroups,
[UseDirectory] = @UseDirectory,
[UseEvents] = @UseEvents,
[UseTotp] = @UseTotp,
[Use2fa] = @Use2fa,
[UseApi] = @UseApi,
[UseResetPassword] = @UseResetPassword,
[SelfHost] = @SelfHost,
[UsersGetPremium] = @UsersGetPremium,
[Storage] = @Storage,
[MaxStorageGb] = @MaxStorageGb,
[Gateway] = @Gateway,
[GatewayCustomerId] = @GatewayCustomerId,
[GatewaySubscriptionId] = @GatewaySubscriptionId,
[ReferenceData] = @ReferenceData,
[Enabled] = @Enabled,
[LicenseKey] = @LicenseKey,
[PublicKey] = @PublicKey,
[PrivateKey] = @PrivateKey,
[TwoFactorProviders] = @TwoFactorProviders,
[ExpirationDate] = @ExpirationDate,
[CreationDate] = @CreationDate,
[RevisionDate] = @RevisionDate,
[OwnersNotifiedOfAutoscaling] = @OwnersNotifiedOfAutoscaling,
[MaxAutoscaleSeats] = @MaxAutoscaleSeats,
[UseKeyConnector] = @UseKeyConnector,
[UseScim] = @UseScim,
[UseCustomPermissions] = @UseCustomPermissions,
[UseSecretsManager] = @UseSecretsManager,
[Status] = @Status,
[UsePasswordManager] = @UsePasswordManager,
[SmSeats] = @SmSeats,
[SmServiceAccounts] = @SmServiceAccounts,
[MaxAutoscaleSmSeats] = @MaxAutoscaleSmSeats,
[MaxAutoscaleSmServiceAccounts] = @MaxAutoscaleSmServiceAccounts,
[SecretsManagerBeta] = @SecretsManagerBeta,
[LimitCollectionCreationDeletion] = COALESCE(@LimitCollectionCreation, @LimitCollectionDeletion, 0), -- Deprecated https://bitwarden.atlassian.net/browse/PM-10863
[LimitCollectionCreation] = @LimitCollectionCreation,
[LimitCollectionDeletion] = @LimitCollectionDeletion,
[AllowAdminAccessToAllCollectionItems] = @AllowAdminAccessToAllCollectionItems
WHERE
[Id] = @Id
END
GO

View File

@ -0,0 +1,8 @@
-- Sync existing data
UPDATE [dbo].[Organization]
SET
[LimitCollectionCreation] = 1,
[LimitCollectionDeletion] = 1
WHERE [LimitCollectionCreationDeletion] = 1
GO

View File

@ -0,0 +1,61 @@
-- View NotificationStatusDetailsView
IF EXISTS(SELECT *
FROM sys.views
WHERE [Name] = 'NotificationStatusDetailsView')
BEGIN
DROP VIEW [dbo].[NotificationStatusDetailsView]
END
GO
CREATE VIEW [dbo].[NotificationStatusDetailsView]
AS
SELECT
N.*,
NS.UserId AS NotificationStatusUserId,
NS.ReadDate,
NS.DeletedDate
FROM
[dbo].[Notification] AS N
LEFT JOIN
[dbo].[NotificationStatus] as NS
ON
N.[Id] = NS.[NotificationId]
GO
-- Stored Procedure Notification_ReadByUserIdAndStatus
CREATE OR ALTER PROCEDURE [dbo].[Notification_ReadByUserIdAndStatus]
@UserId UNIQUEIDENTIFIER,
@ClientType TINYINT,
@Read BIT,
@Deleted BIT
AS
BEGIN
SET NOCOUNT ON
SELECT n.*
FROM [dbo].[NotificationStatusDetailsView] n
LEFT JOIN [dbo].[OrganizationUserView] ou ON n.[OrganizationId] = ou.[OrganizationId]
AND ou.[UserId] = @UserId
WHERE (n.[NotificationStatusUserId] IS NULL OR n.[NotificationStatusUserId] = @UserId)
AND [ClientType] IN (0, CASE WHEN @ClientType != 0 THEN @ClientType END)
AND ([Global] = 1
OR (n.[UserId] = @UserId
AND (n.[OrganizationId] IS NULL
OR ou.[OrganizationId] IS NOT NULL))
OR (n.[UserId] IS NULL
AND ou.[OrganizationId] IS NOT NULL))
AND ((@Read IS NULL AND @Deleted IS NULL)
OR (n.[NotificationStatusUserId] IS NOT NULL
AND ((@Read IS NULL
OR IIF((@Read = 1 AND n.[ReadDate] IS NOT NULL) OR
(@Read = 0 AND n.[ReadDate] IS NULL),
1, 0) = 1)
OR (@Deleted IS NULL
OR IIF((@Deleted = 1 AND n.[DeletedDate] IS NOT NULL) OR
(@Deleted = 0 AND n.[DeletedDate] IS NULL),
1, 0) = 1))))
ORDER BY [Priority] DESC, n.[CreationDate] DESC
END
GO

View File

@ -0,0 +1,57 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bit.MySqlMigrations.Migrations;
/// <inheritdoc />
public partial class SplitOrganizationLimitCollectionCreationDeletionColumn : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<bool>(
name: "LimitCollectionCreationDeletion",
table: "Organization",
type: "tinyint(1)",
nullable: false,
oldClrType: typeof(bool),
oldType: "tinyint(1)",
oldDefaultValue: true);
migrationBuilder.AddColumn<bool>(
name: "LimitCollectionCreation",
table: "Organization",
type: "tinyint(1)",
nullable: false,
defaultValue: false);
migrationBuilder.AddColumn<bool>(
name: "LimitCollectionDeletion",
table: "Organization",
type: "tinyint(1)",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "LimitCollectionCreation",
table: "Organization");
migrationBuilder.DropColumn(
name: "LimitCollectionDeletion",
table: "Organization");
migrationBuilder.AlterColumn<bool>(
name: "LimitCollectionCreationDeletion",
table: "Organization",
type: "tinyint(1)",
nullable: false,
defaultValue: true,
oldClrType: typeof(bool),
oldType: "tinyint(1)");
}
}

View File

@ -0,0 +1,27 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bit.MySqlMigrations.Migrations;
/// <inheritdoc />
public partial class SyncOrganizationLimitCollectionCreationDeletionColumn : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(
@"
UPDATE Organization
SET
LimitCollectionCreation = LimitCollectionCreationDeletion,
LimitCollectionDeletion = LimitCollectionCreationDeletion;
");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}

View File

@ -88,9 +88,14 @@ namespace Bit.MySqlMigrations.Migrations
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<bool>("LimitCollectionCreation")
.HasColumnType("tinyint(1)");
b.Property<bool>("LimitCollectionCreationDeletion")
.HasColumnType("tinyint(1)")
.HasDefaultValue(true);
.HasColumnType("tinyint(1)");
b.Property<bool>("LimitCollectionDeletion")
.HasColumnType("tinyint(1)");
b.Property<int?>("MaxAutoscaleSeats")
.HasColumnType("int");

View File

@ -0,0 +1,57 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bit.PostgresMigrations.Migrations;
/// <inheritdoc />
public partial class SplitOrganizationLimitCollectionCreationDeletionColumn : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<bool>(
name: "LimitCollectionCreationDeletion",
table: "Organization",
type: "boolean",
nullable: false,
oldClrType: typeof(bool),
oldType: "boolean",
oldDefaultValue: true);
migrationBuilder.AddColumn<bool>(
name: "LimitCollectionCreation",
table: "Organization",
type: "boolean",
nullable: false,
defaultValue: false);
migrationBuilder.AddColumn<bool>(
name: "LimitCollectionDeletion",
table: "Organization",
type: "boolean",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "LimitCollectionCreation",
table: "Organization");
migrationBuilder.DropColumn(
name: "LimitCollectionDeletion",
table: "Organization");
migrationBuilder.AlterColumn<bool>(
name: "LimitCollectionCreationDeletion",
table: "Organization",
type: "boolean",
nullable: false,
defaultValue: true,
oldClrType: typeof(bool),
oldType: "boolean");
}
}

View File

@ -0,0 +1,31 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bit.PostgresMigrations.Migrations;
/// <inheritdoc />
public partial class SyncOrganizationLimitCollectionCreationDeletionColumn : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
// Postgres is particular about the casing of entities. It wants to
// lowercase everything by default, and convert casings
// automatically. Quoting the entity names here provides explicit &
// correct casing.
migrationBuilder.Sql(
@"
UPDATE ""Organization""
SET
""LimitCollectionCreation"" = ""LimitCollectionCreationDeletion"",
""LimitCollectionDeletion"" = ""LimitCollectionCreationDeletion"";
");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}

View File

@ -90,9 +90,14 @@ namespace Bit.PostgresMigrations.Migrations
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<bool>("LimitCollectionCreation")
.HasColumnType("boolean");
b.Property<bool>("LimitCollectionCreationDeletion")
.HasColumnType("boolean")
.HasDefaultValue(true);
.HasColumnType("boolean");
b.Property<bool>("LimitCollectionDeletion")
.HasColumnType("boolean");
b.Property<int?>("MaxAutoscaleSeats")
.HasColumnType("integer");

View File

@ -0,0 +1,57 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bit.SqliteMigrations.Migrations;
/// <inheritdoc />
public partial class SplitOrganizationLimitCollectionCreationDeletionColumn : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<bool>(
name: "LimitCollectionCreationDeletion",
table: "Organization",
type: "INTEGER",
nullable: false,
oldClrType: typeof(bool),
oldType: "INTEGER",
oldDefaultValue: true);
migrationBuilder.AddColumn<bool>(
name: "LimitCollectionCreation",
table: "Organization",
type: "INTEGER",
nullable: false,
defaultValue: false);
migrationBuilder.AddColumn<bool>(
name: "LimitCollectionDeletion",
table: "Organization",
type: "INTEGER",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "LimitCollectionCreation",
table: "Organization");
migrationBuilder.DropColumn(
name: "LimitCollectionDeletion",
table: "Organization");
migrationBuilder.AlterColumn<bool>(
name: "LimitCollectionCreationDeletion",
table: "Organization",
type: "INTEGER",
nullable: false,
defaultValue: true,
oldClrType: typeof(bool),
oldType: "INTEGER");
}
}

View File

@ -0,0 +1,27 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bit.SqliteMigrations.Migrations;
/// <inheritdoc />
public partial class SyncOrganizationLimitCollectionCreationDeletionColumn : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(
@"
UPDATE Organization
SET
LimitCollectionCreation = LimitCollectionCreationDeletion,
LimitCollectionDeletion = LimitCollectionCreationDeletion;
");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}

View File

@ -83,9 +83,14 @@ namespace Bit.SqliteMigrations.Migrations
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<bool>("LimitCollectionCreation")
.HasColumnType("INTEGER");
b.Property<bool>("LimitCollectionCreationDeletion")
.HasColumnType("INTEGER")
.HasDefaultValue(true);
.HasColumnType("INTEGER");
b.Property<bool>("LimitCollectionDeletion")
.HasColumnType("INTEGER");
b.Property<int?>("MaxAutoscaleSeats")
.HasColumnType("INTEGER");