Пример #1
0
        public async Task Needs2FABecauseNewDeviceAsync_ReturnsTrue(SutProvider <UserService> sutProvider, User user)
        {
            user.Id            = Guid.NewGuid();
            user.EmailVerified = true;
            const string deviceIdToCheck = "7b01b586-b210-499f-8d52-0c3fdaa646fc";
            const string deviceIdInRepo  = "ea29126c-91b7-4cc4-8ce6-00105b37f64a";

            sutProvider.GetDependency <IDeviceRepository>()
            .GetManyByUserIdAsync(user.Id)
            .Returns(Task.FromResult <ICollection <Device> >(new List <Device>
            {
                new Device {
                    Identifier = deviceIdInRepo
                }
            }));

            Assert.True(await sutProvider.Sut.Needs2FABecauseNewDeviceAsync(user, deviceIdToCheck, "password"));
        }
Пример #2
0
        public async Task DeleteWithServerAsync_Success(SutProvider <SendService> sutProvider, string userId, IEnumerable <SendData> sendDatas)
        {
            var initialSendDatas = sendDatas.ToDictionary(d => d.Id, d => d);
            var idToDelete       = initialSendDatas.First().Key;
            var expectedSends    = initialSendDatas.Skip(1).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            sutProvider.GetDependency <IUserService>().GetUserIdAsync().Returns(userId);
            sutProvider.GetDependency <IStorageService>()
            .GetAsync <Dictionary <string, SendData> >(Arg.Any <string>()).Returns(initialSendDatas);

            await sutProvider.Sut.DeleteWithServerAsync(idToDelete);

            await sutProvider.GetDependency <IApiService>().Received(1).DeleteSendAsync(idToDelete);

            await sutProvider.GetDependency <IStorageService>().Received(1)
            .SaveAsync(GetSendKey(userId),
                       Arg.Is <Dictionary <string, SendData> >(s => TestHelper.AssertEqualExpectedPredicate(expectedSends)(s)));
        }
Пример #3
0
        // SendOptionsPolicy.DisableHideEmail check

        private void SaveSendAsync_DisableHideEmail_Setup(SendType sendType, bool canManagePolicies,
                                                          SutProvider <SendService> sutProvider, Send send, List <Policy> policies)
        {
            send.Id        = default;
            send.Type      = sendType;
            send.HideEmail = true;

            var dataObj = new SendOptionsPolicyData();

            dataObj.DisableHideEmail = true;

            policies.First().Type    = PolicyType.SendOptions;
            policies.First().Enabled = true;
            policies.First().Data    = JsonConvert.SerializeObject(dataObj);

            sutProvider.GetDependency <IPolicyRepository>().GetManyByUserIdAsync(send.UserId.Value).Returns(policies);
            sutProvider.GetDependency <ICurrentContext>().ManagePolicies(Arg.Any <Guid>()).Returns(canManagePolicies);
        }
Пример #4
0
        public async Task DeleteAsync_Success(int numberToDelete, SutProvider <SendService> sutProvider, string userId, IEnumerable <SendData> sendDatas)
        {
            var actualSendDataDict = sendDatas.ToDictionary(d => d.Id, d => d);

            sutProvider.GetDependency <IUserService>().GetUserIdAsync().Returns(userId);
            sutProvider.GetDependency <IStorageService>()
            .GetAsync <Dictionary <string, SendData> >(GetSendKey(userId)).Returns(actualSendDataDict);

            var idsToDelete   = actualSendDataDict.Take(numberToDelete).Select(kvp => kvp.Key).ToArray();
            var expectedSends = actualSendDataDict.Skip(numberToDelete).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            await sutProvider.Sut.DeleteAsync(idsToDelete);


            await sutProvider.GetDependency <IStorageService>().Received(1)
            .SaveAsync(GetSendKey(userId),
                       Arg.Is <Dictionary <string, SendData> >(s => TestHelper.AssertEqualExpectedPredicate(expectedSends)(s)));
        }
Пример #5
0
        public async Task SaveWithServerAsync_PrefersFileUploadService(SutProvider <CipherService> sutProvider,
                                                                       Cipher cipher, string fileName, EncByteArray data, AttachmentUploadDataResponse uploadDataResponse, EncString encKey)
        {
            var encFileName = new EncString(fileName);

            sutProvider.GetDependency <ICryptoService>().EncryptAsync(fileName, Arg.Any <SymmetricCryptoKey>())
            .Returns(encFileName);
            sutProvider.GetDependency <ICryptoService>().EncryptToBytesAsync(data.Buffer, Arg.Any <SymmetricCryptoKey>())
            .Returns(data);
            sutProvider.GetDependency <ICryptoService>().MakeEncKeyAsync(Arg.Any <SymmetricCryptoKey>()).Returns(new Tuple <SymmetricCryptoKey, EncString>(null, encKey));
            sutProvider.GetDependency <IApiService>().PostCipherAttachmentAsync(cipher.Id, Arg.Any <AttachmentRequest>())
            .Returns(uploadDataResponse);

            await sutProvider.Sut.SaveAttachmentRawWithServerAsync(cipher, fileName, data.Buffer);

            await sutProvider.GetDependency <IFileUploadService>().Received(1)
            .UploadCipherAttachmentFileAsync(uploadDataResponse, encFileName, data);
        }
Пример #6
0
        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);
        }
Пример #7
0
        public async Task ShareManyAsync_CorrectRevisionDate_Passes(string revisionDateString,
                                                                    SutProvider <CipherService> sutProvider, IEnumerable <Cipher> ciphers, Organization organization, List <Guid> collectionIds)
        {
            sutProvider.GetDependency <IOrganizationRepository>().GetByIdAsync(organization.Id)
            .Returns(new Organization
            {
                PlanType     = Enums.PlanType.EnterpriseAnnually,
                MaxStorageGb = 100
            });

            var cipherInfos = ciphers.Select(c => (c,
                                                   string.IsNullOrEmpty(revisionDateString) ? null : (DateTime?)c.RevisionDate));
            var sharingUserId = ciphers.First().UserId.Value;

            await sutProvider.Sut.ShareManyAsync(cipherInfos, organization.Id, collectionIds, sharingUserId);

            await sutProvider.GetDependency <ICipherRepository>().Received(1).UpdateCiphersAsync(sharingUserId,
                                                                                                 Arg.Is <IEnumerable <Cipher> >(arg => arg.Except(ciphers).IsNullOrEmpty()));
        }
Пример #8
0
        public async Task ShareManyAsync_FreeOrgWithAttachment_Throws(SutProvider <CipherService> sutProvider,
                                                                      IEnumerable <Cipher> ciphers, Guid organizationId, List <Guid> collectionIds)
        {
            sutProvider.GetDependency <IOrganizationRepository>().GetByIdAsync(organizationId).Returns(new Organization
            {
                PlanType = Enums.PlanType.Free
            });
            ciphers.FirstOrDefault().Attachments =
                "{\"attachment1\":{\"Size\":\"250\",\"FileName\":\"superCoolFile\","
                + "\"Key\":\"superCoolFile\",\"ContainerName\":\"testContainer\",\"Validated\":false}}";

            var cipherInfos = ciphers.Select(c => (c,
                                                   (DateTime?)c.RevisionDate));
            var sharingUserId = ciphers.First().UserId.Value;

            var exception = await Assert.ThrowsAsync <BadRequestException>(
                () => sutProvider.Sut.ShareManyAsync(cipherInfos, organizationId, collectionIds, sharingUserId));

            Assert.Contains("This organization cannot use attachments", exception.Message);
        }
Пример #9
0
        public async void UpdateFileToExistingSendAsync_Success(SutProvider <SendService> sutProvider,
                                                                Send send)
        {
            var fileContents = "Test file content";

            var sendFileData = new SendFileData
            {
                Id   = "TEST",
                Size = fileContents.Length,
            };

            send.Type = SendType.File;
            send.Data = JsonConvert.SerializeObject(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);
        }
        public async Task ValidateSponsorshipAsync_Valid(PlanType planType,
                                                         Organization sponsoredOrg, OrganizationSponsorship existingSponsorship, Organization sponsoringOrg,
                                                         SutProvider <ValidateSponsorshipCommand> sutProvider)
        {
            sponsoringOrg.PlanType = planType;
            sponsoringOrg.Enabled  = true;
            existingSponsorship.SponsoringOrganizationId = sponsoringOrg.Id;

            sutProvider.GetDependency <IOrganizationSponsorshipRepository>()
            .GetBySponsoredOrganizationIdAsync(sponsoredOrg.Id).Returns(existingSponsorship);
            sutProvider.GetDependency <IOrganizationRepository>().GetByIdAsync(sponsoredOrg.Id).Returns(sponsoredOrg);
            sutProvider.GetDependency <IOrganizationRepository>().GetByIdAsync(sponsoringOrg.Id).Returns(sponsoringOrg);

            var result = await sutProvider.Sut.ValidateSponsorshipAsync(sponsoredOrg.Id);

            Assert.True(result);

            await AssertDidNotRemoveSponsoredPaymentAsync(sutProvider);
            await AssertDidNotDeleteSponsorshipAsync(sutProvider);
        }
Пример #11
0
        public async void SaveSendAsync_DisableHideEmail_CantManagePolicies_success(SendType sendType,
                                                                                    SutProvider <SendService> sutProvider, Send send, List <Policy> policies)
        {
            SaveSendAsync_DisableHideEmail_Setup(sendType, canManagePolicies: false, sutProvider, send, policies);

            var policyData = new SendOptionsPolicyData();

            policyData.DisableHideEmail = false;
            var policyDataSerialized = JsonConvert.SerializeObject(policyData);

            foreach (var policy in policies.Where(p => p.Type == PolicyType.SendOptions))
            {
                policies.First().Enabled = true;
                policies.First().Data    = policyDataSerialized;
            }

            await sutProvider.Sut.SaveSendAsync(send);

            await sutProvider.GetDependency <ISendRepository>().Received(1).CreateAsync(send);
        }
Пример #12
0
        public void SendCanBeAccessed_Success(SutProvider <SendService> sutProvider, Send send)
        {
            var now = DateTime.UtcNow;

            send.MaxAccessCount = 10;
            send.AccessCount    = 5;
            send.ExpirationDate = now.AddYears(1);
            send.DeletionDate   = now.AddYears(1);
            send.Disabled       = false;

            sutProvider.GetDependency <IPasswordHasher <User> >()
            .VerifyHashedPassword(Arg.Any <User>(), send.Password, "TEST")
            .Returns(PasswordVerificationResult.Success);

            var(grant, passwordRequiredError, passwordInvalidError)
                = sutProvider.Sut.SendCanBeAccessed(send, "TEST");

            Assert.True(grant);
            Assert.False(passwordRequiredError);
            Assert.False(passwordInvalidError);
        }
        public async Task OrgImportCreateNewUsers(SutProvider <OrganizationService> sutProvider, Guid userId,
                                                  Organization org, List <OrganizationUserUserDetails> existingUsers, List <ImportedOrganizationUser> newUsers)
        {
            org.UseDirectory = true;
            newUsers.Add(new ImportedOrganizationUser
            {
                Email      = existingUsers.First().Email,
                ExternalId = existingUsers.First().ExternalId
            });
            var expectedNewUsersCount = newUsers.Count - 1;

            sutProvider.GetDependency <IOrganizationRepository>().GetByIdAsync(org.Id).Returns(org);
            sutProvider.GetDependency <IOrganizationUserRepository>().GetManyDetailsByOrganizationAsync(org.Id)
            .Returns(existingUsers);
            sutProvider.GetDependency <IOrganizationUserRepository>().GetCountByOrganizationIdAsync(org.Id)
            .Returns(existingUsers.Count);

            await sutProvider.Sut.ImportAsync(org.Id, userId, null, newUsers, null, false);

            await sutProvider.GetDependency <IOrganizationUserRepository>().DidNotReceiveWithAnyArgs()
            .UpsertAsync(default);
Пример #14
0
        public async Task SaveWithServerAsync_ThrowsOnBadRequestApiException(SutProvider <CipherService> sutProvider,
                                                                             Cipher cipher, string fileName, EncByteArray data, EncString encKey)
        {
            sutProvider.GetDependency <ICryptoService>().EncryptAsync(fileName, Arg.Any <SymmetricCryptoKey>())
            .Returns(new EncString(fileName));
            sutProvider.GetDependency <ICryptoService>().EncryptToBytesAsync(data.Buffer, Arg.Any <SymmetricCryptoKey>())
            .Returns(data);
            sutProvider.GetDependency <ICryptoService>().MakeEncKeyAsync(Arg.Any <SymmetricCryptoKey>())
            .Returns(new Tuple <SymmetricCryptoKey, EncString>(null, encKey));
            var expectedException = new ApiException(new ErrorResponse {
                StatusCode = HttpStatusCode.BadRequest
            });

            sutProvider.GetDependency <IApiService>().PostCipherAttachmentAsync(cipher.Id, Arg.Any <AttachmentRequest>())
            .Throws(expectedException);

            var actualException = await Assert.ThrowsAsync <ApiException>(async() =>
                                                                          await sutProvider.Sut.SaveAttachmentRawWithServerAsync(cipher, fileName, data.Buffer));

            Assert.Equal(expectedException.Error.StatusCode, actualException.Error.StatusCode);
        }
Пример #15
0
        public async Task SaveWithServerAsync_FallsBackToLegacyFormData(HttpStatusCode statusCode,
                                                                        SutProvider <CipherService> sutProvider, Cipher cipher, string fileName, EncByteArray data,
                                                                        CipherResponse response, EncString encKey)
        {
            sutProvider.GetDependency <ICryptoService>().EncryptAsync(fileName, Arg.Any <SymmetricCryptoKey>())
            .Returns(new EncString(fileName));
            sutProvider.GetDependency <ICryptoService>().EncryptToBytesAsync(data.Buffer, Arg.Any <SymmetricCryptoKey>())
            .Returns(data);
            sutProvider.GetDependency <ICryptoService>().MakeEncKeyAsync(Arg.Any <SymmetricCryptoKey>()).Returns(new Tuple <SymmetricCryptoKey, EncString>(null, encKey));
            sutProvider.GetDependency <IApiService>().PostCipherAttachmentAsync(cipher.Id, Arg.Any <AttachmentRequest>())
            .Throws(new ApiException(new ErrorResponse {
                StatusCode = statusCode
            }));
            sutProvider.GetDependency <IApiService>().PostCipherAttachmentLegacyAsync(cipher.Id, Arg.Any <MultipartFormDataContent>())
            .Returns(response);

            await sutProvider.Sut.SaveAttachmentRawWithServerAsync(cipher, fileName, data.Buffer);

            await sutProvider.GetDependency <IApiService>().Received(1)
            .PostCipherAttachmentLegacyAsync(cipher.Id, Arg.Any <MultipartFormDataContent>());
        }
Пример #16
0
        // Send Options Policy - Disable Hide Email check

        private void SaveSendAsync_HideEmail_Setup(bool disableHideEmailAppliesToUser,
                                                   SutProvider <SendService> sutProvider, Send send, Policy policy)
        {
            send.HideEmail = true;

            var sendOptions = new SendOptionsPolicyData
            {
                DisableHideEmail = disableHideEmailAppliesToUser
            };

            policy.Data = JsonSerializer.Serialize(sendOptions, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            });

            sutProvider.GetDependency <IPolicyRepository>().GetManyByTypeApplicableToUserIdAsync(
                Arg.Any <Guid>(), PolicyType.SendOptions).Returns(new List <Policy>
            {
                policy,
            });
        }
Пример #17
0
        public async Task GetAllDecryptedAsync_Success(SutProvider <SendService> sutProvider, string userId, IEnumerable <SendData> sendDatas)
        {
            var sendDataDict = sendDatas.ToDictionary(d => d.Id, d => d);

            sutProvider.GetDependency <ICryptoService>().HasKeyAsync().Returns(true);
            ServiceContainer.Register("cryptoService", sutProvider.GetDependency <ICryptoService>());
            sutProvider.GetDependency <II18nService>().StringComparer.Returns(StringComparer.CurrentCulture);
            sutProvider.GetDependency <IUserService>().GetUserIdAsync().Returns(userId);
            sutProvider.GetDependency <IStorageService>().GetAsync <Dictionary <string, SendData> >(GetSendKey(userId)).Returns(sendDataDict);

            var actual = await sutProvider.Sut.GetAllDecryptedAsync();

            Assert.Equal(sendDataDict.Count, actual.Count);
            foreach (var(actualView, expectedId) in actual.Zip(sendDataDict.Select(s => s.Key)))
            {
                // Note Send -> SendView is tested in SendTests
                Assert.Equal(expectedId, actualView.Id);
            }

            ServiceContainer.Reset();
        }
Пример #18
0
        public async Task ShareManyAsync_PaidOrgWithAttachment_Passes(SutProvider <CipherService> sutProvider,
                                                                      IEnumerable <Cipher> ciphers, Guid organizationId, List <Guid> collectionIds)
        {
            sutProvider.GetDependency <IOrganizationRepository>().GetByIdAsync(organizationId)
            .Returns(new Organization
            {
                PlanType     = Enums.PlanType.EnterpriseAnnually,
                MaxStorageGb = 100
            });
            ciphers.FirstOrDefault().Attachments =
                "{\"attachment1\":{\"Size\":\"250\",\"FileName\":\"superCoolFile\","
                + "\"Key\":\"superCoolFile\",\"ContainerName\":\"testContainer\",\"Validated\":false}}";

            var cipherInfos = ciphers.Select(c => (c,
                                                   (DateTime?)c.RevisionDate));
            var sharingUserId = ciphers.First().UserId.Value;

            await sutProvider.Sut.ShareManyAsync(cipherInfos, organizationId, collectionIds, sharingUserId);

            await sutProvider.GetDependency <ICipherRepository>().Received(1).UpdateCiphersAsync(sharingUserId,
                                                                                                 Arg.Is <IEnumerable <Cipher> >(arg => arg.Except(ciphers).IsNullOrEmpty()));
        }
        public async Task GetOrganizationApiKey_HasOne_Returns(SutProvider <GetOrganizationApiKeyCommand> sutProvider,
                                                               Guid id, Guid organizationId, OrganizationApiKeyType keyType)
        {
            sutProvider.GetDependency <IOrganizationApiKeyRepository>()
            .GetManyByOrganizationIdTypeAsync(organizationId, keyType)
            .Returns(new List <OrganizationApiKey>
            {
                new OrganizationApiKey
                {
                    Id             = id,
                    OrganizationId = organizationId,
                    ApiKey         = "test",
                    Type           = keyType,
                    RevisionDate   = DateTime.Now.AddDays(-1),
                },
            });

            var apiKey = await sutProvider.Sut.GetOrganizationApiKeyAsync(organizationId, keyType);

            Assert.NotNull(apiKey);
            Assert.Equal(id, apiKey.Id);
        }
Пример #20
0
        public async Task UpdateLicenseAsync_Success(SutProvider <UserService> sutProvider,
                                                     User user, UserLicense userLicense)
        {
            using var tempDir = new TempDirectory();

            var now = DateTime.UtcNow;

            userLicense.Issued  = now.AddDays(-10);
            userLicense.Expires = now.AddDays(10);
            userLicense.Version = 1;
            userLicense.Premium = true;

            user.EmailVerified = true;
            user.Email         = userLicense.Email;

            sutProvider.GetDependency <Settings.IGlobalSettings>().SelfHosted       = true;
            sutProvider.GetDependency <Settings.IGlobalSettings>().LicenseDirectory = tempDir.Directory;
            sutProvider.GetDependency <ILicensingService>()
            .VerifyLicense(userLicense)
            .Returns(true);

            await sutProvider.Sut.UpdateLicenseAsync(user, userLicense);

            var filePath = Path.Combine(tempDir.Directory, "user", $"{user.Id}.json");

            Assert.True(File.Exists(filePath));
            var document = JsonDocument.Parse(File.OpenRead(filePath));
            var root     = document.RootElement;

            Assert.Equal(JsonValueKind.Object, root.ValueKind);
            // Sort of a lazy way to test that it is indented but not sure of a better way
            Assert.Contains('\n', root.GetRawText());
            AssertHelper.AssertJsonProperty(root, "LicenseKey", JsonValueKind.String);
            AssertHelper.AssertJsonProperty(root, "Id", JsonValueKind.String);
            AssertHelper.AssertJsonProperty(root, "Premium", JsonValueKind.True);
            var versionProp = AssertHelper.AssertJsonProperty(root, "Version", JsonValueKind.Number);

            Assert.Equal(1, versionProp.GetInt32());
        }
Пример #21
0
        public async Task Needs2FABecauseNewDeviceAsync_ReturnsTrue(SutProvider <UserService> sutProvider, User user)
        {
            user.EmailVerified      = true;
            user.TwoFactorProviders = null;
            user.UnknownDeviceVerificationEnabled = true;
            const string deviceIdToCheck = "7b01b586-b210-499f-8d52-0c3fdaa646fc";
            const string deviceIdInRepo  = "ea29126c-91b7-4cc4-8ce6-00105b37f64a";

            sutProvider.GetDependency <IDeviceRepository>()
            .GetManyByUserIdAsync(user.Id)
            .Returns(Task.FromResult <ICollection <Device> >(new List <Device>
            {
                new Device {
                    Identifier = deviceIdInRepo
                }
            }));


            sutProvider.GetDependency <Settings.IGlobalSettings>().TwoFactorAuth.EmailOnNewDeviceLogin.Returns(true);

            Assert.True(await sutProvider.Sut.Needs2FABecauseNewDeviceAsync(user, deviceIdToCheck, "password"));
        }
Пример #22
0
        public async Task Post_Success(Guid orgId, SutProvider <CollectionsController> sutProvider)
        {
            sutProvider.GetDependency <ICurrentContext>()
            .CreateNewCollections(orgId)
            .Returns(true);

            sutProvider.GetDependency <ICurrentContext>()
            .EditAnyCollection(orgId)
            .Returns(false);

            var collectionRequest = new CollectionRequestModel
            {
                Name       = "encrypted_string",
                ExternalId = "my_external_id"
            };

            _ = await sutProvider.Sut.Post(orgId, collectionRequest);

            await sutProvider.GetDependency <ICollectionService>()
            .Received(1)
            .SaveAsync(Arg.Any <Collection>(), Arg.Any <IEnumerable <SelectionReadOnly> >(), null);
        }
Пример #23
0
        public async void UpdateFileToExistingSendAsync_InvalidSize(SutProvider <SendService> sutProvider,
                                                                    Send send)
        {
            var fileContents = "Test file content";

            var sendFileData = new SendFileData
            {
                Id   = "TEST",
                Size = fileContents.Length,
            };

            send.Type = SendType.File;
            send.Data = JsonSerializer.Serialize(sendFileData);

            sutProvider.GetDependency <ISendFileStorageService>()
            .ValidateFileAsync(send, sendFileData.Id, sendFileData.Size, Arg.Any <long>())
            .Returns((false, sendFileData.Size));

            var badRequest = await Assert.ThrowsAsync <BadRequestException>(() =>
                                                                            sutProvider.Sut.UploadFileToExistingSendAsync(new MemoryStream(Encoding.UTF8.GetBytes(fileContents)), send)
                                                                            );
        }
Пример #24
0
        public async Task SaveWithServerAsync_NewFileSend_AzureUpload_Success(SutProvider <SendService> sutProvider, string userId, SendFileUploadDataResponse response, Send send)
        {
            send.Id = null;
            response.FileUploadType = FileUploadType.Azure;
            sutProvider.GetDependency <IUserService>().GetUserIdAsync().Returns(userId);
            sutProvider.GetDependency <IApiService>().PostFileTypeSendAsync(Arg.Any <SendRequest>()).Returns(response);

            var fileContentBytes = new EncByteArray(Encoding.UTF8.GetBytes("This is the file content"));

            await sutProvider.Sut.SaveWithServerAsync(send, fileContentBytes);

            switch (send.Type)
            {
            case SendType.File:
                await sutProvider.GetDependency <IFileUploadService>().Received(1).UploadSendFileAsync(response, send.File.FileName, fileContentBytes);

                break;

            case SendType.Text:
            default:
                throw new Exception("Untested send type");
            }
        }
Пример #25
0
        public async Task RestoreManyAsync_UpdatesCiphers(Guid restoringUserId, IEnumerable <CipherDetails> ciphers,
                                                          SutProvider <CipherService> sutProvider)
        {
            var previousRevisionDate = DateTime.UtcNow;

            foreach (var cipher in ciphers)
            {
                cipher.RevisionDate = previousRevisionDate;
            }

            var revisionDate = previousRevisionDate + TimeSpan.FromMinutes(1);

            sutProvider.GetDependency <ICipherRepository>().RestoreAsync(Arg.Any <IEnumerable <Guid> >(), restoringUserId)
            .Returns(revisionDate);

            await sutProvider.Sut.RestoreManyAsync(ciphers, restoringUserId);

            foreach (var cipher in ciphers)
            {
                Assert.Null(cipher.DeletedDate);
                Assert.Equal(revisionDate, cipher.RevisionDate);
            }
        }
Пример #26
0
        public async Task InviteUser_Passes(Organization organization, OrganizationUserInvite invite,
                                            OrganizationUser invitor, SutProvider <OrganizationService> sutProvider)
        {
            invitor.Permissions = JsonSerializer.Serialize(new Permissions()
            {
                ManageUsers = true
            },
                                                           new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            });

            var organizationRepository     = sutProvider.GetDependency <IOrganizationRepository>();
            var organizationUserRepository = sutProvider.GetDependency <IOrganizationUserRepository>();
            var eventService = sutProvider.GetDependency <IEventService>();

            organizationRepository.GetByIdAsync(organization.Id).Returns(organization);
            organizationUserRepository.GetManyByUserAsync(invitor.UserId.Value).Returns(new List <OrganizationUser> {
                invitor
            });

            await sutProvider.Sut.InviteUserAsync(organization.Id, invitor.UserId, null, invite);
        }
Пример #27
0
        public async Task SaveWithServerAsync_NewFileSend_Success(SutProvider <SendService> sutProvider, string userId, SendResponse response, Send send)
        {
            send.Id = null;
            sutProvider.GetDependency <IUserService>().GetUserIdAsync().Returns(userId);
            sutProvider.GetDependency <IApiService>().PostSendAsync(Arg.Any <SendRequest>()).Returns(response);
            sutProvider.GetDependency <IApiService>().PostSendFileAsync(Arg.Any <MultipartFormDataContent>()).Returns(response);

            var fileContentBytes = Encoding.UTF8.GetBytes("This is the file content");

            await sutProvider.Sut.SaveWithServerAsync(send, fileContentBytes);

            Predicate <MultipartFormDataContent> formDataPredicate = fd =>
            {
                Assert.Equal(2, fd.Count()); // expect a request and file content

                var expectedRequest = JsonConvert.SerializeObject(new SendRequest(send, fileContentBytes?.LongLength));
                var actualRequest   = fd.First().ReadAsStringAsync().GetAwaiter().GetResult();
                Assert.Equal(expectedRequest, actualRequest);

                var actualFileContent = fd.Skip(1).First().ReadAsByteArrayAsync().GetAwaiter().GetResult();
                Assert.Equal(fileContentBytes, actualFileContent);
                return(true);
            };

            switch (send.Type)
            {
            case SendType.File:
                await sutProvider.GetDependency <IApiService>().Received(1)
                .PostSendFileAsync(Arg.Is <MultipartFormDataContent>(f => formDataPredicate(f)));

                break;

            case SendType.Text:
            default:
                throw new Exception("Untested send type");
            }
        }
Пример #28
0
        public async Task GetAllDecryptedAsync_Success(SutProvider <SendService> sutProvider, string userId, IEnumerable <SendData> sendDatas)
        {
            // TODO restore this once race condition is fixed or GHA can re-run jobs on individual platforms
            return;

            var sendDataDict = sendDatas.ToDictionary(d => d.Id, d => d);

            sutProvider.GetDependency <ICryptoService>().HasKeyAsync().Returns(true);
            ServiceContainer.Register("cryptoService", sutProvider.GetDependency <ICryptoService>());
            sutProvider.GetDependency <II18nService>().StringComparer.Returns(StringComparer.CurrentCulture);
            sutProvider.GetDependency <IStateService>().GetActiveUserIdAsync().Returns(userId);
            sutProvider.GetDependency <IStateService>().GetEncryptedSendsAsync().Returns(sendDataDict);

            var actual = await sutProvider.Sut.GetAllDecryptedAsync();

            Assert.Equal(sendDataDict.Count, actual.Count);
            foreach (var(actualView, expectedId) in actual.Zip(sendDataDict.Select(s => s.Key)))
            {
                // Note Send -> SendView is tested in SendTests
                Assert.Equal(expectedId, actualView.Id);
            }

            ServiceContainer.Reset();
        }
Пример #29
0
        public async Task Put_Success(Guid orgId, Guid collectionId, Guid userId, CollectionRequestModel collectionRequest,
                                      SutProvider <CollectionsController> sutProvider)
        {
            sutProvider.GetDependency <ICurrentContext>()
            .ViewAssignedCollections(orgId)
            .Returns(true);

            sutProvider.GetDependency <ICurrentContext>()
            .EditAssignedCollections(orgId)
            .Returns(true);

            sutProvider.GetDependency <ICurrentContext>()
            .UserId
            .Returns(userId);

            sutProvider.GetDependency <ICollectionRepository>()
            .GetByIdAsync(collectionId, userId)
            .Returns(new CollectionDetails
            {
                OrganizationId = orgId,
            });

            _ = await sutProvider.Sut.Put(orgId, collectionId, collectionRequest);
        }
Пример #30
0
        public async Task RestoreAsync_UpdatesCipher(Guid restoringUserId, Cipher cipher, SutProvider <CipherService> sutProvider)
        {
            sutProvider.GetDependency <ICipherRepository>().GetCanEditByIdAsync(restoringUserId, cipher.Id).Returns(true);

            var initialRevisionDate = new DateTime(1970, 1, 1, 0, 0, 0);

            cipher.DeletedDate  = initialRevisionDate;
            cipher.RevisionDate = initialRevisionDate;

            await sutProvider.Sut.RestoreAsync(cipher, restoringUserId, cipher.OrganizationId.HasValue);

            Assert.Null(cipher.DeletedDate);
            Assert.NotEqual(initialRevisionDate, cipher.RevisionDate);
        }