1
0
mirror of https://github.com/bitwarden/server.git synced 2024-11-25 12:45:18 +01:00
bitwarden-server/test/Core.Test/Tools/Services/SendServiceTests.cs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

770 lines
24 KiB
C#
Raw Normal View History

using System.Text;
Families for Enterprise (#1714) * Create common test infrastructure project * Add helpers to further type PlanTypes * Enable testing of ASP.net MVC controllers Controller properties have all kinds of validations in the background. In general, we don't user properties on our Controllers, so the easiest way to allow for Autofixture-based testing of our Controllers is to just omit setting all properties on them. * Workaround for broken MemberAutoDataAttribute https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only the first test case is pulled for this attribute. This is a workaround that populates the provided parameters, left to right, using AutoFixture to populate any remaining. * WIP: Organization sponsorship flow * Add Attribute to use the Bit Autodata dependency chain BitAutoDataAttribute is used to mark a Theory as autopopulating parameters. Extract common attribute methods to to a helper class. Cannot inherit a common base, since both require inheriting from different Xunit base classes to work. * WIP: scaffolding for families for enterprise sponsorship flow * Fix broken tests * Create sponsorship offer (#1688) * Initial db work (#1687) * Add organization sponsorship databases to all providers * Generalize create and update for database, specialize in code * Add PlanSponsorshipType to db model * Write valid json for test entries * Initial scaffolding of emails (#1686) * Initial scaffolding of emails * Work on adding models for FamilyForEnterprise emails * Switch verbage * Put preliminary copy in emails * Skip test * Families for enterprise/stripe integrations (#1699) * Add PlanSponsorshipType to static store * Add sponsorship type to token and creates sponsorship * PascalCase properties * Require sponsorship for remove * Create subscription sponsorship helper class * Handle Sponsored subscription changes * Add sponsorship id to subscription metadata * Make sponsoring references nullable This state indicates that a sponsorship has lapsed, but was not able to be reverted for billing reasons * WIP: Validate and remove subscriptions * Update sponsorships on organization and org user delete * Add friendly name to organization sponsorship * Add sponsorship available boolean to orgDetails * Add sponsorship service to DI * Use userId to find org users * Send f4e offer email * Simplify names of f4e mail messages * Fix Stripe org default tax rates * Universal sponsorship redeem api * Populate user in current context * Add product type to organization details * Use upgrade path to change sponsorship Sponsorships need to be annual to match the GB add-on charge rate * Use organization and auth to find organization sponsorship * Add resend sponsorship offer api endpoint * Fix double email send * Fix sponsorship upgrade options * Add is sponsored item to subscription response * Add sponsorship validation to upcoming invoice webhook * Add sponsorship validation to upcoming invoice webhook * Fix organization delete sponsorship hooks * Test org sponsorship service * Fix sproc * Create common test infrastructure project * Add helpers to further type PlanTypes * Enable testing of ASP.net MVC controllers Controller properties have all kinds of validations in the background. In general, we don't user properties on our Controllers, so the easiest way to allow for Autofixture-based testing of our Controllers is to just omit setting all properties on them. * Workaround for broken MemberAutoDataAttribute https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only the first test case is pulled for this attribute. This is a workaround that populates the provided parameters, left to right, using AutoFixture to populate any remaining. * WIP: Organization sponsorship flow * Add Attribute to use the Bit Autodata dependency chain BitAutoDataAttribute is used to mark a Theory as autopopulating parameters. Extract common attribute methods to to a helper class. Cannot inherit a common base, since both require inheriting from different Xunit base classes to work. * WIP: scaffolding for families for enterprise sponsorship flow * Fix broken tests * Create sponsorship offer (#1688) * Initial db work (#1687) * Add organization sponsorship databases to all providers * Generalize create and update for database, specialize in code * Add PlanSponsorshipType to db model * Write valid json for test entries * Initial scaffolding of emails (#1686) * Initial scaffolding of emails * Work on adding models for FamilyForEnterprise emails * Switch verbage * Put preliminary copy in emails * Skip test * Families for enterprise/stripe integrations (#1699) * Add PlanSponsorshipType to static store * Add sponsorship type to token and creates sponsorship * PascalCase properties * Require sponsorship for remove * Create subscription sponsorship helper class * Handle Sponsored subscription changes * Add sponsorship id to subscription metadata * Make sponsoring references nullable This state indicates that a sponsorship has lapsed, but was not able to be reverted for billing reasons * WIP: Validate and remove subscriptions * Update sponsorships on organization and org user delete * Add friendly name to organization sponsorship * Add sponsorship available boolean to orgDetails * Add sponsorship service to DI * Use userId to find org users * Send f4e offer email * Simplify names of f4e mail messages * Fix Stripe org default tax rates * Universal sponsorship redeem api * Populate user in current context * Add product type to organization details * Use upgrade path to change sponsorship Sponsorships need to be annual to match the GB add-on charge rate * Use organization and auth to find organization sponsorship * Add resend sponsorship offer api endpoint * Fix double email send * Fix sponsorship upgrade options * Add is sponsored item to subscription response * Add sponsorship validation to upcoming invoice webhook * Add sponsorship validation to upcoming invoice webhook * Fix organization delete sponsorship hooks * Test org sponsorship service * Fix sproc * Fix build error * Update emails * Fix tests * Skip local test * Add newline * Fix stripe subscription update * Finish emails * Skip test * Fix unit tests * Remove unused variable * Fix unit tests * Switch to handlebars ifs * Remove ending email * Remove reconfirmation template * Switch naming convention * Switch naming convention * Fix migration * Update copy and links * Switch to using Guid in the method * Remove unneeded css styles * Add sql files to Sql.sqlproj * Removed old comments * Made name more verbose * Fix SQL error * Move unit tests to service * Fix sp * Revert "Move unit tests to service" This reverts commit 1185bf3ec8ca36ccd75717ed2463adf8885159a6. * Do repository validation in service layer * Fix tests * Fix merge conflicts and remove TODO * Remove unneeded models * Fix spacing and formatting * Switch Org -> Organization * Remove single use variables * Switch method name * Fix Controller * Switch to obfuscating email * Fix unit tests Co-authored-by: Justin Baur <admin@justinbaur.com>
2021-11-19 23:25:06 +01:00
using System.Text.Json;
using Bit.Core.Entities;
using Bit.Core.Enums;
using Bit.Core.Exceptions;
using Bit.Core.Models.Data.Organizations.Policies;
using Bit.Core.Repositories;
using Bit.Core.Services;
using Bit.Core.Test.AutoFixture.CurrentContextFixtures;
using Bit.Core.Test.Entities;
using Bit.Core.Test.Tools.AutoFixture.SendFixtures;
using Bit.Core.Tools.Entities;
using Bit.Core.Tools.Enums;
using Bit.Core.Tools.Models.Data;
using Bit.Core.Tools.Repositories;
using Bit.Core.Tools.Services;
Families for Enterprise (#1714) * Create common test infrastructure project * Add helpers to further type PlanTypes * Enable testing of ASP.net MVC controllers Controller properties have all kinds of validations in the background. In general, we don't user properties on our Controllers, so the easiest way to allow for Autofixture-based testing of our Controllers is to just omit setting all properties on them. * Workaround for broken MemberAutoDataAttribute https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only the first test case is pulled for this attribute. This is a workaround that populates the provided parameters, left to right, using AutoFixture to populate any remaining. * WIP: Organization sponsorship flow * Add Attribute to use the Bit Autodata dependency chain BitAutoDataAttribute is used to mark a Theory as autopopulating parameters. Extract common attribute methods to to a helper class. Cannot inherit a common base, since both require inheriting from different Xunit base classes to work. * WIP: scaffolding for families for enterprise sponsorship flow * Fix broken tests * Create sponsorship offer (#1688) * Initial db work (#1687) * Add organization sponsorship databases to all providers * Generalize create and update for database, specialize in code * Add PlanSponsorshipType to db model * Write valid json for test entries * Initial scaffolding of emails (#1686) * Initial scaffolding of emails * Work on adding models for FamilyForEnterprise emails * Switch verbage * Put preliminary copy in emails * Skip test * Families for enterprise/stripe integrations (#1699) * Add PlanSponsorshipType to static store * Add sponsorship type to token and creates sponsorship * PascalCase properties * Require sponsorship for remove * Create subscription sponsorship helper class * Handle Sponsored subscription changes * Add sponsorship id to subscription metadata * Make sponsoring references nullable This state indicates that a sponsorship has lapsed, but was not able to be reverted for billing reasons * WIP: Validate and remove subscriptions * Update sponsorships on organization and org user delete * Add friendly name to organization sponsorship * Add sponsorship available boolean to orgDetails * Add sponsorship service to DI * Use userId to find org users * Send f4e offer email * Simplify names of f4e mail messages * Fix Stripe org default tax rates * Universal sponsorship redeem api * Populate user in current context * Add product type to organization details * Use upgrade path to change sponsorship Sponsorships need to be annual to match the GB add-on charge rate * Use organization and auth to find organization sponsorship * Add resend sponsorship offer api endpoint * Fix double email send * Fix sponsorship upgrade options * Add is sponsored item to subscription response * Add sponsorship validation to upcoming invoice webhook * Add sponsorship validation to upcoming invoice webhook * Fix organization delete sponsorship hooks * Test org sponsorship service * Fix sproc * Create common test infrastructure project * Add helpers to further type PlanTypes * Enable testing of ASP.net MVC controllers Controller properties have all kinds of validations in the background. In general, we don't user properties on our Controllers, so the easiest way to allow for Autofixture-based testing of our Controllers is to just omit setting all properties on them. * Workaround for broken MemberAutoDataAttribute https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only the first test case is pulled for this attribute. This is a workaround that populates the provided parameters, left to right, using AutoFixture to populate any remaining. * WIP: Organization sponsorship flow * Add Attribute to use the Bit Autodata dependency chain BitAutoDataAttribute is used to mark a Theory as autopopulating parameters. Extract common attribute methods to to a helper class. Cannot inherit a common base, since both require inheriting from different Xunit base classes to work. * WIP: scaffolding for families for enterprise sponsorship flow * Fix broken tests * Create sponsorship offer (#1688) * Initial db work (#1687) * Add organization sponsorship databases to all providers * Generalize create and update for database, specialize in code * Add PlanSponsorshipType to db model * Write valid json for test entries * Initial scaffolding of emails (#1686) * Initial scaffolding of emails * Work on adding models for FamilyForEnterprise emails * Switch verbage * Put preliminary copy in emails * Skip test * Families for enterprise/stripe integrations (#1699) * Add PlanSponsorshipType to static store * Add sponsorship type to token and creates sponsorship * PascalCase properties * Require sponsorship for remove * Create subscription sponsorship helper class * Handle Sponsored subscription changes * Add sponsorship id to subscription metadata * Make sponsoring references nullable This state indicates that a sponsorship has lapsed, but was not able to be reverted for billing reasons * WIP: Validate and remove subscriptions * Update sponsorships on organization and org user delete * Add friendly name to organization sponsorship * Add sponsorship available boolean to orgDetails * Add sponsorship service to DI * Use userId to find org users * Send f4e offer email * Simplify names of f4e mail messages * Fix Stripe org default tax rates * Universal sponsorship redeem api * Populate user in current context * Add product type to organization details * Use upgrade path to change sponsorship Sponsorships need to be annual to match the GB add-on charge rate * Use organization and auth to find organization sponsorship * Add resend sponsorship offer api endpoint * Fix double email send * Fix sponsorship upgrade options * Add is sponsored item to subscription response * Add sponsorship validation to upcoming invoice webhook * Add sponsorship validation to upcoming invoice webhook * Fix organization delete sponsorship hooks * Test org sponsorship service * Fix sproc * Fix build error * Update emails * Fix tests * Skip local test * Add newline * Fix stripe subscription update * Finish emails * Skip test * Fix unit tests * Remove unused variable * Fix unit tests * Switch to handlebars ifs * Remove ending email * Remove reconfirmation template * Switch naming convention * Switch naming convention * Fix migration * Update copy and links * Switch to using Guid in the method * Remove unneeded css styles * Add sql files to Sql.sqlproj * Removed old comments * Made name more verbose * Fix SQL error * Move unit tests to service * Fix sp * Revert "Move unit tests to service" This reverts commit 1185bf3ec8ca36ccd75717ed2463adf8885159a6. * Do repository validation in service layer * Fix tests * Fix merge conflicts and remove TODO * Remove unneeded models * Fix spacing and formatting * Switch Org -> Organization * Remove single use variables * Switch method name * Fix Controller * Switch to obfuscating email * Fix unit tests Co-authored-by: Justin Baur <admin@justinbaur.com>
2021-11-19 23:25:06 +01:00
using Bit.Test.Common.AutoFixture;
using Bit.Test.Common.AutoFixture.Attributes;
using Microsoft.AspNetCore.Identity;
using NSubstitute;
using Xunit;
namespace Bit.Core.Test.Tools.Services;
2022-08-29 22:06:55 +02:00
[SutProviderCustomize]
[CurrentContextCustomize]
[UserSendCustomize]
public class SendServiceTests
{
private void SaveSendAsync_Setup(SendType sendType, bool disableSendPolicyAppliesToUser,
SutProvider<SendService> sutProvider, Send send)
{
send.Id = default;
send.Type = sendType;
sutProvider.GetDependency<IPolicyRepository>().GetCountByTypeApplicableToUserIdAsync(
Arg.Any<Guid>(), PolicyType.DisableSend).Returns(disableSendPolicyAppliesToUser ? 1 : 0);
}
// Disable Send policy check
[Theory]
[BitAutoData(SendType.File)]
[BitAutoData(SendType.Text)]
public async void SaveSendAsync_DisableSend_Applies_throws(SendType sendType,
SutProvider<SendService> sutProvider, Send send)
{
SaveSendAsync_Setup(sendType, disableSendPolicyAppliesToUser: true, sutProvider, send);
await Assert.ThrowsAsync<BadRequestException>(() => sutProvider.Sut.SaveSendAsync(send));
}
[Theory]
[BitAutoData(SendType.File)]
[BitAutoData(SendType.Text)]
public async void SaveSendAsync_DisableSend_DoesntApply_success(SendType sendType,
SutProvider<SendService> sutProvider, Send send)
{
SaveSendAsync_Setup(sendType, disableSendPolicyAppliesToUser: false, sutProvider, send);
await sutProvider.Sut.SaveSendAsync(send);
2022-08-29 20:53:16 +02:00
await sutProvider.GetDependency<ISendRepository>().Received(1).CreateAsync(send);
}
2022-08-29 22:06:55 +02:00
// Send Options Policy - Disable Hide Email check
private void SaveSendAsync_HideEmail_Setup(bool disableHideEmailAppliesToUser,
SutProvider<SendService> sutProvider, Send send, Policy policy)
2022-08-29 22:06:55 +02:00
{
send.HideEmail = true;
var sendOptions = new SendOptionsPolicyData
2022-08-29 22:06:55 +02:00
{
DisableHideEmail = disableHideEmailAppliesToUser
2022-08-29 22:06:55 +02:00
};
policy.Data = JsonSerializer.Serialize(sendOptions, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
});
sutProvider.GetDependency<IPolicyRepository>().GetManyByTypeApplicableToUserIdAsync(
Arg.Any<Guid>(), PolicyType.SendOptions).Returns(new List<Policy>
{
policy,
});
2022-08-29 22:06:55 +02:00
}
[Theory]
[BitAutoData(SendType.File)]
[BitAutoData(SendType.Text)]
public async void SaveSendAsync_DisableHideEmail_Applies_throws(SendType sendType,
SutProvider<SendService> sutProvider, Send send, Policy policy)
{
SaveSendAsync_Setup(sendType, false, sutProvider, send);
SaveSendAsync_HideEmail_Setup(true, sutProvider, send, policy);
await Assert.ThrowsAsync<BadRequestException>(() => sutProvider.Sut.SaveSendAsync(send));
}
[Theory]
[BitAutoData(SendType.File)]
[BitAutoData(SendType.Text)]
public async void SaveSendAsync_DisableHideEmail_DoesntApply_success(SendType sendType,
SutProvider<SendService> sutProvider, Send send, Policy policy)
{
SaveSendAsync_Setup(sendType, false, sutProvider, send);
SaveSendAsync_HideEmail_Setup(false, sutProvider, send, policy);
await sutProvider.Sut.SaveSendAsync(send);
await sutProvider.GetDependency<ISendRepository>().Received(1).CreateAsync(send);
}
[Theory]
[BitAutoData]
public async void SaveSendAsync_ExistingSend_Updates(SutProvider<SendService> sutProvider,
Send send)
{
send.Id = Guid.NewGuid();
var now = DateTime.UtcNow;
await sutProvider.Sut.SaveSendAsync(send);
Assert.True(send.RevisionDate - now < TimeSpan.FromSeconds(1));
await sutProvider.GetDependency<ISendRepository>()
.Received(1)
.UpsertAsync(send);
await sutProvider.GetDependency<IPushNotificationService>()
.Received(1)
.PushSyncSendUpdateAsync(send);
}
[Theory]
[BitAutoData]
public async void SaveFileSendAsync_TextType_ThrowsBadRequest(SutProvider<SendService> sutProvider,
Send send)
{
send.Type = SendType.Text;
var badRequest = await Assert.ThrowsAsync<BadRequestException>(() =>
sutProvider.Sut.SaveFileSendAsync(send, null, 0)
);
Assert.Contains("not of type \"file\"", badRequest.Message, StringComparison.InvariantCultureIgnoreCase);
}
[Theory]
[BitAutoData]
public async void SaveFileSendAsync_EmptyFile_ThrowsBadRequest(SutProvider<SendService> sutProvider,
Send send)
{
send.Type = SendType.File;
var badRequest = await Assert.ThrowsAsync<BadRequestException>(() =>
sutProvider.Sut.SaveFileSendAsync(send, null, 0)
);
Assert.Contains("no file data", badRequest.Message, StringComparison.InvariantCultureIgnoreCase);
}
[Theory]
[BitAutoData]
public async void SaveFileSendAsync_UserCannotAccessPremium_ThrowsBadRequest(SutProvider<SendService> sutProvider,
Send send)
2022-08-29 22:06:55 +02:00
{
var user = new User
{
Id = Guid.NewGuid(),
};
2022-08-29 20:53:16 +02:00
send.UserId = user.Id;
send.Type = SendType.File;
2022-08-29 20:53:16 +02:00
sutProvider.GetDependency<IUserRepository>()
.GetByIdAsync(user.Id)
.Returns(user);
2022-08-29 20:53:16 +02:00
sutProvider.GetDependency<IUserService>()
.CanAccessPremium(user)
.Returns(false);
2022-08-29 20:53:16 +02:00
var badRequest = await Assert.ThrowsAsync<BadRequestException>(() =>
sutProvider.Sut.SaveFileSendAsync(send, null, 1)
);
2022-08-29 20:53:16 +02:00
Assert.Contains("must have premium", badRequest.Message, StringComparison.InvariantCultureIgnoreCase);
}
2022-08-29 20:53:16 +02:00
[Theory]
[BitAutoData]
public async void SaveFileSendAsync_UserHasUnconfirmedEmail_ThrowsBadRequest(SutProvider<SendService> sutProvider,
Send send)
2022-08-29 22:06:55 +02:00
{
var user = new User
{
Id = Guid.NewGuid(),
EmailVerified = false,
};
2022-08-29 20:53:16 +02:00
send.UserId = user.Id;
send.Type = SendType.File;
2022-08-29 20:53:16 +02:00
sutProvider.GetDependency<IUserRepository>()
.GetByIdAsync(user.Id)
.Returns(user);
2022-08-29 20:53:16 +02:00
sutProvider.GetDependency<IUserService>()
.CanAccessPremium(user)
.Returns(true);
2022-08-29 20:53:16 +02:00
var badRequest = await Assert.ThrowsAsync<BadRequestException>(() =>
sutProvider.Sut.SaveFileSendAsync(send, null, 1)
);
2022-08-29 20:53:16 +02:00
Assert.Contains("must confirm your email", badRequest.Message, StringComparison.InvariantCultureIgnoreCase);
}
2022-08-29 20:53:16 +02:00
[Theory]
[BitAutoData]
public async void SaveFileSendAsync_UserCanAccessPremium_HasNoStorage_ThrowsBadRequest(SutProvider<SendService> sutProvider,
Send send)
2022-08-29 22:06:55 +02:00
{
var user = new User
2022-08-29 20:53:16 +02:00
{
Id = Guid.NewGuid(),
EmailVerified = true,
Premium = true,
MaxStorageGb = null,
Storage = 0,
};
2022-08-29 22:06:55 +02:00
send.UserId = user.Id;
send.Type = SendType.File;
2022-08-29 22:06:55 +02:00
sutProvider.GetDependency<IUserRepository>()
.GetByIdAsync(user.Id)
.Returns(user);
2022-08-29 22:06:55 +02:00
sutProvider.GetDependency<IUserService>()
.CanAccessPremium(user)
.Returns(true);
2022-08-29 22:06:55 +02:00
var badRequest = await Assert.ThrowsAsync<BadRequestException>(() =>
sutProvider.Sut.SaveFileSendAsync(send, null, 1)
);
2022-08-29 22:06:55 +02:00
Assert.Contains("not enough storage", badRequest.Message, StringComparison.InvariantCultureIgnoreCase);
}
2022-08-29 22:06:55 +02:00
[Theory]
[BitAutoData]
public async void SaveFileSendAsync_UserCanAccessPremium_StorageFull_ThrowsBadRequest(SutProvider<SendService> sutProvider,
Send send)
2022-08-29 22:06:55 +02:00
{
var user = new User
{
Id = Guid.NewGuid(),
EmailVerified = true,
Premium = true,
MaxStorageGb = 2,
Storage = 2 * UserTests.Multiplier,
};
2022-08-29 22:06:55 +02:00
send.UserId = user.Id;
send.Type = SendType.File;
2022-08-29 22:06:55 +02:00
sutProvider.GetDependency<IUserRepository>()
.GetByIdAsync(user.Id)
.Returns(user);
2022-08-29 22:06:55 +02:00
sutProvider.GetDependency<IUserService>()
.CanAccessPremium(user)
.Returns(true);
2022-08-29 22:06:55 +02:00
var badRequest = await Assert.ThrowsAsync<BadRequestException>(() =>
sutProvider.Sut.SaveFileSendAsync(send, null, 1)
);
2022-08-29 22:06:55 +02:00
Assert.Contains("not enough storage", badRequest.Message, StringComparison.InvariantCultureIgnoreCase);
}
2022-08-29 22:06:55 +02:00
[Theory]
[BitAutoData]
public async void SaveFileSendAsync_UserCanAccessPremium_IsNotPremium_IsSelfHosted_GiantFile_ThrowsBadRequest(SutProvider<SendService> sutProvider,
Send send)
2022-08-29 22:06:55 +02:00
{
var user = new User
{
Id = Guid.NewGuid(),
EmailVerified = true,
Premium = false,
};
send.UserId = user.Id;
send.Type = SendType.File;
sutProvider.GetDependency<IUserRepository>()
.GetByIdAsync(user.Id)
.Returns(user);
sutProvider.GetDependency<IUserService>()
.CanAccessPremium(user)
.Returns(true);
sutProvider.GetDependency<Settings.GlobalSettings>()
.SelfHosted = true;
var badRequest = await Assert.ThrowsAsync<BadRequestException>(() =>
sutProvider.Sut.SaveFileSendAsync(send, null, 11000 * UserTests.Multiplier)
);
Assert.Contains("not enough storage", badRequest.Message, StringComparison.InvariantCultureIgnoreCase);
}
[Theory]
[BitAutoData]
public async void SaveFileSendAsync_UserCanAccessPremium_IsNotPremium_IsNotSelfHosted_TwoGigabyteFile_ThrowsBadRequest(SutProvider<SendService> sutProvider,
Send send)
2022-08-29 22:06:55 +02:00
{
var user = new User
{
Id = Guid.NewGuid(),
EmailVerified = true,
Premium = false,
};
send.UserId = user.Id;
send.Type = SendType.File;
sutProvider.GetDependency<IUserRepository>()
.GetByIdAsync(user.Id)
.Returns(user);
sutProvider.GetDependency<IUserService>()
.CanAccessPremium(user)
.Returns(true);
sutProvider.GetDependency<Settings.GlobalSettings>()
.SelfHosted = false;
var badRequest = await Assert.ThrowsAsync<BadRequestException>(() =>
sutProvider.Sut.SaveFileSendAsync(send, null, 2 * UserTests.Multiplier)
);
Assert.Contains("not enough storage", badRequest.Message, StringComparison.InvariantCultureIgnoreCase);
}
[Theory]
[BitAutoData]
public async void SaveFileSendAsync_ThroughOrg_MaxStorageIsNull_ThrowsBadRequest(SutProvider<SendService> sutProvider,
Send send)
2022-08-29 22:06:55 +02:00
{
var org = new Organization
{
Id = Guid.NewGuid(),
MaxStorageGb = null,
};
send.UserId = null;
send.OrganizationId = org.Id;
send.Type = SendType.File;
sutProvider.GetDependency<IOrganizationRepository>()
.GetByIdAsync(org.Id)
.Returns(org);
var badRequest = await Assert.ThrowsAsync<BadRequestException>(() =>
sutProvider.Sut.SaveFileSendAsync(send, null, 1)
);
Assert.Contains("organization cannot use file sends", badRequest.Message, StringComparison.InvariantCultureIgnoreCase);
}
[Theory]
[BitAutoData]
public async void SaveFileSendAsync_ThroughOrg_MaxStorageIsNull_TwoGBFile_ThrowsBadRequest(SutProvider<SendService> sutProvider,
Send send)
2022-08-29 22:06:55 +02:00
{
var org = new Organization
{
Id = Guid.NewGuid(),
MaxStorageGb = null,
};
send.UserId = null;
send.OrganizationId = org.Id;
send.Type = SendType.File;
sutProvider.GetDependency<IOrganizationRepository>()
.GetByIdAsync(org.Id)
.Returns(org);
var badRequest = await Assert.ThrowsAsync<BadRequestException>(() =>
sutProvider.Sut.SaveFileSendAsync(send, null, 1)
);
Assert.Contains("organization cannot use file sends", badRequest.Message, StringComparison.InvariantCultureIgnoreCase);
}
[Theory]
[BitAutoData]
public async void SaveFileSendAsync_ThroughOrg_MaxStorageIsOneGB_TwoGBFile_ThrowsBadRequest(SutProvider<SendService> sutProvider,
Send send)
2022-08-29 22:06:55 +02:00
{
var org = new Organization
{
Id = Guid.NewGuid(),
MaxStorageGb = 1,
};
send.UserId = null;
send.OrganizationId = org.Id;
send.Type = SendType.File;
sutProvider.GetDependency<IOrganizationRepository>()
.GetByIdAsync(org.Id)
.Returns(org);
var badRequest = await Assert.ThrowsAsync<BadRequestException>(() =>
sutProvider.Sut.SaveFileSendAsync(send, null, 2 * UserTests.Multiplier)
);
Assert.Contains("not enough storage", badRequest.Message, StringComparison.InvariantCultureIgnoreCase);
}
[Theory]
[BitAutoData]
public async void SaveFileSendAsync_HasEnouphStorage_Success(SutProvider<SendService> sutProvider,
Send send)
2022-08-29 22:06:55 +02:00
{
var user = new User
{
Id = Guid.NewGuid(),
EmailVerified = true,
MaxStorageGb = 10,
};
var data = new SendFileData
{
};
send.UserId = user.Id;
send.Type = SendType.File;
var testUrl = "https://test.com/";
sutProvider.GetDependency<IUserRepository>()
.GetByIdAsync(user.Id)
.Returns(user);
sutProvider.GetDependency<IUserService>()
.CanAccessPremium(user)
.Returns(true);
sutProvider.GetDependency<ISendFileStorageService>()
.GetSendFileUploadUrlAsync(send, Arg.Any<string>())
.Returns(testUrl);
var utcNow = DateTime.UtcNow;
var url = await sutProvider.Sut.SaveFileSendAsync(send, data, 1 * UserTests.Multiplier);
Assert.Equal(testUrl, url);
Assert.True(send.RevisionDate - utcNow < TimeSpan.FromSeconds(1));
await sutProvider.GetDependency<ISendFileStorageService>()
.Received(1)
.GetSendFileUploadUrlAsync(send, Arg.Any<string>());
await sutProvider.GetDependency<ISendRepository>()
.Received(1)
.UpsertAsync(send);
await sutProvider.GetDependency<IPushNotificationService>()
.Received(1)
.PushSyncSendUpdateAsync(send);
}
[Theory]
[BitAutoData]
public async void SaveFileSendAsync_HasEnouphStorage_SendFileThrows_CleansUp(SutProvider<SendService> sutProvider,
Send send)
2022-08-29 22:06:55 +02:00
{
var user = new User
{
Id = Guid.NewGuid(),
EmailVerified = true,
MaxStorageGb = 10,
};
var data = new SendFileData
{
};
send.UserId = user.Id;
send.Type = SendType.File;
sutProvider.GetDependency<IUserRepository>()
.GetByIdAsync(user.Id)
.Returns(user);
sutProvider.GetDependency<IUserService>()
.CanAccessPremium(user)
.Returns(true);
sutProvider.GetDependency<ISendFileStorageService>()
.GetSendFileUploadUrlAsync(send, Arg.Any<string>())
.Returns<string>(callInfo => throw new Exception("Problem"));
var utcNow = DateTime.UtcNow;
var exception = await Assert.ThrowsAsync<Exception>(() =>
sutProvider.Sut.SaveFileSendAsync(send, data, 1 * UserTests.Multiplier)
);
2022-08-29 20:53:16 +02:00
Assert.True(send.RevisionDate - utcNow < TimeSpan.FromSeconds(1));
Assert.Equal("Problem", exception.Message);
await sutProvider.GetDependency<ISendFileStorageService>()
.Received(1)
.GetSendFileUploadUrlAsync(send, Arg.Any<string>());
await sutProvider.GetDependency<ISendRepository>()
.Received(1)
.UpsertAsync(send);
await sutProvider.GetDependency<IPushNotificationService>()
.Received(1)
.PushSyncSendUpdateAsync(send);
await sutProvider.GetDependency<ISendFileStorageService>()
.Received(1)
.DeleteFileAsync(send, Arg.Any<string>());
2022-08-29 20:53:16 +02:00
}
[Theory]
[BitAutoData]
public async void UpdateFileToExistingSendAsync_SendNull_ThrowsBadRequest(SutProvider<SendService> sutProvider)
2022-08-29 20:53:16 +02:00
{
2022-08-29 22:06:55 +02:00
var badRequest = await Assert.ThrowsAsync<BadRequestException>(() =>
sutProvider.Sut.UploadFileToExistingSendAsync(new MemoryStream(), null)
2022-08-29 22:06:55 +02:00
);
Assert.Contains("does not have file data", badRequest.Message, StringComparison.InvariantCultureIgnoreCase);
2022-08-29 22:06:55 +02:00
}
[Theory]
[BitAutoData]
public async void UpdateFileToExistingSendAsync_SendDataNull_ThrowsBadRequest(SutProvider<SendService> sutProvider,
Send send)
2022-08-29 22:06:55 +02:00
{
send.Data = null;
var badRequest = await Assert.ThrowsAsync<BadRequestException>(() =>
sutProvider.Sut.UploadFileToExistingSendAsync(new MemoryStream(), send)
);
Assert.Contains("does not have file data", badRequest.Message, StringComparison.InvariantCultureIgnoreCase);
2022-08-29 22:06:55 +02:00
}
[Theory]
[BitAutoData]
public async void UpdateFileToExistingSendAsync_NotFileType_ThrowsBadRequest(SutProvider<SendService> sutProvider,
Send send)
2022-08-29 22:06:55 +02:00
{
var badRequest = await Assert.ThrowsAsync<BadRequestException>(() =>
sutProvider.Sut.UploadFileToExistingSendAsync(new MemoryStream(), send)
);
Assert.Contains("not a file type send", badRequest.Message, StringComparison.InvariantCultureIgnoreCase);
2022-08-29 22:06:55 +02:00
}
[Theory]
[BitAutoData]
public async void UpdateFileToExistingSendAsync_Success(SutProvider<SendService> sutProvider,
Send send)
2022-08-29 22:06:55 +02:00
{
var fileContents = "Test file content";
var sendFileData = new SendFileData
{
Id = "TEST",
Size = fileContents.Length,
Validated = false,
};
send.Type = SendType.File;
send.Data = JsonSerializer.Serialize(sendFileData);
sutProvider.GetDependency<ISendFileStorageService>()
.ValidateFileAsync(send, sendFileData.Id, sendFileData.Size, Arg.Any<long>())
.Returns((true, sendFileData.Size));
await sutProvider.Sut.UploadFileToExistingSendAsync(new MemoryStream(Encoding.UTF8.GetBytes(fileContents)), send);
2022-08-29 22:06:55 +02:00
}
[Theory]
[BitAutoData]
public async void UpdateFileToExistingSendAsync_InvalidSize(SutProvider<SendService> sutProvider,
Send send)
2022-08-29 22:06:55 +02:00
{
var fileContents = "Test file content";
2022-08-29 20:53:16 +02:00
var sendFileData = new SendFileData
{
Id = "TEST",
Size = fileContents.Length,
};
2022-08-29 20:53:16 +02:00
send.Type = SendType.File;
send.Data = JsonSerializer.Serialize(sendFileData);
2022-08-29 20:53:16 +02:00
sutProvider.GetDependency<ISendFileStorageService>()
.ValidateFileAsync(send, sendFileData.Id, sendFileData.Size, Arg.Any<long>())
.Returns((false, sendFileData.Size));
2022-08-29 20:53:16 +02:00
var badRequest = await Assert.ThrowsAsync<BadRequestException>(() =>
sutProvider.Sut.UploadFileToExistingSendAsync(new MemoryStream(Encoding.UTF8.GetBytes(fileContents)), send)
);
2022-08-29 22:06:55 +02:00
}
2022-08-29 20:53:16 +02:00
[Theory]
[BitAutoData]
public void SendCanBeAccessed_Success(SutProvider<SendService> sutProvider, Send send)
2022-08-29 22:06:55 +02:00
{
var now = DateTime.UtcNow;
send.MaxAccessCount = 10;
send.AccessCount = 5;
send.ExpirationDate = now.AddYears(1);
send.DeletionDate = now.AddYears(1);
send.Disabled = false;
2022-08-29 22:06:55 +02:00
sutProvider.GetDependency<IPasswordHasher<User>>()
.VerifyHashedPassword(Arg.Any<User>(), send.Password, "TEST")
.Returns(PasswordVerificationResult.Success);
2022-08-29 22:06:55 +02:00
var (grant, passwordRequiredError, passwordInvalidError)
= sutProvider.Sut.SendCanBeAccessed(send, "TEST");
2022-08-29 22:06:55 +02:00
Assert.True(grant);
Assert.False(passwordRequiredError);
Assert.False(passwordInvalidError);
}
2022-08-29 20:53:16 +02:00
[Theory]
[BitAutoData]
public void SendCanBeAccessed_NullMaxAccess_Success(SutProvider<SendService> sutProvider,
Send send)
{
var now = DateTime.UtcNow;
send.MaxAccessCount = null;
send.AccessCount = 5;
send.ExpirationDate = now.AddYears(1);
send.DeletionDate = now.AddYears(1);
send.Disabled = false;
2022-08-29 22:06:55 +02:00
sutProvider.GetDependency<IPasswordHasher<User>>()
.VerifyHashedPassword(Arg.Any<User>(), send.Password, "TEST")
.Returns(PasswordVerificationResult.Success);
2022-08-29 22:06:55 +02:00
var (grant, passwordRequiredError, passwordInvalidError)
= sutProvider.Sut.SendCanBeAccessed(send, "TEST");
2022-08-29 22:06:55 +02:00
Assert.True(grant);
Assert.False(passwordRequiredError);
Assert.False(passwordInvalidError);
}
2022-08-29 22:06:55 +02:00
[Theory]
[BitAutoData]
public void SendCanBeAccessed_NullSend_DoesNotGrantAccess(SutProvider<SendService> sutProvider)
{
sutProvider.GetDependency<IPasswordHasher<User>>()
.VerifyHashedPassword(Arg.Any<User>(), "TEST", "TEST")
.Returns(PasswordVerificationResult.Success);
2022-08-29 22:06:55 +02:00
var (grant, passwordRequiredError, passwordInvalidError)
= sutProvider.Sut.SendCanBeAccessed(null, "TEST");
2022-08-29 22:06:55 +02:00
Assert.False(grant);
Assert.False(passwordRequiredError);
Assert.False(passwordInvalidError);
}
2022-08-29 22:06:55 +02:00
[Theory]
[BitAutoData]
public void SendCanBeAccessed_NullPassword_PasswordRequiredErrorReturnsTrue(SutProvider<SendService> sutProvider,
Send send)
2022-08-29 22:06:55 +02:00
{
var now = DateTime.UtcNow;
send.MaxAccessCount = null;
send.AccessCount = 5;
send.ExpirationDate = now.AddYears(1);
send.DeletionDate = now.AddYears(1);
send.Disabled = false;
send.Password = "HASH";
2022-08-29 22:06:55 +02:00
sutProvider.GetDependency<IPasswordHasher<User>>()
.VerifyHashedPassword(Arg.Any<User>(), "TEST", "TEST")
.Returns(PasswordVerificationResult.Success);
2022-08-29 22:06:55 +02:00
var (grant, passwordRequiredError, passwordInvalidError)
= sutProvider.Sut.SendCanBeAccessed(send, null);
2022-08-29 22:06:55 +02:00
Assert.False(grant);
Assert.True(passwordRequiredError);
Assert.False(passwordInvalidError);
}
2022-08-29 22:06:55 +02:00
[Theory]
[BitAutoData]
public void SendCanBeAccessed_RehashNeeded_RehashesPassword(SutProvider<SendService> sutProvider,
Send send)
{
var now = DateTime.UtcNow;
send.MaxAccessCount = null;
send.AccessCount = 5;
send.ExpirationDate = now.AddYears(1);
send.DeletionDate = now.AddYears(1);
send.Disabled = false;
send.Password = "TEST";
2022-08-29 22:06:55 +02:00
sutProvider.GetDependency<IPasswordHasher<User>>()
.VerifyHashedPassword(Arg.Any<User>(), "TEST", "TEST")
.Returns(PasswordVerificationResult.SuccessRehashNeeded);
2022-08-29 22:06:55 +02:00
var (grant, passwordRequiredError, passwordInvalidError)
= sutProvider.Sut.SendCanBeAccessed(send, "TEST");
2022-08-29 22:06:55 +02:00
sutProvider.GetDependency<IPasswordHasher<User>>()
.Received(1)
.HashPassword(Arg.Any<User>(), "TEST");
2022-08-29 22:06:55 +02:00
Assert.True(grant);
Assert.False(passwordRequiredError);
Assert.False(passwordInvalidError);
}
2022-08-29 22:06:55 +02:00
[Theory]
[BitAutoData]
public void SendCanBeAccessed_VerifyFailed_PasswordInvalidReturnsTrue(SutProvider<SendService> sutProvider,
Send send)
{
var now = DateTime.UtcNow;
send.MaxAccessCount = null;
send.AccessCount = 5;
send.ExpirationDate = now.AddYears(1);
send.DeletionDate = now.AddYears(1);
send.Disabled = false;
send.Password = "TEST";
2022-08-29 22:06:55 +02:00
sutProvider.GetDependency<IPasswordHasher<User>>()
.VerifyHashedPassword(Arg.Any<User>(), "TEST", "TEST")
.Returns(PasswordVerificationResult.Failed);
2022-08-29 22:06:55 +02:00
var (grant, passwordRequiredError, passwordInvalidError)
= sutProvider.Sut.SendCanBeAccessed(send, "TEST");
2022-08-29 22:06:55 +02:00
Assert.False(grant);
Assert.False(passwordRequiredError);
Assert.True(passwordInvalidError);
}
}