public void CreatesPackageOwnerRequestSendsEmailAndReturnsPendingState()
            {
                var newOwner = new User { Username = "******" };
                var currentOwner = new User { Username = "******" };
                var package = new PackageRegistration { Id = "foo", Owners = new[] { currentOwner } };
                var packageOwnerRequest = new PackageOwnerRequest { ConfirmationCode = "some-generated-code" };
                var currentUser = new Mock<IPrincipal>();
                currentUser.Setup(u => u.Identity.Name).Returns("scott");
                var userService = new Mock<IUserService>();
                userService.Setup(u => u.FindByUsername(currentOwner.Username)).Returns(currentOwner);
                userService.Setup(u => u.FindByUsername(newOwner.Username)).Returns(newOwner);
                var packageService = new Mock<IPackageService>();
                packageService.Setup(svc => svc.FindPackageRegistrationById("foo")).Returns(package);
                packageService.Setup(svc => svc.CreatePackageOwnerRequest(package, currentOwner, It.IsAny<User>())).Returns(packageOwnerRequest);
                var messageService = new Mock<IMessageService>();
                messageService.Setup(
                    m => m.SendPackageOwnerRequest(
                        currentOwner,
                        newOwner,
                        package,
                        "https://example.org/?Controller=Packages&Action=ConfirmOwner&id=foo&username=steve&token=some-generated-code")).Verifiable();
                var controller = CreateJsonApiController(packageService, userService, currentUser: currentUser, messageService: messageService);

                var result = controller.AddPackageOwner("foo", newOwner.Username);

                // We use a catch-all route for unit tests so we can see the parameters
                // are passed correctly.
                Assert.True(TestUtility.GetAnonymousPropertyValue<bool>(result, "success"));
                Assert.Equal(newOwner.Username, TestUtility.GetAnonymousPropertyValue<string>(result, "name"));
                Assert.True(TestUtility.GetAnonymousPropertyValue<bool>(result, "pending"));
                messageService.VerifyAll();
            }
        public void V1FeedSearchDoesNotReturnUnlistedPackages()
        {
            // Arrange
            var packageRegistration = new PackageRegistration { Id = "Foo" };
            var repo = new Mock<IEntityRepository<Package>>(MockBehavior.Strict);
            repo.Setup(r => r.GetAll()).Returns(new[] {
                new Package { PackageRegistration = packageRegistration, Version = "1.0.0", IsPrerelease = false, Listed = true, DownloadStatistics = new List<PackageStatistics>() },
                new Package { PackageRegistration = packageRegistration, Version = "1.0.1-a", IsPrerelease = true, Listed = true, DownloadStatistics = new List<PackageStatistics>() },
                new Package { PackageRegistration = new PackageRegistration { Id ="baz" }, Version = "2.0", Listed = false, DownloadStatistics = new List<PackageStatistics>() },
            }.AsQueryable());
            var searchService = new Mock<ISearchService>(MockBehavior.Strict);
            searchService.Setup(s => s.SearchWithRelevance(It.IsAny<IQueryable<Package>>(), It.IsAny<String>())).Returns<IQueryable<Package>, string>((_, __) => _);
            var configuration = new Mock<IConfiguration>(MockBehavior.Strict);
            configuration.Setup(c => c.GetSiteRoot(It.IsAny<bool>())).Returns("http://test.nuget.org/");
            var v1Service = new TestableV1Feed(repo.Object, configuration.Object, searchService.Object);

            // Act
            var result = v1Service.Search(null, null);

            // Assert
            Assert.Equal(1, result.Count());
            var package = result.First();
            Assert.Equal("Foo", package.Id);
            Assert.Equal("1.0.0", package.Version);
            Assert.Equal("http://test.nuget.org/packages/Foo/1.0.0", package.GalleryDetailsUrl);
            Assert.Equal("http://test.nuget.org/package/ReportAbuse/Foo/1.0.0", package.ReportAbuseUrl);
        }
            public TestableCuratedFeedService()
            {
                StubCuratedFeed = new CuratedFeed { Key = 0, Name = "aName" };
                StubPackageRegistration = new PackageRegistration { Key = 1066, Id = "aPackageId" };

                StubCuratedPackage = new CuratedPackage
                {
                    Key = 0,
                    CuratedFeedKey = StubCuratedFeed.Key,
                    CuratedFeed = StubCuratedFeed,
                    PackageRegistration = StubPackageRegistration,
                    PackageRegistrationKey = StubPackageRegistration.Key
                };
                StubCuratedFeed.Packages.Add(StubCuratedPackage);

                StubCuratedFeedRepository = new Mock<IEntityRepository<CuratedFeed>>();
                StubCuratedFeedRepository
                    .Setup(repo => repo.GetAll())
                    .Returns(new CuratedFeed[] { StubCuratedFeed }.AsQueryable());

                StubCuratedPackageRepository = new Mock<IEntityRepository<CuratedPackage>>();
                StubCuratedPackageRepository
                    .Setup(repo => repo.GetAll())
                    .Returns(new CuratedPackage[] { StubCuratedPackage }.AsQueryable());
            }
            public void CallsSendContactOwnersMessageWithUserInfo()
            {
                var messageService = new Mock<IMessageService>();
                messageService.Setup(s => s.SendContactOwnersMessage(
                    It.IsAny<MailAddress>(),
                    It.IsAny<PackageRegistration>(),
                    "I like the cut of your jib", It.IsAny<string>()));
                var package = new PackageRegistration { Id = "factory" };

                var packageSvc = new Mock<IPackageService>();
                packageSvc.Setup(p => p.FindPackageRegistrationById("factory")).Returns(package);
                var httpContext = new Mock<HttpContextBase>();
                httpContext.Setup(h => h.User.Identity.Name).Returns("Montgomery");
                var userSvc = new Mock<IUserService>();
                userSvc.Setup(u => u.FindByUsername("Montgomery")).Returns(new User { EmailAddress = "*****@*****.**", Username = "******" });
                var controller = CreateController(packageSvc: packageSvc,
                    messageSvc: messageService,
                    userSvc: userSvc,
                    httpContext: httpContext);
                var model = new ContactOwnersViewModel
                {
                    Message = "I like the cut of your jib",
                };

                var result = controller.ContactOwners("factory", model) as RedirectToRouteResult;

                Assert.NotNull(result);
            }
        public void V1FeedSearchDoesNotReturnPrereleasePackages()
        {
            // Arrange
            var packageRegistration = new PackageRegistration { Id = "Foo" };
            var repo = new Mock<IEntityRepository<Package>>(MockBehavior.Strict);
            repo.Setup(r => r.GetAll()).Returns(new[] {
                new Package { PackageRegistration = packageRegistration, Version = "1.0.0", IsPrerelease = false, Listed = true, DownloadStatistics = new List<PackageStatistics>() },
                new Package { PackageRegistration = packageRegistration, Version = "1.0.1-a", IsPrerelease = true, Listed = true, DownloadStatistics = new List<PackageStatistics>() },
            }.AsQueryable());
            var configuration = new Mock<IConfiguration>(MockBehavior.Strict);
            configuration.Setup(c => c.GetSiteRoot(It.IsAny<bool>())).Returns("https://localhost:8081/");
            var searchService = new Mock<ISearchService>(MockBehavior.Strict);
            int total;
            searchService.Setup(s => s.Search(It.IsAny<IQueryable<Package>>(), It.IsAny<SearchFilter>(), out total)).Returns<IQueryable<Package>, string>((_, __) => _);
            var v1Service = new TestableV1Feed(repo.Object, configuration.Object, searchService.Object);

            // Act
            var result = v1Service.Search(null, null);

            // Assert
            Assert.Equal(1, result.Count());
            Assert.Equal("Foo", result.First().Id);
            Assert.Equal("1.0.0", result.First().Version);
            Assert.Equal("https://localhost:8081/packages/Foo/1.0.0", result.First().GalleryDetailsUrl);
        }
 public static AuditedPackageRegistration CreateFrom(PackageRegistration packageRegistration)
 {
     return new AuditedPackageRegistration
     {
         Id = packageRegistration.Id,
         DownloadCount = packageRegistration.DownloadCount,
         Key = packageRegistration.Key
     };
 }
            public TestableCuratedFeedService()
            {
                StubCuratedFeed = new CuratedFeed { Key = 0, Name = "aName" };
                StubCuratedFeed2 = new CuratedFeed {Key = 1, Name = "AnotherFeed"};
                StubPackageRegistration_ForFeed1 = new PackageRegistration { Key = 1066, Id = "aPackageId" };
                StubPackageRegistration_ForFeed2 = new PackageRegistration { Key = 1067, Id = "aPackageId2" };
                StubPackageRegistration_ForFeed1_NotIncluded = new PackageRegistration { Key = 1068, Id = "aPackageId2" };
                StubPackage = new Package { PackageRegistration = StubPackageRegistration_ForFeed1, PackageRegistrationKey = StubPackageRegistration_ForFeed1.Key, Version = "1.0.0" };
                StubPackage_IncompatibleVersion = new Package { PackageRegistration = StubPackageRegistration_ForFeed1, PackageRegistrationKey = StubPackageRegistration_ForFeed1.Key, Version = "2.0.0" };
                StubPackage_ForFeed1_NotIncluded = new Package { PackageRegistration = StubPackageRegistration_ForFeed1_NotIncluded, PackageRegistrationKey = StubPackageRegistration_ForFeed1_NotIncluded.Key };

                StubCuratedPackageRegistration_ForFeed1 = new CuratedPackage
                {
                    Key = 1, 
                    CuratedFeedKey = StubCuratedFeed.Key, 
                    CuratedFeed = StubCuratedFeed, 
                    PackageRegistration = StubPackageRegistration_ForFeed1,
                    PackageRegistrationKey = StubPackageRegistration_ForFeed1.Key,
                    Included = true
                };
                StubCuratedFeed.Packages.Add(StubCuratedPackageRegistration_ForFeed1);

                StubCuratedPackageRegistration_ForFeed2 = new CuratedPackage
                {
                    Key = 2,
                    CuratedFeedKey = StubCuratedFeed2.Key,
                    CuratedFeed = StubCuratedFeed2,
                    PackageRegistration = StubPackageRegistration_ForFeed2,
                    PackageRegistrationKey = StubPackageRegistration_ForFeed2.Key,
                    Included = true
                };
                StubCuratedFeed2.Packages.Add(StubCuratedPackageRegistration_ForFeed2);

                StubCuratedPackageRegistration_ForFeed1_NotIncluded = new CuratedPackage
                {
                    Key = 3,
                    CuratedFeedKey = StubCuratedFeed.Key,
                    CuratedFeed = StubCuratedFeed,
                    PackageRegistration = StubPackageRegistration_ForFeed1_NotIncluded,
                    PackageRegistrationKey = StubPackageRegistration_ForFeed1_NotIncluded.Key,
                    Included = false
                };
                StubCuratedFeed.Packages.Add(StubCuratedPackageRegistration_ForFeed1_NotIncluded);

                StubCuratedFeedRepository = new Mock<IEntityRepository<CuratedFeed>>();
                StubCuratedFeedRepository
                    .Setup(repo => repo.GetAll())
                    .Returns(new CuratedFeed[] { StubCuratedFeed, StubCuratedFeed2 }.AsQueryable());

                StubCuratedPackageRepository = new Mock<IEntityRepository<CuratedPackage>>();
                StubCuratedPackageRepository
                    .Setup(repo => repo.GetAll())
                    .Returns(new CuratedPackage[] { StubCuratedPackageRegistration_ForFeed1, StubCuratedPackageRegistration_ForFeed2, StubCuratedPackageRegistration_ForFeed1_NotIncluded }.AsQueryable());
            }
        protected void InterceptPackageRegistrationMaterialized(PackageRegistration packageRegistration)
        {
            if (packageRegistration == null)
            {
                return;
            }

            int downloadCount;
            if (_downloadCountService.TryGetDownloadCountForPackageRegistration(packageRegistration.Id, out downloadCount))
            {
                packageRegistration.DownloadCount = downloadCount;
            }
        }
            public void ReturnsFailureWhenRequestedNewOwnerDoesNotExist()
            {
                var package = new PackageRegistration { Id = "foo", Owners = new[] { new User { Username = "******" } } };
                var packageService = new Mock<IPackageService>();
                packageService.Setup(svc => svc.FindPackageRegistrationById("foo")).Returns(package);
                var currentUser = new Mock<IPrincipal>();
                currentUser.Setup(u => u.Identity.Name).Returns("scott");
                var controller = CreateJsonApiController(packageService, currentUser: currentUser);

                var result = controller.AddPackageOwner("foo", "steve");

                Assert.False(TestUtility.GetAnonymousPropertyValue<bool>(result, "success"));
                Assert.Equal("Maintainer not found", TestUtility.GetAnonymousPropertyValue<string>(result, "message"));
            }
            public void OnlyShowsOwnersWhoAllowReceivingEmails()
            {
                var package = new PackageRegistration
                {
                    Id = "pkgid",
                    Owners = new[]{
                        new User { Username = "******", EmailAllowed = true},
                        new User { Username = "******", EmailAllowed = false},
                        new User { Username = "******", EmailAllowed = true}
                    }
                };
                var packageSvc = new Mock<IPackageService>();
                packageSvc.Setup(p => p.FindPackageRegistrationById("pkgid")).Returns(package);
                var controller = CreateController(packageSvc: packageSvc);

                var model = (controller.ContactOwners("pkgid") as ViewResult).Model as ContactOwnersViewModel;

                Assert.Equal(2, model.Owners.Count());
                Assert.Empty(model.Owners.Where(u => u.Username == "grinch"));
            }
        public void V1FeedFindPackagesByIdReturnsUnlistedPackagesButNotPrereleasePackages()
        {
            // Arrange
            var packageRegistration = new PackageRegistration { Id = "Foo" };
            var repo = new Mock<IEntityRepository<Package>>(MockBehavior.Strict);
            repo.Setup(r => r.GetAll()).Returns(new[] {
                new Package { PackageRegistration = packageRegistration, Version = "1.0.0", IsPrerelease = false, Listed = false, DownloadStatistics = new List<PackageStatistics>() },
                new Package { PackageRegistration = packageRegistration, Version = "1.0.1-a", IsPrerelease = true, Listed = true, DownloadStatistics = new List<PackageStatistics>() },
            }.AsQueryable());
            var configuration = new Mock<IConfiguration>(MockBehavior.Strict);
            configuration.Setup(c => c.GetSiteRoot(It.IsAny<bool>())).Returns("https://localhost:8081/");
            var v1Service = new TestableV1Feed(repo.Object, configuration.Object, null);

            // Act
            var result = v1Service.FindPackagesById("Foo");

            // Assert
            Assert.Equal(1, result.Count());
            Assert.Equal("Foo", result.First().Id);
            Assert.Equal("1.0.0", result.First().Version);
            Assert.Equal("https://localhost:8081/packages/Foo/1.0.0", result.First().GalleryDetailsUrl);
        }
        public void V2FeedSearchDoesNotReturnPrereleasePackagesIfFlagIsFalse()
        {
            // Arrange
            var packageRegistration = new PackageRegistration { Id = "Foo" };
            var repo = new Mock<IEntityRepository<Package>>(MockBehavior.Strict);
            repo.Setup(r => r.GetAll()).Returns(new[] {
                new Package { PackageRegistration = packageRegistration, Version = "1.0.0", IsPrerelease = false, Listed = true, DownloadStatistics = new List<PackageStatistics>() },
                new Package { PackageRegistration = packageRegistration, Version = "1.0.1a", IsPrerelease = true, Listed = true, DownloadStatistics = new List<PackageStatistics>() },
            }.AsQueryable());
            var configuration = new Mock<IConfiguration>(MockBehavior.Strict);
            configuration.SetupGet(c => c.SiteRoot).Returns("https://staged.nuget.org/");
            var v2Service = new V2Feed(repo.Object, configuration.Object);

            // Act
            var result = v2Service.Search(null, null, includePrerelease: false);

            // Assert
            Assert.Equal(1, result.Count());
            var package = result.First();
            Assert.Equal("Foo", package.Id);
            Assert.Equal("1.0.0", package.Version);
            Assert.Equal("https://staged.nuget.org/packages/Foo/1.0.0", package.GalleryDetailsUrl);
            Assert.Equal("https://staged.nuget.org/package/ReportAbuse/Foo/1.0.0", package.ReportAbuseUrl);
        }
            public async Task ReplacesExistingDeprecations(bool shouldUnlist)
            {
                // Arrange
                var lastEdited = new DateTime(2019, 3, 4);

                var packageWithDeprecation1 = new Package
                {
                    Deprecations = new List <PackageDeprecation> {
                        new PackageDeprecation()
                    },
                    LastEdited = lastEdited
                };

                var packageWithoutDeprecation1 = new Package
                {
                    LastEdited = lastEdited
                };

                var packageWithDeprecation2 = new Package
                {
                    LastEdited   = lastEdited,
                    Deprecations = new List <PackageDeprecation>
                    {
                        new PackageDeprecation
                        {
                            Cves = new List <Cve>
                            {
                                new Cve
                                {
                                    CveId = "cve-0"
                                }
                            }
                        }
                    }
                };

                var packageWithoutDeprecation2 = new Package
                {
                    LastEdited = lastEdited
                };

                var packageWithDeprecation3 = new Package
                {
                    LastEdited   = lastEdited,
                    Deprecations = new List <PackageDeprecation>
                    {
                        new PackageDeprecation
                        {
                            Cwes = new List <Cwe>
                            {
                                new Cwe
                                {
                                    CweId = "cwe-0"
                                }
                            }
                        }
                    }
                };

                var packages = new[]
                {
                    packageWithDeprecation1,
                    packageWithoutDeprecation1,
                    packageWithDeprecation2,
                    packageWithoutDeprecation2,
                    packageWithDeprecation3
                };

                var deprecationRepository       = GetMock <IEntityRepository <PackageDeprecation> >();
                var packagesWithoutDeprecations = packages.Where(p => p.Deprecations.SingleOrDefault() == null).ToList();

                deprecationRepository
                .Setup(x => x.InsertOnCommit(
                           It.Is <IEnumerable <PackageDeprecation> >(
                               // The deprecations inserted must be identical to the list of packages without deprecations.
                               i => packagesWithoutDeprecations.SequenceEqual(i.Select(d => d.Package)))))
                .Verifiable();

                deprecationRepository
                .Setup(x => x.CommitChangesAsync())
                .Completes()
                .Verifiable();

                var service = Get <PackageDeprecationService>();

                var status = (PackageDeprecationStatus)99;

                var cves = new []
                {
                    new Cve
                    {
                        CveId = "cve-1"
                    },

                    new Cve
                    {
                        CveId = "cve-2"
                    }
                };

                var cvss = (decimal)5.5;

                var cwes = new[]
                {
                    new Cwe
                    {
                        CweId = "cwe-1"
                    },

                    new Cwe
                    {
                        CweId = "cwe-2"
                    }
                };

                var alternatePackageRegistration = new PackageRegistration();
                var alternatePackage             = new Package();

                var customMessage = "message";

                // Act
                await service.UpdateDeprecation(
                    packages,
                    status,
                    cves,
                    cvss,
                    cwes,
                    alternatePackageRegistration,
                    alternatePackage,
                    customMessage);

                // Assert
                deprecationRepository.Verify();

                foreach (var package in packages)
                {
                    var deprecation = package.Deprecations.Single();
                    Assert.Equal(status, deprecation.Status);
                    Assert.Equal(cves, deprecation.Cves);
                    Assert.Equal(cvss, deprecation.CvssRating);
                    Assert.Equal(cwes, deprecation.Cwes);
                    Assert.Equal(alternatePackageRegistration, deprecation.AlternatePackageRegistration);
                    Assert.Equal(alternatePackage, deprecation.AlternatePackage);
                    Assert.Equal(customMessage, deprecation.CustomMessage);
                }
            }
Exemple #14
0
        public void V2FeedGetUpdatesFiltersIncludesHighestPrereleasePackage()
        {
            // Arrange
            var packageRegistrationA = new PackageRegistration {
                Id = "Foo"
            };
            var packageRegistrationB = new PackageRegistration {
                Id = "Qux"
            };
            var repo = new Mock <IEntityRepository <Package> >(MockBehavior.Strict);

            repo.Setup(r => r.GetAll()).Returns(new[] {
                new Package {
                    PackageRegistration = packageRegistrationA, Version = "1.0.0", IsPrerelease = false, Listed = true
                },
                new Package {
                    PackageRegistration = packageRegistrationA, Version = "1.1.0", IsPrerelease = false, Listed = true,
                    SupportedFrameworks = new[] { new PackageFramework {
                                                      TargetFramework = "SL5"
                                                  }, new PackageFramework {
                                                      TargetFramework = "Net40-Full"
                                                  } }
                },
                new Package {
                    PackageRegistration = packageRegistrationA, Version = "1.2.0", IsPrerelease = false, Listed = true,
                    SupportedFrameworks = new[] { new PackageFramework {
                                                      TargetFramework = "SL5"
                                                  }, new PackageFramework {
                                                      TargetFramework = "Net40-Full"
                                                  } }
                },
                new Package {
                    PackageRegistration = packageRegistrationA, Version = "1.3.0-alpha", IsPrerelease = true, Listed = true,
                    SupportedFrameworks = new[] { new PackageFramework {
                                                      TargetFramework = "SL5"
                                                  }, new PackageFramework {
                                                      TargetFramework = "Net40-Full"
                                                  } }
                },
                new Package {
                    PackageRegistration = packageRegistrationA, Version = "2.0.0", IsPrerelease = false, Listed = true,
                    SupportedFrameworks = new[] { new PackageFramework {
                                                      TargetFramework = "SL5"
                                                  }, new PackageFramework {
                                                      TargetFramework = "WinRT"
                                                  } }
                },
                new Package {
                    PackageRegistration = packageRegistrationB, Version = "2.0", IsPrerelease = false, Listed = true
                },
            }.AsQueryable());
            var configuration = new Mock <IConfiguration>(MockBehavior.Strict);

            configuration.Setup(c => c.GetSiteRoot(false)).Returns("https://localhost:8081/");
            var v2Service = new TestableV2Feed(repo.Object, configuration.Object, null);

            // Act
            var result = v2Service.GetUpdates("Foo|Qux", "1.0|1.5", includePrerelease: true, includeAllVersions: false, targetFrameworks: "net40")
                         .ToList();

            // Assert
            Assert.Equal(2, result.Count);
            AssertPackage(new { Id = "Foo", Version = "1.3.0-alpha" }, result[0]);
            AssertPackage(new { Id = "Qux", Version = "2.0" }, result[1]);
        }
        private IReadOnlyList <IndexAction <KeyedDocument> > AddOrUpdatePackage(
            PackageRegistration registration,
            bool isUpdate)
        {
            var encodedId = EncodePackageId(registration.PackageId.ToLowerInvariant());
            var result    = new List <IndexAction <KeyedDocument> >();

            for (var i = 0; i < 4; i++)
            {
                var includePrerelease = (i & 1) != 0;
                var includeSemVer2    = (i & 2) != 0;
                var searchFilters     = (SearchFilters)i;

                var documentKey = $"{encodedId}-{searchFilters}";
                var filtered    = registration.Packages.Where(p => p.Listed);

                if (!includePrerelease)
                {
                    filtered = filtered.Where(p => !p.IsPrerelease);
                }

                if (!includeSemVer2)
                {
                    filtered = filtered.Where(p => p.SemVerLevel != SemVerLevel.SemVer2);
                }

                var versions = filtered.OrderBy(p => p.Version).ToList();
                if (versions.Count == 0)
                {
                    if (isUpdate)
                    {
                        var action = IndexAction.Delete(
                            new KeyedDocument
                        {
                            Key = documentKey
                        });

                        result.Add(action);
                    }

                    continue;
                }

                var latest       = versions.Last();
                var dependencies = latest
                                   .Dependencies
                                   .Select(d => d.Id?.ToLowerInvariant())
                                   .Where(d => d != null)
                                   .Distinct()
                                   .ToArray();

                var document = new PackageDocument();

                document.Key                = $"{encodedId}-{searchFilters}";
                document.Id                 = latest.Id;
                document.Version            = latest.Version.ToFullString();
                document.Description        = latest.Description;
                document.Authors            = latest.Authors;
                document.IconUrl            = latest.IconUrlString;
                document.LicenseUrl         = latest.LicenseUrlString;
                document.ProjectUrl         = latest.ProjectUrlString;
                document.Published          = latest.Published;
                document.Summary            = latest.Summary;
                document.Tags               = latest.Tags;
                document.Title              = latest.Title;
                document.TotalDownloads     = versions.Sum(p => p.Downloads);
                document.DownloadsMagnitude = document.TotalDownloads.ToString().Length;
                document.Versions           = versions.Select(p => p.Version.ToFullString()).ToArray();
                document.VersionDownloads   = versions.Select(p => p.Downloads.ToString()).ToArray();
                document.Dependencies       = dependencies;
                document.PackageTypes       = latest.PackageTypes.Select(t => t.Name).ToArray();
                document.Frameworks         = latest.TargetFrameworks.Select(f => f.Moniker.ToLowerInvariant()).ToArray();
                document.SearchFilters      = searchFilters.ToString();

                result.Add(
                    isUpdate
                        ? IndexAction.MergeOrUpload <KeyedDocument>(document)
                        : IndexAction.Upload <KeyedDocument>(document));
            }

            return(result);
        }
 public virtual IReadOnlyList <IndexAction <KeyedDocument> > UpdatePackage(
     PackageRegistration registration)
 {
     return(AddOrUpdatePackage(registration, isUpdate: true));
 }
        public Fakes()
        {
            User = new User("testUser")
            {
                Key          = 40,
                EmailAddress = "*****@*****.**",
                Credentials  = new List <Credential>
                {
                    new CredentialBuilder().CreatePasswordCredential(Password),
                    TestCredentialHelper.CreateV1ApiKey(Guid.Parse("669e180e-335c-491a-ac26-e83c4bd31d65"),
                                                        ExpirationForApiKeyV1),
                    TestCredentialHelper.CreateV2ApiKey(Guid.Parse("779e180e-335c-491a-ac26-e83c4bd31d87"),
                                                        ExpirationForApiKeyV1),
                    TestCredentialHelper.CreateV2VerificationApiKey(Guid.Parse("b0c51551-823f-4701-8496-43980b4b3913")),
                    TestCredentialHelper.CreateExternalCredential("abc")
                }
            };

            Pbkdf2User = new User("testPbkdf2User")
            {
                Key          = 41,
                EmailAddress = "*****@*****.**",
                Credentials  = new List <Credential>
                {
                    TestCredentialHelper.CreatePbkdf2Password(Password),
                    TestCredentialHelper.CreateV1ApiKey(Guid.Parse("519e180e-335c-491a-ac26-e83c4bd31d65"),
                                                        ExpirationForApiKeyV1)
                }
            };

            ShaUser = new User("testShaUser")
            {
                Key          = 42,
                EmailAddress = "*****@*****.**",
                Credentials  = new List <Credential>
                {
                    TestCredentialHelper.CreateSha1Password(Password),
                    TestCredentialHelper.CreateV1ApiKey(Guid.Parse("b9704a41-4107-4cd2-bcfa-70d84e021ab2"),
                                                        ExpirationForApiKeyV1)
                }
            };

            Admin = new User("testAdmin")
            {
                Key          = 43,
                EmailAddress = "*****@*****.**",
                Credentials  = new List <Credential> {
                    TestCredentialHelper.CreatePbkdf2Password(Password)
                },
                Roles = new List <Role> {
                    new Role {
                        Name = Constants.AdminRoleName
                    }
                }
            };

            Owner = new User("testPackageOwner")
            {
                Key         = 44,
                Credentials = new List <Credential> {
                    TestCredentialHelper.CreatePbkdf2Password(Password)
                },
                EmailAddress = "*****@*****.**" //package owners need confirmed email addresses, obviously.
            };

            Package = new PackageRegistration
            {
                Id     = "FakePackage",
                Owners = new List <User> {
                    Owner
                },
                Packages = new List <Package>
                {
                    new Package {
                        Version = "1.0"
                    },
                    new Package {
                        Version = "2.0"
                    }
                }
            };
        }
Exemple #18
0
            public async Task DeletesExistingDeprecationsIfStatusNotDeprecated()
            {
                // Arrange
                var id           = "theId";
                var registration = new PackageRegistration {
                    Id = id
                };
                var packageWithDeprecation1 = new Package
                {
                    PackageRegistration = registration,
                    NormalizedVersion   = "1.0.0",
                    Deprecations        = new List <PackageDeprecation> {
                        new PackageDeprecation()
                    }
                };

                var packageWithoutDeprecation1 = new Package
                {
                    PackageRegistration = registration,
                    NormalizedVersion   = "2.0.0"
                };

                var packageWithDeprecation2 = new Package
                {
                    PackageRegistration = registration,
                    NormalizedVersion   = "3.0.0",
                    Deprecations        = new List <PackageDeprecation> {
                        new PackageDeprecation()
                    }
                };

                var packageWithoutDeprecation2 = new Package
                {
                    PackageRegistration = registration,
                    NormalizedVersion   = "4.0.0"
                };

                var packages = new[]
                {
                    packageWithDeprecation1,
                    packageWithoutDeprecation1,
                    packageWithDeprecation2,
                    packageWithoutDeprecation2
                };

                var transactionMock = new Mock <IDbContextTransaction>();

                transactionMock
                .Setup(x => x.Commit())
                .Verifiable();

                var databaseMock = new Mock <IDatabase>();

                databaseMock
                .Setup(x => x.BeginTransaction())
                .Returns(transactionMock.Object);

                var context = GetFakeContext();

                context.SetupDatabase(databaseMock.Object);
                context.Deprecations.AddRange(
                    packages
                    .Select(p => p.Deprecations.SingleOrDefault())
                    .Where(d => d != null));

                var packageUpdateService = GetMock <IPackageUpdateService>();

                packageUpdateService
                .Setup(b => b.UpdatePackagesAsync(packages, true))
                .Returns(Task.CompletedTask)
                .Verifiable();

                var auditingService = GetService <IAuditingService>();

                var telemetryService = GetMock <ITelemetryService>();

                telemetryService
                .Setup(x => x.TrackPackageDeprecate(packages, PackageDeprecationStatus.NotDeprecated, null, null, false))
                .Verifiable();

                var user = new User {
                    Key = 1
                };
                var service = Get <PackageDeprecationService>();

                // Act
                await service.UpdateDeprecation(
                    packages,
                    PackageDeprecationStatus.NotDeprecated,
                    alternatePackageRegistration : null,
                    alternatePackage : null,
                    customMessage : null,
                    user : user);

                // Assert
                context.VerifyCommitChanges();
                Assert.Equal(0, context.Deprecations.Count());
                packageUpdateService.Verify();
                transactionMock.Verify();
                telemetryService.Verify();

                foreach (var package in packages)
                {
                    Assert.Empty(package.Deprecations);

                    auditingService.WroteRecord <PackageAuditRecord>(
                        r => r.Action == AuditedPackageAction.Undeprecate &&
                        r.Reason == PackageUndeprecatedVia.Web &&
                        r.DeprecationRecord == null &&
                        r.Id == id &&
                        r.PackageRecord.NormalizedVersion == package.NormalizedVersion);
                }
            }
Exemple #19
0
            public async Task ReplacesExistingDeprecations()
            {
                // Arrange
                var lastTimestamp = new DateTime(2019, 3, 4);

                var id           = "theId";
                var registration = new PackageRegistration {
                    Id = id
                };
                var packageWithDeprecation1 = new Package
                {
                    PackageRegistration = registration,
                    NormalizedVersion   = "1.0.0",
                    Deprecations        = new List <PackageDeprecation> {
                        new PackageDeprecation()
                    },
                    LastEdited = lastTimestamp
                };

                var packageWithoutDeprecation1 = new Package
                {
                    PackageRegistration = registration,
                    NormalizedVersion   = "2.0.0",
                    LastEdited          = lastTimestamp
                };

                var packageWithDeprecation2 = new Package
                {
                    PackageRegistration = registration,
                    NormalizedVersion   = "3.0.0",
                    LastEdited          = lastTimestamp,
                    Deprecations        = new List <PackageDeprecation>
                    {
                        new PackageDeprecation
                        {
                        }
                    }
                };

                var packageWithoutDeprecation2 = new Package
                {
                    PackageRegistration = registration,
                    NormalizedVersion   = "4.0.0",
                    LastEdited          = lastTimestamp
                };

                var packageWithDeprecation3 = new Package
                {
                    PackageRegistration = registration,
                    NormalizedVersion   = "5.0.0",
                    LastEdited          = lastTimestamp,
                    Deprecations        = new List <PackageDeprecation>
                    {
                        new PackageDeprecation
                        {
                        }
                    }
                };

                var packages = new[]
                {
                    packageWithDeprecation1,
                    packageWithoutDeprecation1,
                    packageWithDeprecation2,
                    packageWithoutDeprecation2,
                    packageWithDeprecation3
                };

                var transactionMock = new Mock <IDbContextTransaction>();

                transactionMock
                .Setup(x => x.Commit())
                .Verifiable();

                var databaseMock = new Mock <IDatabase>();

                databaseMock
                .Setup(x => x.BeginTransaction())
                .Returns(transactionMock.Object);

                var context = GetFakeContext();

                context.SetupDatabase(databaseMock.Object);
                context.Deprecations.AddRange(
                    packages
                    .Select(p => p.Deprecations.SingleOrDefault())
                    .Where(d => d != null));

                var packageUpdateService = GetMock <IPackageUpdateService>();

                packageUpdateService
                .Setup(b => b.UpdatePackagesAsync(packages, true))
                .Returns(Task.CompletedTask)
                .Verifiable();

                var auditingService = GetService <IAuditingService>();

                var status = (PackageDeprecationStatus)99;

                var alternatePackageRegistration = new PackageRegistration();
                var alternatePackage             = new Package();

                var telemetryService = GetMock <ITelemetryService>();

                telemetryService
                .Setup(x => x.TrackPackageDeprecate(packages, status, alternatePackageRegistration, alternatePackage, true))
                .Verifiable();

                var service = Get <PackageDeprecationService>();

                var customMessage = "message";
                var user          = new User {
                    Key = 1
                };

                // Act
                await service.UpdateDeprecation(
                    packages,
                    status,
                    alternatePackageRegistration,
                    alternatePackage,
                    customMessage,
                    user);

                // Assert
                context.VerifyCommitChanges();
                databaseMock.Verify();
                transactionMock.Verify();
                packageUpdateService.Verify();
                telemetryService.Verify();

                Assert.Equal(packages.Count(), context.Deprecations.Count());
                foreach (var package in packages)
                {
                    var deprecation = package.Deprecations.Single();
                    Assert.Contains(deprecation, context.Deprecations);
                    Assert.Equal(status, deprecation.Status);
                    Assert.Equal(alternatePackageRegistration, deprecation.AlternatePackageRegistration);
                    Assert.Equal(alternatePackage, deprecation.AlternatePackage);
                    Assert.Equal(customMessage, deprecation.CustomMessage);

                    auditingService.WroteRecord <PackageAuditRecord>(
                        r => r.Action == (status == PackageDeprecationStatus.NotDeprecated ? AuditedPackageAction.Undeprecate : AuditedPackageAction.Deprecate) &&
                        r.Reason == (status == PackageDeprecationStatus.NotDeprecated ? PackageUndeprecatedVia.Web : PackageDeprecatedVia.Web) &&
                        r.DeprecationRecord == null &&
                        r.Id == id &&
                        r.PackageRecord.NormalizedVersion == package.NormalizedVersion);
                }
            }
Exemple #20
0
            public async Task WithExistingVulnerability_NotWithdrawn_UpdatesPackages(
                bool hasExistingVulnerablePackages,
                bool wasUpdated)
            {
                // Arrange
                var key           = 1;
                var severity      = PackageVulnerabilitySeverity.Low;
                var newSeverity   = PackageVulnerabilitySeverity.Critical;
                var url           = "http://hi";
                var newUrl        = "https://howdy";
                var vulnerability = new PackageVulnerability
                {
                    GitHubDatabaseKey = key,
                    Severity          = wasUpdated ? newSeverity : severity,
                    AdvisoryUrl       = wasUpdated ? newUrl : url
                };

                var existingVulnerability = new PackageVulnerability
                {
                    GitHubDatabaseKey = key,
                    Severity          = severity,
                    AdvisoryUrl       = url
                };

                Context.Vulnerabilities.Add(existingVulnerability);

                var id           = "theId";
                var versionRange = new VersionRange(NuGetVersion.Parse("1.0.0")).ToNormalizedString();
                var range        = new VulnerablePackageVersionRange
                {
                    Vulnerability       = vulnerability,
                    PackageId           = id,
                    PackageVersionRange = versionRange
                };

                vulnerability.AffectedRanges.Add(range);

                var registration = new PackageRegistration
                {
                    Id = id
                };

                var expectedPackagesToUpdate   = new List <Package>();
                var expectedVulnerablePackages = new List <Package>();

                if (hasExistingVulnerablePackages)
                {
                    // Any packages that are already vulnerable to this vulnerability but not associated with this package vulnerability should be updated if the vulnerability is updated.
                    var existingVulnerablePackage = new Package
                    {
                        PackageRegistration = registration,
                        NormalizedVersion   = "0.0.5"
                    };

                    var existingVulnerablePackageVersion = NuGetVersion.Parse(existingVulnerablePackage.NormalizedVersion);
                    var existingRange = new VulnerablePackageVersionRange
                    {
                        Vulnerability       = existingVulnerability,
                        PackageId           = id,
                        PackageVersionRange = new VersionRange(existingVulnerablePackageVersion, true, existingVulnerablePackageVersion, true).ToNormalizedString()
                    };

                    Context.VulnerableRanges.Add(existingRange);
                    existingRange.Packages.Add(existingVulnerablePackage);
                    existingVulnerability.AffectedRanges.Add(existingRange);
                    vulnerability.AffectedRanges.Add(existingRange);

                    expectedVulnerablePackages.Add(existingVulnerablePackage);
                    if (wasUpdated)
                    {
                        expectedPackagesToUpdate.Add(existingVulnerablePackage);
                    }

                    // If an existing vulnerable range is updated, its packages should be updated.
                    var existingVulnerablePackageWithUpdatedRange = new Package
                    {
                        PackageRegistration = registration,
                        NormalizedVersion   = "0.0.9"
                    };

                    var existingVulnerablePackageVersionWithUpdatedRange = NuGetVersion.Parse(existingVulnerablePackageWithUpdatedRange.NormalizedVersion);
                    var existingRangeWithUpdatedRange = new VulnerablePackageVersionRange
                    {
                        Vulnerability       = existingVulnerability,
                        PackageId           = id,
                        PackageVersionRange = new VersionRange(existingVulnerablePackageVersionWithUpdatedRange, true, existingVulnerablePackageVersionWithUpdatedRange, true).ToNormalizedString()
                    };

                    Context.VulnerableRanges.Add(existingRangeWithUpdatedRange);
                    existingRangeWithUpdatedRange.Packages.Add(existingVulnerablePackageWithUpdatedRange);
                    existingVulnerability.AffectedRanges.Add(existingRangeWithUpdatedRange);

                    var updatedExistingRange = new VulnerablePackageVersionRange
                    {
                        Vulnerability              = existingRangeWithUpdatedRange.Vulnerability,
                        PackageId                  = existingRangeWithUpdatedRange.PackageId,
                        PackageVersionRange        = existingRangeWithUpdatedRange.PackageVersionRange,
                        FirstPatchedPackageVersion = "1.0.0"
                    };

                    vulnerability.AffectedRanges.Add(updatedExistingRange);

                    expectedVulnerablePackages.Add(existingVulnerablePackageWithUpdatedRange);
                    expectedPackagesToUpdate.Add(existingVulnerablePackageWithUpdatedRange);

                    // If a package vulnerability is missing from the new vulnerability, it should be removed.
                    var existingMissingVulnerablePackage = new Package
                    {
                        PackageRegistration = registration,
                        NormalizedVersion   = "0.0.6"
                    };

                    var existingMissingVulnerablePackageVersion = NuGetVersion.Parse(existingMissingVulnerablePackage.NormalizedVersion);
                    var existingMissingRange = new VulnerablePackageVersionRange
                    {
                        Vulnerability       = existingVulnerability,
                        PackageId           = id,
                        PackageVersionRange = new VersionRange(existingMissingVulnerablePackageVersion, true, existingMissingVulnerablePackageVersion, true).ToNormalizedString()
                    };

                    Context.VulnerableRanges.Add(existingMissingRange);
                    existingMissingRange.Packages.Add(existingMissingVulnerablePackage);
                    existingVulnerability.AffectedRanges.Add(existingMissingRange);

                    expectedPackagesToUpdate.Add(existingMissingVulnerablePackage);
                }

                Context.PackageRegistrations.Add(registration);

                // A package that fits in the version range but is not vulnerable yet should be vulnerable and updated.
                var newlyVulnerablePackage = new Package
                {
                    PackageRegistration = registration,
                    NormalizedVersion   = "1.0.2"
                };

                registration.Packages.Add(newlyVulnerablePackage);
                expectedVulnerablePackages.Add(newlyVulnerablePackage);
                expectedPackagesToUpdate.Add(newlyVulnerablePackage);

                // A package that is not vulnerable and does not fit in the version range should not be touched.
                var neverVulnerablePackage = new Package
                {
                    PackageRegistration = registration,
                    NormalizedVersion   = "0.0.1"
                };

                registration.Packages.Add(neverVulnerablePackage);

                if (expectedPackagesToUpdate.Any())
                {
                    UpdateServiceMock
                    .Setup(x => x.UpdatePackagesAsync(
                               It.Is <IReadOnlyList <Package> >(
                                   p => p
                                   .OrderBy(v => v.NormalizedVersion)
                                   .SequenceEqual(
                                       expectedPackagesToUpdate.OrderBy(v => v.NormalizedVersion))),
                               true))
                    .Returns(Task.CompletedTask)
                    .Verifiable();
                }

                var service = GetService <PackageVulnerabilityService>();

                // Act
                await service.UpdateVulnerabilityAsync(vulnerability, false);

                // Assert
                Assert.Contains(existingVulnerability, Context.Vulnerabilities);
                Assert.Contains(range, Context.VulnerableRanges);
                Assert.Equal(existingVulnerability, range.Vulnerability);
                Assert.Equal(wasUpdated ? newSeverity : severity, existingVulnerability.Severity);
                Assert.Equal(wasUpdated ? newUrl : url, existingVulnerability.AdvisoryUrl);
                Assert.Equal(
                    expectedVulnerablePackages.OrderBy(p => p.NormalizedVersion),
                    Context.VulnerableRanges.SelectMany(pv => pv.Packages).OrderBy(p => p.NormalizedVersion));

                UpdateServiceMock.Verify();

                VerifyTransaction();
            }
        private void SetUp()
        {
            _registrationVulnerable = new PackageRegistration {
                Id = "Vulnerable"
            };

            _vulnerabilityCritical = new PackageVulnerability
            {
                AdvisoryUrl       = "http://theurl/1234",
                GitHubDatabaseKey = 1234,
                Severity          = PackageVulnerabilitySeverity.Critical
            };
            _vulnerabilityModerate = new PackageVulnerability
            {
                AdvisoryUrl       = "http://theurl/5678",
                GitHubDatabaseKey = 5678,
                Severity          = PackageVulnerabilitySeverity.Moderate
            };

            _versionRangeCritical = new VulnerablePackageVersionRange
            {
                Vulnerability              = _vulnerabilityCritical,
                PackageVersionRange        = "1.1.1",
                FirstPatchedPackageVersion = "1.1.2"
            };
            _versionRangeModerate = new VulnerablePackageVersionRange
            {
                Vulnerability              = _vulnerabilityModerate,
                PackageVersionRange        = "<=1.1.1",
                FirstPatchedPackageVersion = "1.1.2"
            };

            _packageVulnerable100 = new Package
            {
                Key = 0,
                PackageRegistration     = _registrationVulnerable,
                Version                 = "1.0.0",
                VulnerablePackageRanges = new List <VulnerablePackageVersionRange>
                {
                    _versionRangeModerate
                }
            };
            _packageVulnerable110 = new Package
            {
                Key = 1,
                PackageRegistration     = _registrationVulnerable,
                Version                 = "1.1.0",
                VulnerablePackageRanges = new List <VulnerablePackageVersionRange>
                {
                    _versionRangeModerate
                }
            };
            _packageVulnerable111 = new Package
            {
                Key = 3, // simulate a different order in db - create a non-contiguous range of rows, even if the range is contiguous
                PackageRegistration     = _registrationVulnerable,
                Version                 = "1.1.1",
                VulnerablePackageRanges = new List <VulnerablePackageVersionRange>
                {
                    _versionRangeModerate,
                    _versionRangeCritical
                }
            };
            _packageVulnerable112 = new Package
            {
                Key = 2, // simulate a different order in db  - create a non-contiguous range of rows, even if the range is contiguous
                PackageRegistration     = _registrationVulnerable,
                Version                 = "1.1.2",
                VulnerablePackageRanges = new List <VulnerablePackageVersionRange>()
            };
            _packageNotVulnerable = new Package
            {
                Key = 4,
                PackageRegistration = new PackageRegistration {
                    Id = "NotVulnerable"
                },
                VulnerablePackageRanges = new List <VulnerablePackageVersionRange>()
            };
        }
Exemple #22
0
 public OptionPage(OptionPageRegistration registration, PackageRegistration package)
 {
     Registration = registration;
     Package      = package;
 }
 public PackageRegistrationAuditRecord(
     PackageRegistration packageRegistration, AuditedPackageRegistrationAction action, string owner)
     : this(packageRegistration.Id, AuditedPackageRegistration.CreateFrom(packageRegistration), action, owner)
 {
 }
Exemple #24
0
        public static IReadOnlyList <MailAddress> GetOwnersSubscribedToPackagePushedNotification(PackageRegistration packageRegistration)
        {
            if (packageRegistration == null)
            {
                throw new ArgumentNullException(nameof(packageRegistration));
            }

            var recipients = new List <MailAddress>();

            foreach (var owner in packageRegistration.Owners.Where(o => o.NotifyPackagePushed))
            {
                recipients.Add(owner.ToMailAddress());
            }

            return(recipients);
        }
Exemple #25
0
        public Fakes()
        {
            User = new User("testUser")
            {
                Key          = 42,
                EmailAddress = "*****@*****.**",
                Credentials  = new List <Credential>
                {
                    CredentialBuilder.CreatePbkdf2Password(Password),
                    CredentialBuilder.CreateV1ApiKey(Guid.Parse("519e180e-335c-491a-ac26-e83c4bd31d65"),
                                                     ExpirationForApiKeyV1)
                }
            };

            ShaUser = new User("testShaUser")
            {
                Key          = 42,
                EmailAddress = "*****@*****.**",
                Credentials  = new List <Credential>
                {
                    CredentialBuilder.CreateSha1Password(Password),
                    CredentialBuilder.CreateV1ApiKey(Guid.Parse("b9704a41-4107-4cd2-bcfa-70d84e021ab2"),
                                                     ExpirationForApiKeyV1)
                }
            };

            Admin = new User("testAdmin")
            {
                Key          = 43,
                EmailAddress = "*****@*****.**",
                Credentials  = new List <Credential> {
                    CredentialBuilder.CreatePbkdf2Password(Password)
                },
                Roles = new List <Role> {
                    new Role {
                        Name = Constants.AdminRoleName
                    }
                }
            };

            Owner = new User("testPackageOwner")
            {
                Key         = 44,
                Credentials = new List <Credential> {
                    CredentialBuilder.CreatePbkdf2Password(Password)
                },
                EmailAddress = "*****@*****.**" //package owners need confirmed email addresses, obviously.
            };

            Package = new PackageRegistration
            {
                Id     = "FakePackage",
                Owners = new List <User> {
                    Owner
                },
                Packages = new List <Package>
                {
                    new Package {
                        Version = "1.0"
                    },
                    new Package {
                        Version = "2.0"
                    }
                }
            };
        }
Exemple #26
0
            public DeleteAccountTestService(User user, PackageRegistration userPackagesRegistration)
            {
                _user = user;
                _user.ReservedNamespaces.Add(_reservedNamespace);
                _user.Credentials.Add(_credential);
                _credential.User = _user;
                _user.SecurityPolicies.Add(_securityPolicy);
                _userPackagesRegistration = userPackagesRegistration;
                _userPackages             = userPackagesRegistration.Packages;

                SupportRequests.Add(new Issue()
                {
                    CreatedBy      = user.Username,
                    Key            = 1,
                    IssueTitle     = Strings.AccountDelete_SupportRequestTitle,
                    OwnerEmail     = user.EmailAddress,
                    IssueStatusId  = IssueStatusKeys.New,
                    HistoryEntries = new List <History>()
                    {
                        new History()
                        {
                            EditedBy = user.Username, IssueId = 1, Key = 1, IssueStatusId = IssueStatusKeys.New
                        }
                    }
                });

                SupportRequests.Add(new Issue()
                {
                    CreatedBy      = $"{user.Username}_second",
                    Key            = 2,
                    IssueTitle     = "Second",
                    OwnerEmail     = "random",
                    IssueStatusId  = IssueStatusKeys.New,
                    HistoryEntries = new List <History>()
                    {
                        new History()
                        {
                            EditedBy = $"{user.Username}_second", IssueId = 2, Key = 2, IssueStatusId = IssueStatusKeys.New
                        }
                    }
                });

                PackageOwnerRequests.Add(new PackageOwnerRequest()
                {
                    PackageRegistration = new PackageRegistration()
                    {
                        Id = $"{user.Username}_first"
                    },
                    NewOwner = _user
                });

                PackageOwnerRequests.Add(new PackageOwnerRequest()
                {
                    PackageRegistration = new PackageRegistration()
                    {
                        Id = $"{user.Username}_second"
                    },
                    NewOwner = _user
                });

                AccountDeletedByUser = new AccountDelete {
                    DeletedBy = _user, DeletedByKey = _user.Key
                };
                AccountDeletedByDifferentUser = new AccountDelete {
                    DeletedBy = new User {
                        Key = 1111
                    }, DeletedByKey = 1111
                };
                PackageDeletedByUser = new PackageDelete {
                    DeletedBy = _user, DeletedByKey = _user.Key
                };
                PackageDeletedByDifferentUser = new PackageDelete {
                    DeletedBy = new User {
                        Key = 1111
                    }, DeletedByKey = 1111
                };

                PackagePushedByUser = new Package
                {
                    User    = _user,
                    UserKey = _user.Key
                };

                DeprecationDeprecatedByUser = new PackageDeprecation
                {
                    DeprecatedByUser    = _user,
                    DeprecatedByUserKey = _user.Key
                };
            }
Exemple #27
0
            public async Task ReturnsNotFoundIfGetCwesByIdThrowsArgumentException(User currentUser, User owner)
            {
                // Arrange
                var id = "id";

                var featureFlagService = GetMock <IFeatureFlagService>();

                featureFlagService
                .Setup(x => x.IsManageDeprecationEnabled(currentUser))
                .Returns(true)
                .Verifiable();

                var registration = new PackageRegistration
                {
                    Id = id
                };

                registration.Owners.Add(owner);

                var package = new Package
                {
                    NormalizedVersion   = "2.3.4",
                    PackageRegistration = registration
                };

                var packageService = GetMock <IPackageService>();

                packageService
                .Setup(x => x.FindPackagesById(id, PackageDeprecationFieldsToInclude.DeprecationAndRelationships))
                .Returns(new[] { package })
                .Verifiable();

                var deprecationService = GetMock <IPackageDeprecationService>();

                var cves = new Cve[0];

                deprecationService
                .Setup(x => x.GetOrCreateCvesByIdAsync(Enumerable.Empty <string>(), false))
                .CompletesWith(cves)
                .Verifiable();

                deprecationService
                .Setup(x => x.GetCwesById(Enumerable.Empty <string>()))
                .Throws(new ArgumentException())
                .Verifiable();

                var controller = GetController <ManageDeprecationJsonApiController>();

                controller.SetCurrentUser(currentUser);

                // Act
                var result = await controller.Deprecate(
                    id, new[] { package.NormalizedVersion }, false, false, false, null, null, null, null, null, null);

                // Assert
                AssertErrorResponse(
                    controller,
                    result,
                    HttpStatusCode.NotFound,
                    Strings.DeprecatePackage_CweMissing);
                featureFlagService.Verify();
                packageService.Verify();
            }
Exemple #28
0
        public Fakes()
        {
            _users = Get <User>();
            _packageRegistrations = Get <PackageRegistration>();

            var key = 39;
            var credentialBuilder = new CredentialBuilder();

            User = new User("testUser")
            {
                Key          = key++,
                EmailAddress = "*****@*****.**",
                Credentials  = new List <Credential>
                {
                    credentialBuilder.CreatePasswordCredential(Password),
                    TestCredentialHelper.CreateV1ApiKey(Guid.Parse("669e180e-335c-491a-ac26-e83c4bd31d65"),
                                                        ExpirationForApiKeyV1),
                    TestCredentialHelper.CreateV2ApiKey(Guid.Parse("779e180e-335c-491a-ac26-e83c4bd31d87"),
                                                        ExpirationForApiKeyV1).WithDefaultScopes(),
                    TestCredentialHelper.CreateV4ApiKey(null, out string apiKeyV4PlaintextValue).WithDefaultScopes(),
                    TestCredentialHelper.CreateV2VerificationApiKey(Guid.Parse("b0c51551-823f-4701-8496-43980b4b3913")),
                    TestCredentialHelper.CreateExternalCredential("abc")
                }
            };

            ApiKeyV4PlaintextValue = apiKeyV4PlaintextValue;

            Organization = new Organization("testOrganization")
            {
                Key          = key++,
                EmailAddress = "*****@*****.**",
                // invalid credentials for testing authentication constraints
                Credentials = new List <Credential>
                {
                    credentialBuilder.CreatePasswordCredential(Password)
                }
            };

            CreateOrganizationUsers(ref key, credentialBuilder, "", out var organization, out var organizationAdmin, out var organizationCollaborator);
            Organization             = organization;
            OrganizationAdmin        = organizationAdmin;
            OrganizationCollaborator = organizationCollaborator;

            CreateOrganizationUsers(ref key, credentialBuilder, "Owner", out var organizationOwner, out var organizationAdminOwner, out var organizationCollaboratorOwner);
            OrganizationOwner             = organizationOwner;
            OrganizationOwnerAdmin        = organizationAdminOwner;
            OrganizationOwnerCollaborator = organizationCollaboratorOwner;

            Pbkdf2User = new User("testPbkdf2User")
            {
                Key          = key++,
                EmailAddress = "*****@*****.**",
                Credentials  = new List <Credential>
                {
                    TestCredentialHelper.CreatePbkdf2Password(Password),
                    TestCredentialHelper.CreateV1ApiKey(Guid.Parse("519e180e-335c-491a-ac26-e83c4bd31d65"),
                                                        ExpirationForApiKeyV1)
                }
            };

            ShaUser = new User("testShaUser")
            {
                Key          = key++,
                EmailAddress = "*****@*****.**",
                Credentials  = new List <Credential>
                {
                    TestCredentialHelper.CreateSha1Password(Password),
                    TestCredentialHelper.CreateV1ApiKey(Guid.Parse("b9704a41-4107-4cd2-bcfa-70d84e021ab2"),
                                                        ExpirationForApiKeyV1)
                }
            };

            Admin = new User("testAdmin")
            {
                Key          = key++,
                EmailAddress = "*****@*****.**",
                Credentials  = new List <Credential> {
                    TestCredentialHelper.CreatePbkdf2Password(Password)
                },
                Roles = new List <Role> {
                    new Role {
                        Name = Constants.AdminRoleName
                    }
                }
            };

            Owner = new User("testPackageOwner")
            {
                Key         = key++,
                Credentials = new List <Credential> {
                    TestCredentialHelper.CreatePbkdf2Password(Password)
                },
                EmailAddress = "*****@*****.**" //package owners need confirmed email addresses, obviously.
            };

            Package = new PackageRegistration
            {
                Id     = "FakePackage",
                Owners = new List <User> {
                    Owner, OrganizationOwner
                },
            };
            Package.Packages = new List <Package>
            {
                new Package {
                    Version = "1.0", PackageRegistration = Package
                },
                new Package {
                    Version = "2.0", PackageRegistration = Package
                }
            };
        }
        public static Mock<IEntityRepository<Package>> SetupTestPackageRepository()
        {
            var fooPackage = new PackageRegistration { Id = "Foo" };
            var barPackage = new PackageRegistration { Id = "Bar" };
            var bazPackage = new PackageRegistration { Id = "Baz" };

            var repo = new Mock<IEntityRepository<Package>>(MockBehavior.Strict);
            repo.Setup(r => r.GetAll()).Returns(new[]
            {
                new Package
                {
                    PackageRegistration = fooPackage,
                    Version = "1.0.0",
                    IsPrerelease = false,
                    Listed = true,
                    Authors = new [] { new PackageAuthor { Name = "Test "} },
                    FlattenedAuthors = "Test",
                    Description = "Foo",
                    Summary = "Foo",
                    Tags = "Foo CommonTag"
                },
                new Package
                {
                    PackageRegistration = fooPackage,
                    Version = "1.0.1-a",
                    IsPrerelease = true,
                    Listed = true,
                    Authors = new [] { new PackageAuthor { Name = "Test "} },
                    FlattenedAuthors = "Test",
                    Description = "Foo",
                    Summary = "Foo",
                    Tags = "Foo CommonTag"
                },
                new Package
                {
                    PackageRegistration = barPackage,
                    Version = "1.0.0",
                    IsPrerelease = false,
                    Listed = true,
                    Authors = new [] { new PackageAuthor { Name = "Test "} },
                    FlattenedAuthors = "Test",
                    Description = "Bar",
                    Summary = "Bar",
                    Tags = "Bar CommonTag"
                },
                new Package
                {
                    PackageRegistration = barPackage,
                    Version = "2.0.0",
                    IsPrerelease = false,
                    Listed = true,
                    Authors = new [] { new PackageAuthor { Name = "Test "} },
                    FlattenedAuthors = "Test",
                    Description = "Bar",
                    Summary = "Bar",
                    Tags = "Bar CommonTag"
                },
                new Package
                {
                    PackageRegistration = barPackage,
                    Version = "2.0.1-a",
                    IsPrerelease = true,
                    Listed = true,
                    Authors = new [] { new PackageAuthor { Name = "Test "} },
                    FlattenedAuthors = "Test",
                    Description = "Bar",
                    Summary = "Bar",
                    Tags = "Bar CommonTag"
                },
                new Package
                {
                    PackageRegistration = barPackage,
                    Version = "2.0.1-b",
                    IsPrerelease = true,
                    Listed = false,
                    Authors = new [] { new PackageAuthor { Name = "Test "} },
                    FlattenedAuthors = "Test",
                    Description = "Bar",
                    Summary = "Bar",
                    Tags = "Bar CommonTag"
                },
                new Package
                {
                    PackageRegistration = bazPackage,
                    Version = "1.0.0",
                    IsPrerelease = false,
                    Listed = false,
                    Deleted = true, // plot twist: this package is a soft-deleted one
                    Authors = new [] { new PackageAuthor { Name = "Test "} },
                    FlattenedAuthors = "Test",
                    Description = "Baz",
                    Summary = "Baz",
                    Tags = "Baz CommonTag"
                }
            }.AsQueryable());

            return repo;
        }
Exemple #30
0
            public TestableCuratedFeedService()
            {
                StubCuratedFeed = new CuratedFeed {
                    Key = 0, Name = "aName"
                };
                StubCuratedFeed2 = new CuratedFeed {
                    Key = 1, Name = "AnotherFeed"
                };
                StubPackageRegistration_ForFeed1 = new PackageRegistration {
                    Key = 1066, Id = "aPackageId"
                };
                StubPackageRegistration_ForFeed2 = new PackageRegistration {
                    Key = 1067, Id = "aPackageId2"
                };
                StubPackageRegistration_ForFeed1_NotIncluded = new PackageRegistration {
                    Key = 1068, Id = "aPackageId2"
                };
                StubPackage = new Package {
                    PackageRegistration = StubPackageRegistration_ForFeed1, PackageRegistrationKey = StubPackageRegistration_ForFeed1.Key, Version = "1.0.0"
                };
                StubPackage_IncompatibleVersion = new Package {
                    PackageRegistration = StubPackageRegistration_ForFeed1, PackageRegistrationKey = StubPackageRegistration_ForFeed1.Key, Version = "2.0.0"
                };
                StubPackage_ForFeed1_NotIncluded = new Package {
                    PackageRegistration = StubPackageRegistration_ForFeed1_NotIncluded, PackageRegistrationKey = StubPackageRegistration_ForFeed1_NotIncluded.Key
                };

                StubCuratedPackageRegistration_ForFeed1 = new CuratedPackage
                {
                    Key                    = 1,
                    CuratedFeedKey         = StubCuratedFeed.Key,
                    CuratedFeed            = StubCuratedFeed,
                    PackageRegistration    = StubPackageRegistration_ForFeed1,
                    PackageRegistrationKey = StubPackageRegistration_ForFeed1.Key,
                    Included               = true
                };
                StubCuratedFeed.Packages.Add(StubCuratedPackageRegistration_ForFeed1);

                StubCuratedPackageRegistration_ForFeed2 = new CuratedPackage
                {
                    Key                    = 2,
                    CuratedFeedKey         = StubCuratedFeed2.Key,
                    CuratedFeed            = StubCuratedFeed2,
                    PackageRegistration    = StubPackageRegistration_ForFeed2,
                    PackageRegistrationKey = StubPackageRegistration_ForFeed2.Key,
                    Included               = true
                };
                StubCuratedFeed2.Packages.Add(StubCuratedPackageRegistration_ForFeed2);

                StubCuratedPackageRegistration_ForFeed1_NotIncluded = new CuratedPackage
                {
                    Key                    = 3,
                    CuratedFeedKey         = StubCuratedFeed.Key,
                    CuratedFeed            = StubCuratedFeed,
                    PackageRegistration    = StubPackageRegistration_ForFeed1_NotIncluded,
                    PackageRegistrationKey = StubPackageRegistration_ForFeed1_NotIncluded.Key,
                    Included               = false
                };
                StubCuratedFeed.Packages.Add(StubCuratedPackageRegistration_ForFeed1_NotIncluded);

                StubCuratedFeedRepository = new Mock <IEntityRepository <CuratedFeed> >();
                StubCuratedFeedRepository
                .Setup(repo => repo.GetAll())
                .Returns(new CuratedFeed[] { StubCuratedFeed, StubCuratedFeed2 }.AsQueryable());

                StubCuratedPackageRepository = new Mock <IEntityRepository <CuratedPackage> >();
                StubCuratedPackageRepository
                .Setup(repo => repo.GetAll())
                .Returns(new CuratedPackage[] { StubCuratedPackageRegistration_ForFeed1, StubCuratedPackageRegistration_ForFeed2, StubCuratedPackageRegistration_ForFeed1_NotIncluded }.AsQueryable());
            }
        private static Package ReadPackage(JObject doc)
        {
            var dependencies =
                doc.Value<JArray>("Dependencies")
                   .Cast<JObject>()
                   .Select(obj => new PackageDependency()
                    {
                        Id = obj.Value<string>("Id"),
                        VersionSpec = obj.Value<string>("VersionSpec"),
                        TargetFramework = obj.Value<string>("TargetFramework")
                    })
                   .ToArray();

            var frameworks =
                doc.Value<JArray>("SupportedFrameworks")
                   .Select(v => new PackageFramework() { TargetFramework = v.Value<string>() })
                   .ToArray();

            var reg = doc["PackageRegistration"];
            PackageRegistration registration = null;
            if(reg != null) {
                registration = new PackageRegistration() {
                    Id = reg.Value<string>("Id"),
                    Owners = reg.Value<JArray>("Owners")
                       .Select(v => new User { Username = v.Value<string>() })
                       .ToArray(),
                    DownloadCount = reg.Value<int>("DownloadCount"),
                    Key = reg.Value<int>("Key")
                };
            }

            return new Package
            {
                Copyright = doc.Value<string>("Copyright"),
                Created = doc.Value<DateTime>("Created"),
                Description = doc.Value<string>("Description"),
                Dependencies = dependencies,
                DownloadCount = doc.Value<int>("DownloadCount"),
                FlattenedAuthors = doc.Value<string>("Authors"),
                FlattenedDependencies = doc.Value<string>("FlattenedDependencies"),
                Hash = doc.Value<string>("Hash"),
                HashAlgorithm = doc.Value<string>("HashAlgorithm"),
                IconUrl = doc.Value<string>("IconUrl"),
                IsLatest = doc.Value<bool>("IsLatest"),
                IsLatestStable = doc.Value<bool>("IsLatestStable"),
                Key = doc.Value<int>("Key"),
                Language = doc.Value<string>("Language"),
                LastUpdated = doc.Value<DateTime>("LastUpdated"),
                LastEdited = doc.Value<DateTime?>("LastEdited"),
                PackageRegistration = registration,
                PackageRegistrationKey = registration == null ? 0 : registration.Key,
                PackageFileSize = doc.Value<long>("PackageFileSize"),
                ProjectUrl = doc.Value<string>("ProjectUrl"),
                Published = doc.Value<DateTime>("Published"),
                ReleaseNotes = doc.Value<string>("ReleaseNotes"),
                RequiresLicenseAcceptance = doc.Value<bool>("RequiresLicenseAcceptance"),
                Summary = doc.Value<string>("Summary"),
                Tags = doc.Value<string>("Tags"),
                Title = doc.Value<string>("Title"),
                Version = doc.Value<string>("Version"),
                NormalizedVersion = doc.Value<string>("NormalizedVersion"),
                SupportedFrameworks = frameworks,
                MinClientVersion = doc.Value<string>("MinClientVersion"),
                LicenseUrl = doc.Value<string>("LicenseUrl"),
                LicenseNames = doc.Value<string>("LicenseNames"),
                LicenseReportUrl = doc.Value<string>("LicenseReportUrl"),
                HideLicenseReport = doc.Value<bool>("HideLicenseReport")
            };
        }
Exemple #32
0
            public async Task ReturnsNotFoundIfAlternatePackageVersionMissing(User currentUser, User owner)
            {
                // Arrange
                var id = "id";

                var featureFlagService = GetMock <IFeatureFlagService>();

                featureFlagService
                .Setup(x => x.IsManageDeprecationEnabled(currentUser))
                .Returns(true)
                .Verifiable();

                var registration = new PackageRegistration
                {
                    Id = id
                };

                registration.Owners.Add(owner);

                var package = new Package
                {
                    PackageRegistration = registration
                };

                var packageService = GetMock <IPackageService>();

                packageService
                .Setup(x => x.FindPackagesById(id, PackageDeprecationFieldsToInclude.DeprecationAndRelationships))
                .Returns(new[] { package })
                .Verifiable();

                var alternatePackageId      = "altId";
                var alternatePackageVersion = "1.2.3-alt";

                packageService
                .Setup(x => x.FindPackageByIdAndVersionStrict(alternatePackageId, alternatePackageVersion))
                .Returns((Package)null)
                .Verifiable();

                var controller = GetController <ManageDeprecationJsonApiController>();

                controller.SetCurrentUser(currentUser);

                // Act
                var result = await controller.Deprecate(
                    id : id,
                    versions : new[] { "1.0.0" },
                    isLegacy : false,
                    hasCriticalBugs : false,
                    isOther : false,
                    alternatePackageId : alternatePackageId,
                    alternatePackageVersion : alternatePackageVersion,
                    customMessage : null);

                // Assert
                AssertErrorResponse(
                    controller,
                    result,
                    HttpStatusCode.NotFound,
                    string.Format(Strings.DeprecatePackage_NoAlternatePackage, alternatePackageId, alternatePackageVersion));
                featureFlagService.Verify();
                packageService.Verify();
            }
Exemple #33
0
            private async Task AssertSuccessful(
                User currentUser,
                User owner,
                bool isLegacy,
                bool hasCriticalBugs,
                bool isOther,
                PackageDeprecationStatus expectedStatus,
                ReturnsSuccessful_AlternatePackage_State alternatePackageState,
                bool hasCustomMessage)
            {
                // Arrange
                var id = "id";

                var featureFlagService = GetMock <IFeatureFlagService>();

                featureFlagService
                .Setup(x => x.IsManageDeprecationEnabled(currentUser))
                .Returns(true)
                .Verifiable();

                var registration = new PackageRegistration
                {
                    Id = id
                };

                registration.Owners.Add(owner);

                var package = new Package
                {
                    NormalizedVersion   = "2.3.4",
                    PackageRegistration = registration
                };

                var package2 = new Package
                {
                    NormalizedVersion   = "1.0.0",
                    PackageRegistration = registration
                };

                var unselectedPackage = new Package
                {
                    NormalizedVersion   = "1.3.2",
                    PackageRegistration = registration
                };

                var packageService = GetMock <IPackageService>();

                packageService
                .Setup(x => x.FindPackagesById(id, PackageDeprecationFieldsToInclude.DeprecationAndRelationships))
                .Returns(new[] { package, package2, unselectedPackage })
                .Verifiable();

                var alternatePackageId      = alternatePackageState != ReturnsSuccessful_AlternatePackage_State.None ? "altId" : null;
                var alternatePackageVersion = alternatePackageState == ReturnsSuccessful_AlternatePackage_State.Package ? "1.2.3-alt" : null;

                var alternatePackageRegistration = new PackageRegistration
                {
                    Id = alternatePackageId
                };

                var alternatePackage = new Package
                {
                    NormalizedVersion   = alternatePackageVersion,
                    PackageRegistration = alternatePackageRegistration
                };

                if (alternatePackageState == ReturnsSuccessful_AlternatePackage_State.Registration)
                {
                    packageService
                    .Setup(x => x.FindPackageRegistrationById(alternatePackageId))
                    .Returns(alternatePackageRegistration)
                    .Verifiable();
                }
                else if (alternatePackageState == ReturnsSuccessful_AlternatePackage_State.Package)
                {
                    packageService
                    .Setup(x => x.FindPackageByIdAndVersionStrict(alternatePackageId, alternatePackageVersion))
                    .Returns(alternatePackage)
                    .Verifiable();
                }

                var deprecationService = GetMock <IPackageDeprecationService>();

                var customMessage = hasCustomMessage ? "message" : null;

                deprecationService
                .Setup(x => x.UpdateDeprecation(
                           new[] { package, package2 },
                           expectedStatus,
                           alternatePackageState == ReturnsSuccessful_AlternatePackage_State.Registration ? alternatePackageRegistration : null,
                           alternatePackageState == ReturnsSuccessful_AlternatePackage_State.Package ? alternatePackage : null,
                           customMessage,
                           currentUser))
                .Completes()
                .Verifiable();

                var auditingService = GetService <IAuditingService>();

                var controller = GetController <ManageDeprecationJsonApiController>();

                controller.SetCurrentUser(currentUser);

                var packageNormalizedVersions = new[] { package.NormalizedVersion, package2.NormalizedVersion };

                // Act
                var result = await controller.Deprecate(
                    id,
                    packageNormalizedVersions,
                    isLegacy,
                    hasCriticalBugs,
                    isOther,
                    alternatePackageId,
                    alternatePackageVersion,
                    customMessage);

                // Assert
                AssertSuccessResponse(controller);

                if (expectedStatus == PackageDeprecationStatus.NotDeprecated)
                {
                    foreach (var normalizedVersion in packageNormalizedVersions)
                    {
                        auditingService.WroteRecord <PackageAuditRecord>(
                            r => r.Action == AuditedPackageAction.Undeprecate &&
                            r.Reason == PackageUndeprecatedVia.Web &&
                            r.DeprecationRecord == null &&
                            r.Id == id &&
                            r.PackageRecord.NormalizedVersion == normalizedVersion);
                    }
                }
                else
                {
                    foreach (var normalizedVersion in packageNormalizedVersions)
                    {
                        auditingService.WroteRecord <PackageAuditRecord>(
                            r => r.Action == AuditedPackageAction.Deprecate &&
                            r.Reason == PackageDeprecatedVia.Web &&
                            r.DeprecationRecord.Status == (int)expectedStatus &&
                            r.Id == id &&
                            r.PackageRecord.NormalizedVersion == normalizedVersion);
                    }
                }

                featureFlagService.Verify();
                packageService.Verify();
                deprecationService.Verify();
            }
 public bool IsManageDeprecationEnabled(User user, PackageRegistration registration) => throw new NotImplementedException();
Exemple #35
0
 public void TrackPackageDeprecate(IReadOnlyList <Package> packages, PackageDeprecationStatus status, PackageRegistration alternateRegistration, Package alternatePackage, bool hasCustomMessage)
 {
     throw new NotImplementedException();
 }
Exemple #36
0
            public async Task WhenPackageSupportsButDoesNotRequireSigning_AcceptsUnsignedPackages()
            {
                // Arrange
                var user1 = new User
                {
                    Key = 1
                };
                var user2 = new User
                {
                    Key = 2
                };
                var packageRegistration = new PackageRegistration
                {
                    Key = 3,
                    Id  = TestResources.UnsignedPackageId
                };
                var package = new Package
                {
                    PackageStatusKey = PackageStatus.Validating,
                };
                var certificate = new Certificate
                {
                    Key        = 4,
                    Thumbprint = TestResources.Leaf1Thumbprint
                };
                var userCertificate = new UserCertificate
                {
                    Key            = 5,
                    CertificateKey = certificate.Key,
                    Certificate    = certificate,
                    UserKey        = user1.Key,
                    User           = user1
                };

                user1.UserCertificates.Add(userCertificate);
                certificate.UserCertificates.Add(userCertificate);

                packageRegistration.Owners.Add(user1);
                packageRegistration.Owners.Add(user2);

                _message = new SignatureValidationMessage(
                    TestResources.UnsignedPackageId,
                    TestResources.UnsignedPackageVersion,
                    new Uri($"https://unit.test/{TestResources.UnsignedPackage.ToLowerInvariant()}"),
                    Guid.NewGuid());
                _packageStream = TestResources.GetResourceStream(TestResources.UnsignedPackage);
                _corePackageService
                .Setup(x => x.FindPackageRegistrationById(_message.PackageId))
                .Returns(packageRegistration);
                _corePackageService
                .Setup(x => x.FindPackageByIdAndVersionStrict(_message.PackageId, _message.PackageVersion))
                .Returns(package);

                // Act
                var result = await _target.ValidateAsync(
                    _packageKey,
                    _packageStream,
                    _message,
                    _cancellationToken);

                // Assert
                Validate(result, ValidationStatus.Succeeded, PackageSigningStatus.Unsigned);
                Assert.Empty(result.Issues);
            }
            public async Task DeleteOrganization(bool isPackageOrphaned, AccountDeletionOrphanPackagePolicy orphanPolicy)
            {
                // Arrange
                var member = new User("testUser")
                {
                    Key = Key++
                };
                var organization = new Organization("testOrganization")
                {
                    Key          = Key++,
                    EmailAddress = "*****@*****.**"
                };

                var membership = new Membership()
                {
                    Organization = organization, Member = member
                };

                member.Organizations.Add(membership);
                organization.Members.Add(membership);

                var requestedMember = new User("testRequestedMember")
                {
                    Key = Key++
                };
                var memberRequest = new MembershipRequest()
                {
                    Organization = organization, NewMember = requestedMember
                };

                requestedMember.OrganizationRequests.Add(memberRequest);
                organization.MemberRequests.Add(memberRequest);

                PackageRegistration registration = new PackageRegistration();

                registration.Owners.Add(organization);

                Package p = new Package()
                {
                    Description = "TestPackage",
                    Key         = 1
                };

                p.PackageRegistration = registration;
                registration.Packages.Add(p);

                var testableService      = new DeleteAccountTestService(organization, registration);
                var deleteAccountService = testableService.GetDeleteAccountService(isPackageOrphaned);

                // Act
                var status = await deleteAccountService.
                             DeleteAccountAsync(
                    organization,
                    member,
                    commitAsTransaction : false,
                    orphanPackagePolicy : orphanPolicy);

                // Assert
                if (orphanPolicy == AccountDeletionOrphanPackagePolicy.DoNotAllowOrphans && isPackageOrphaned)
                {
                    Assert.False(status.Success);
                    Assert.Equal(organization.Confirmed, organization.EmailAddress != null);
                    Assert.True(registration.Owners.Any(o => o.MatchesUser(organization)));
                    Assert.NotEmpty(organization.SecurityPolicies);
                    Assert.Empty(testableService.DeletedAccounts);
                    Assert.NotEmpty(testableService.PackageOwnerRequests);
                    Assert.Empty(testableService.AuditService.Records);
                    Assert.False(testableService.HasDeletedOwnerScope);
                    Assert.Empty(testableService.AuditService.Records);
                }
                else
                {
                    Assert.True(status.Success);
                    Assert.Null(organization.EmailAddress);
                    Assert.Equal(
                        orphanPolicy == AccountDeletionOrphanPackagePolicy.UnlistOrphans && isPackageOrphaned,
                        !registration.Packages.Single().Listed);
                    Assert.False(registration.Owners.Any(o => o.MatchesUser(organization)));
                    Assert.Empty(organization.SecurityPolicies);
                    Assert.Single(testableService.DeletedAccounts);
                    Assert.Empty(testableService.PackageOwnerRequests);
                    Assert.Single(testableService.AuditService.Records);
                    Assert.True(testableService.HasDeletedOwnerScope);

                    var deleteRecord = testableService.AuditService.Records[0] as DeleteAccountAuditRecord;
                    Assert.True(deleteRecord != null);
                }

                // Reserved namespaces and support requests are deleted before the request fails due to orphaned packages.
                // Because we are not committing as a transaction in these tests, they remain deleted.
                // In production, they would not be deleted because the transaction they were deleted in would fail.
                Assert.Empty(organization.ReservedNamespaces);
                Assert.Single(testableService.SupportRequests);
            }
            public async Task DeleteHappyUser(bool isPackageOrphaned, AccountDeletionOrphanPackagePolicy orphanPolicy)
            {
                // Arrange
                PackageRegistration registration = null;
                var testUser = CreateTestUser(ref registration);
                var testUserOrganizations = testUser.Organizations.ToList();
                var testableService       = new DeleteAccountTestService(testUser, registration);
                var deleteAccountService  = testableService.GetDeleteAccountService(isPackageOrphaned);

                // Act
                await deleteAccountService.
                DeleteAccountAsync(userToBeDeleted : testUser,
                                   userToExecuteTheDelete : testUser,
                                   commitAsTransaction : false,
                                   orphanPackagePolicy : orphanPolicy);


                if (orphanPolicy == AccountDeletionOrphanPackagePolicy.DoNotAllowOrphans && isPackageOrphaned)
                {
                    Assert.True(registration.Owners.Any(o => o.MatchesUser(testUser)));
                    Assert.NotEmpty(testUser.SecurityPolicies);
                    Assert.True(registration.Packages.Single().Listed);
                    Assert.NotNull(testUser.EmailAddress);
                    Assert.Empty(testableService.DeletedAccounts);
                    Assert.NotEmpty(testableService.PackageOwnerRequests);
                    Assert.False(testableService.HasDeletedOwnerScope);
                    Assert.Empty(testableService.AuditService.Records);
                    Assert.NotNull(testUser.OrganizationMigrationRequest);
                    Assert.NotEmpty(testUser.OrganizationMigrationRequests);
                    Assert.NotEmpty(testUser.OrganizationRequests);
                    Assert.NotEmpty(testUser.Organizations);
                }
                else
                {
                    Assert.False(registration.Owners.Any(o => o.MatchesUser(testUser)));
                    Assert.Empty(testUser.SecurityPolicies);
                    Assert.Equal(
                        orphanPolicy == AccountDeletionOrphanPackagePolicy.UnlistOrphans && isPackageOrphaned,
                        !registration.Packages.Single().Listed);
                    Assert.Null(testUser.EmailAddress);
                    Assert.Single(testableService.DeletedAccounts);
                    Assert.Empty(testableService.PackageOwnerRequests);
                    Assert.True(testableService.HasDeletedOwnerScope);
                    Assert.Single(testableService.AuditService.Records);
                    Assert.Null(testUser.OrganizationMigrationRequest);
                    Assert.Empty(testUser.OrganizationMigrationRequests);
                    Assert.Empty(testUser.OrganizationRequests);

                    Assert.Empty(testUser.Organizations);
                    foreach (var testUserOrganization in testUserOrganizations)
                    {
                        var notDeletedMembers = testUserOrganization.Organization.Members.Where(m => m.Member != testUser);
                        if (notDeletedMembers.Any())
                        {
                            // If an organization that the deleted user was a part of had other members, it should have at least one admin.
                            Assert.Contains(notDeletedMembers, m => m.IsAdmin);
                        }
                        else
                        {
                            // If an organization that the deleted user was a part of had no other members, it should have been deleted.
                            Assert.Contains(testUserOrganization.Organization, testableService.DeletedUsers);
                        }
                    }

                    var deleteRecord = testableService.AuditService.Records[0] as DeleteAccountAuditRecord;
                    Assert.True(deleteRecord != null);
                }

                // Reserved namespaces and support requests are deleted before the request fails due to orphaned packages.
                // Because we are not committing as a transaction in these tests, they remain deleted.
                // In production, they would not be deleted because the transaction they were deleted in would fail.
                Assert.Single(testableService.SupportRequests);
                Assert.Empty(testUser.ReservedNamespaces);
            }
Exemple #39
0
        private static Package ReadPackage(JObject doc)
        {
            var dependencies =
                doc.Value <JArray>("Dependencies")
                .Cast <JObject>()
                .Select(obj => new PackageDependency()
            {
                Id              = obj.Value <string>("Id"),
                VersionSpec     = obj.Value <string>("VersionSpec"),
                TargetFramework = obj.Value <string>("TargetFramework")
            })
                .ToArray();

            var frameworks =
                doc.Value <JArray>("SupportedFrameworks")
                .Select(v => new PackageFramework()
            {
                TargetFramework = v.Value <string>()
            })
                .ToArray();

            var reg = doc["PackageRegistration"];
            PackageRegistration registration = null;

            if (reg != null)
            {
                registration = new PackageRegistration()
                {
                    Id     = reg.Value <string>("Id"),
                    Owners = reg.Value <JArray>("Owners")
                             .Select(v => new User {
                        Username = v.Value <string>()
                    })
                             .ToArray(),
                    DownloadCount = reg.Value <int>("DownloadCount"),
                    Key           = reg.Value <int>("Key")
                };
            }

            return(new Package
            {
                Copyright = doc.Value <string>("Copyright"),
                Created = doc.Value <DateTime>("Created"),
                Description = doc.Value <string>("Description"),
                Dependencies = dependencies,
                DownloadCount = doc.Value <int>("DownloadCount"),
                FlattenedAuthors = doc.Value <string>("Authors"),
                FlattenedDependencies = doc.Value <string>("FlattenedDependencies"),
                Hash = doc.Value <string>("Hash"),
                HashAlgorithm = doc.Value <string>("HashAlgorithm"),
                IconUrl = doc.Value <string>("IconUrl"),
                IsLatest = doc.Value <bool>("IsLatest"),
                IsLatestStable = doc.Value <bool>("IsLatestStable"),
                Key = doc.Value <int>("Key"),
                Language = doc.Value <string>("Language"),
                LastUpdated = doc.Value <DateTime>("LastUpdated"),
                LastEdited = doc.Value <DateTime?>("LastEdited"),
                PackageRegistration = registration,
                PackageRegistrationKey = registration?.Key ?? 0,
                PackageFileSize = doc.Value <long>("PackageFileSize"),
                ProjectUrl = doc.Value <string>("ProjectUrl"),
                Published = doc.Value <DateTime>("Published"),
                ReleaseNotes = doc.Value <string>("ReleaseNotes"),
                RequiresLicenseAcceptance = doc.Value <bool>("RequiresLicenseAcceptance"),
                Summary = doc.Value <string>("Summary"),
                Tags = doc.Value <string>("Tags"),
                Title = doc.Value <string>("Title"),
                Version = doc.Value <string>("Version"),
                NormalizedVersion = doc.Value <string>("NormalizedVersion"),
                SupportedFrameworks = frameworks,
                MinClientVersion = doc.Value <string>("MinClientVersion"),
                LicenseUrl = doc.Value <string>("LicenseUrl"),
                LicenseNames = doc.Value <string>("LicenseNames"),
                LicenseReportUrl = doc.Value <string>("LicenseReportUrl"),
                HideLicenseReport = doc.Value <bool>("HideLicenseReport")
            });
        }
        public void DeprecationFieldsAreSetAsExpected(
            PackageDeprecationStatus status,
            bool hasAlternateRegistration,
            bool hasAlternatePackage)
        {
            // Arrange
            var deprecation = new PackageDeprecation
            {
                CustomMessage = "hello"
            };

            var alternateRegistrationId = "alternateRegistrationId";

            if (hasAlternateRegistration)
            {
                var registration = new PackageRegistration
                {
                    Id = alternateRegistrationId
                };

                deprecation.AlternatePackageRegistration = registration;
            }

            var alternatePackageRegistrationId = "alternatePackageRegistration";
            var alternatePackageVersion        = "1.0.0-alt";

            if (hasAlternatePackage)
            {
                var alternatePackageRegistration = new PackageRegistration
                {
                    Id = alternatePackageRegistrationId
                };

                var alternatePackage = new Package
                {
                    Version             = alternatePackageVersion,
                    PackageRegistration = alternatePackageRegistration
                };

                deprecation.AlternatePackage = alternatePackage;
            }

            var package = CreateTestPackage("1.0.0");

            var linkedDeprecation = new PackageDeprecation
            {
                Status = status
            };

            package.Deprecations.Add(linkedDeprecation);

            // Act
            var model = CreateDisplayPackageViewModel(package, currentUser: null, deprecation: deprecation, readmeHtml: null);

            // Assert
            Assert.Equal(status, model.DeprecationStatus);
            Assert.Equal(deprecation.CustomMessage, model.CustomMessage);

            if (hasAlternatePackage)
            {
                Assert.Equal(alternatePackageRegistrationId, model.AlternatePackageId);
                Assert.Equal(alternatePackageVersion, model.AlternatePackageVersion);
            }
            else if (hasAlternateRegistration)
            {
                Assert.Equal(alternateRegistrationId, model.AlternatePackageId);
                Assert.Null(model.AlternatePackageVersion);
            }
            else
            {
                Assert.Null(model.AlternatePackageId);
                Assert.Null(model.AlternatePackageVersion);
            }

            var versionModel = model.PackageVersions.Single();

            Assert.Equal(status, versionModel.DeprecationStatus);
            Assert.Null(versionModel.AlternatePackageId);
            Assert.Null(versionModel.AlternatePackageVersion);
            Assert.Null(versionModel.CustomMessage);
        }
            private IReadOnlyList <Package> GetPackagesForTest(PackageLatestState latestState, bool listed, int number = 0)
            {
                var registration = new PackageRegistration
                {
                    Id = "updatePackagesAsyncTest" + number
                };

                Package unselectedPackage;

                if (latestState == PackageLatestState.Not)
                {
                    unselectedPackage = new Package
                    {
                        Key                   = 1 + number * 100,
                        Version               = "3.0.0",
                        PackageRegistration   = registration,
                        IsLatest              = true,
                        IsLatestStable        = true,
                        IsLatestSemVer2       = true,
                        IsLatestStableSemVer2 = true,
                        Listed                = true
                    };
                }
                else
                {
                    unselectedPackage = new Package
                    {
                        Key                   = 1 + number * 100,
                        Version               = "1.0.0",
                        PackageRegistration   = registration,
                        IsLatest              = false,
                        IsLatestStable        = false,
                        IsLatestSemVer2       = false,
                        IsLatestStableSemVer2 = false,
                        Listed                = true
                    };
                }

                registration.Packages.Add(unselectedPackage);

                var selectedListedPackage = new Package
                {
                    Key                 = 2 + number * 100,
                    Version             = "2.0.0",
                    PackageRegistration = registration,
                    Listed              = true
                };

                registration.Packages.Add(selectedListedPackage);

                var selectedUnlistedPackage = new Package
                {
                    Key                 = 3 + number * 100,
                    Version             = "2.1.0",
                    PackageRegistration = registration,
                    Listed              = false
                };

                registration.Packages.Add(selectedUnlistedPackage);

                var selectedMaybeLatestPackage = new Package
                {
                    Key                 = 4 + number * 100,
                    Version             = "2.5.0",
                    PackageRegistration = registration,
                    Listed              = listed
                };

                registration.Packages.Add(selectedMaybeLatestPackage);

                SetLatestOfPackage(selectedMaybeLatestPackage, latestState);

                return(new[]
                {
                    selectedListedPackage,
                    selectedUnlistedPackage,
                    selectedMaybeLatestPackage
                });
            }
        public void V2FeedGetUpdatesFiltersIncludesHighestPrereleasePackage()
        {
            // Arrange
            var packageRegistrationA = new PackageRegistration { Id = "Foo" };
            var packageRegistrationB = new PackageRegistration { Id = "Qux" };
            var repo = new Mock<IEntityRepository<Package>>(MockBehavior.Strict);
            repo.Setup(r => r.GetAll()).Returns(new[] {
                new Package { PackageRegistration = packageRegistrationA, Version = "1.0.0", IsPrerelease = false, Listed = true },
                new Package { PackageRegistration = packageRegistrationA, Version = "1.1.0", IsPrerelease = false, Listed = true, 
                    SupportedFrameworks = new[] { new PackageFramework { TargetFramework = "SL5" }, new PackageFramework { TargetFramework = "Net40-Full" } } 
                },
                new Package { PackageRegistration = packageRegistrationA, Version = "1.2.0", IsPrerelease = false, Listed = true, 
                    SupportedFrameworks = new[] { new PackageFramework { TargetFramework = "SL5" }, new PackageFramework { TargetFramework = "Net40-Full" } } 
                },
                new Package { PackageRegistration = packageRegistrationA, Version = "1.3.0-alpha", IsPrerelease = true, Listed = true, 
                    SupportedFrameworks = new[] { new PackageFramework { TargetFramework = "SL5" }, new PackageFramework { TargetFramework = "Net40-Full" } } 
                },
                new Package { PackageRegistration = packageRegistrationA, Version = "2.0.0", IsPrerelease = false, Listed = true, 
                    SupportedFrameworks = new[] { new PackageFramework { TargetFramework = "SL5" }, new PackageFramework { TargetFramework = "WinRT" } } 
                },
                new Package { PackageRegistration = packageRegistrationB, Version = "2.0", IsPrerelease = false, Listed = true },
            }.AsQueryable());
            var configuration = new Mock<IConfiguration>(MockBehavior.Strict);
            configuration.Setup(c => c.GetSiteRoot(false)).Returns("https://localhost:8081/");
            var v2Service = new TestableV2Feed(repo.Object, configuration.Object, null);

            // Act
            var result = v2Service.GetUpdates("Foo|Qux", "1.0|1.5", includePrerelease: true, includeAllVersions: false, targetFrameworks: "net40")
                                  .ToList();

            // Assert
            Assert.Equal(2, result.Count);
            AssertPackage(new { Id = "Foo", Version = "1.3.0-alpha" }, result[0]);
            AssertPackage(new { Id = "Qux", Version = "2.0" }, result[1]);
        }
        public void V2FeedGetUpdatesReturnsVersionsNewerThanListedVersion()
        {
            // Arrange
            var packageRegistrationA = new PackageRegistration { Id = "Foo" };
            var packageRegistrationB = new PackageRegistration { Id = "Qux" };
            var repo = new Mock<IEntityRepository<Package>>(MockBehavior.Strict);
            repo.Setup(r => r.GetAll()).Returns(new[] {
                new Package { PackageRegistration = packageRegistrationA, Version = "1.0.0", IsPrerelease = false, Listed = true },
                new Package { PackageRegistration = packageRegistrationA, Version = "1.1.0", IsPrerelease = false, Listed = true },
                new Package { PackageRegistration = packageRegistrationA, Version = "1.2.0-alpha", IsPrerelease = true, Listed = true },
                new Package { PackageRegistration = packageRegistrationA, Version = "1.2.0", IsPrerelease = false, Listed = true },
                new Package { PackageRegistration = packageRegistrationB, Version = "2.0", IsPrerelease = false, Listed = true },
            }.AsQueryable());
            var configuration = new Mock<IConfiguration>(MockBehavior.Strict);
            configuration.Setup(c => c.GetSiteRoot(false)).Returns("https://localhost:8081/");
            var v2Service = new TestableV2Feed(repo.Object, configuration.Object, null);

            // Act
            var result = v2Service.GetUpdates("Foo|Qux", "1.0.0|0.9", includePrerelease: false, includeAllVersions: true, targetFrameworks: null)
                                  .ToList();

            // Assert
            Assert.Equal(3, result.Count);
            AssertPackage(new { Id = "Foo", Version = "1.1.0" }, result[0]);
            AssertPackage(new { Id = "Foo", Version = "1.2.0" }, result[1]);
            AssertPackage(new { Id = "Qux", Version = "2.0" }, result[2]);
        }
        public static Mock <IEntityRepository <Package> > SetupTestPackageRepository()
        {
            var fooPackage = new PackageRegistration {
                Id = "Foo"
            };
            var barPackage = new PackageRegistration {
                Id = "Bar"
            };
            var bazPackage = new PackageRegistration {
                Id = "Baz"
            };

            var repo = new Mock <IEntityRepository <Package> >(MockBehavior.Strict);

            repo.Setup(r => r.GetAll()).Returns(new[]
            {
                new Package
                {
                    PackageRegistration = fooPackage,
                    Version             = "1.0.0",
                    IsPrerelease        = false,
                    Listed  = true,
                    Authors = new [] { new PackageAuthor {
                                           Name = "Test "
                                       } },
                    FlattenedAuthors = "Test",
                    Description      = "Foo",
                    Summary          = "Foo",
                    Tags             = "Foo CommonTag"
                },
                new Package
                {
                    PackageRegistration = fooPackage,
                    Version             = "1.0.1-a",
                    IsPrerelease        = true,
                    Listed  = true,
                    Authors = new [] { new PackageAuthor {
                                           Name = "Test "
                                       } },
                    FlattenedAuthors = "Test",
                    Description      = "Foo",
                    Summary          = "Foo",
                    Tags             = "Foo CommonTag"
                },
                new Package
                {
                    PackageRegistration = barPackage,
                    Version             = "1.0.0",
                    IsPrerelease        = false,
                    Listed  = true,
                    Authors = new [] { new PackageAuthor {
                                           Name = "Test "
                                       } },
                    FlattenedAuthors = "Test",
                    Description      = "Bar",
                    Summary          = "Bar",
                    Tags             = "Bar CommonTag"
                },
                new Package
                {
                    PackageRegistration = barPackage,
                    Version             = "2.0.0",
                    IsPrerelease        = false,
                    Listed  = true,
                    Authors = new [] { new PackageAuthor {
                                           Name = "Test "
                                       } },
                    FlattenedAuthors = "Test",
                    Description      = "Bar",
                    Summary          = "Bar",
                    Tags             = "Bar CommonTag"
                },
                new Package
                {
                    PackageRegistration = barPackage,
                    Version             = "2.0.1-a",
                    IsPrerelease        = true,
                    Listed  = true,
                    Authors = new [] { new PackageAuthor {
                                           Name = "Test "
                                       } },
                    FlattenedAuthors = "Test",
                    Description      = "Bar",
                    Summary          = "Bar",
                    Tags             = "Bar CommonTag"
                },
                new Package
                {
                    PackageRegistration = barPackage,
                    Version             = "2.0.1-b",
                    IsPrerelease        = true,
                    Listed  = false,
                    Authors = new [] { new PackageAuthor {
                                           Name = "Test "
                                       } },
                    FlattenedAuthors = "Test",
                    Description      = "Bar",
                    Summary          = "Bar",
                    Tags             = "Bar CommonTag"
                },
                new Package
                {
                    PackageRegistration = bazPackage,
                    Version             = "1.0.0",
                    IsPrerelease        = false,
                    Listed  = false,
                    Deleted = true, // plot twist: this package is a soft-deleted one
                    Authors = new [] { new PackageAuthor {
                                           Name = "Test "
                                       } },
                    FlattenedAuthors = "Test",
                    Description      = "Baz",
                    Summary          = "Baz",
                    Tags             = "Baz CommonTag"
                }
            }.AsQueryable());

            return(repo);
        }
        private static IQueryable <Package> CreatePackagesQueryable()
        {
            var packageRegistration = new PackageRegistration {
                Id = TestPackageId
            };

            var list = new List <Package>
            {
                new Package
                {
                    PackageRegistration = packageRegistration,
                    Version             = "1.0.0.0",
                    NormalizedVersion   = "1.0.0",
                    SemVerLevelKey      = SemVerLevelKey.Unknown
                },
                new Package
                {
                    PackageRegistration = packageRegistration,
                    Version             = "1.0.0.0-alpha",
                    NormalizedVersion   = "1.0.0-alpha",
                    IsPrerelease        = true,
                    SemVerLevelKey      = SemVerLevelKey.Unknown
                },
                new Package
                {
                    PackageRegistration = packageRegistration,
                    Version             = "2.0.0",
                    NormalizedVersion   = "2.0.0",
                    SemVerLevelKey      = SemVerLevelKey.Unknown,
                    IsLatestStable      = true
                },
                new Package
                {
                    PackageRegistration = packageRegistration,
                    Version             = "2.0.0-alpha",
                    NormalizedVersion   = "2.0.0-alpha",
                    IsPrerelease        = true,
                    SemVerLevelKey      = SemVerLevelKey.Unknown,
                    IsLatest            = true
                },
                new Package
                {
                    PackageRegistration = packageRegistration,
                    Version             = "2.0.0-alpha.1",
                    NormalizedVersion   = "2.0.0-alpha.1",
                    IsPrerelease        = true,
                    SemVerLevelKey      = SemVerLevelKey.SemVer2
                },
                new Package
                {
                    PackageRegistration   = packageRegistration,
                    Version               = "2.0.0+metadata",
                    NormalizedVersion     = "2.0.0",
                    SemVerLevelKey        = SemVerLevelKey.SemVer2,
                    IsLatestStableSemVer2 = true
                },
                new Package
                {
                    PackageRegistration = packageRegistration,
                    Version             = "2.0.1-alpha.1",
                    NormalizedVersion   = "2.0.1-alpha.1",
                    IsPrerelease        = true,
                    SemVerLevelKey      = SemVerLevelKey.SemVer2,
                    IsLatestSemVer2     = true
                }
            };

            return(list.AsQueryable());
        }
            public async Task DeleteUnconfirmedOrganization()
            {
                // Arrange
                var member = new User("testUser")
                {
                    Key = Key++
                };
                var organization = new Organization("testOrganization")
                {
                    Key = Key++
                };

                var membership = new Membership()
                {
                    Organization = organization, Member = member
                };

                member.Organizations.Add(membership);
                organization.Members.Add(membership);

                var requestedMember = new User("testRequestedMember")
                {
                    Key = Key++
                };
                var memberRequest = new MembershipRequest()
                {
                    Organization = organization, NewMember = requestedMember
                };

                requestedMember.OrganizationRequests.Add(memberRequest);
                organization.MemberRequests.Add(memberRequest);

                PackageRegistration registration = new PackageRegistration();

                registration.Owners.Add(organization);

                Package p = new Package()
                {
                    Description = "TestPackage",
                    Key         = 1
                };

                p.PackageRegistration = registration;
                registration.Packages.Add(p);

                var testableService      = new DeleteAccountTestService(organization, registration);
                var deleteAccountService = testableService.GetDeleteAccountService();

                // Act
                var status = await deleteAccountService.
                             DeleteAccountAsync(
                    organization,
                    member,
                    commitAsTransaction : false,
                    orphanPackagePolicy : AccountDeletionOrphanPackagePolicy.KeepOrphans);

                // Assert
                Assert.True(status.Success);
                Assert.Null(testableService.User);
                Assert.Empty(registration.Owners);
                Assert.Empty(organization.SecurityPolicies);
                Assert.Empty(organization.ReservedNamespaces);
                Assert.Empty(testableService.DeletedAccounts);
                Assert.Single(testableService.SupportRequests);
                Assert.Empty(testableService.PackageOwnerRequests);
                Assert.True(testableService.HasDeletedOwnerScope);
                Assert.Single(testableService.AuditService.Records);

                var deleteRecord = testableService.AuditService.Records[0] as DeleteAccountAuditRecord;

                Assert.True(deleteRecord != null);
            }
            public void WillNotAttemptToSendIfNoOwnersAllow()
            {
                var from = new MailAddress("*****@*****.**", "flossy");
                var package = new PackageRegistration { Id = "smangit" };
                package.Owners = new[] {
                    new User {EmailAddress = "*****@*****.**", EmailAllowed = false },
                    new User {EmailAddress = "*****@*****.**", EmailAllowed = false }
                };
                var mailSender = new Mock<IMailSender>();
                mailSender.Setup(m => m.Send(It.IsAny<MailMessage>())).Throws(new InvalidOperationException());
                var setting = new GallerySetting { GalleryOwnerName = "Joe Schmoe", GalleryOwnerEmail = "*****@*****.**" };
                var messageService = new MessageService(mailSender.Object, setting);

                var message = messageService.SendContactOwnersMessage(from, package, "Test message", "http://someurl/");

                Assert.Equal(0, message.To.Count);
            }
            public void WillNotSendEmailToOwnerThatOptsOut()
            {
                var from = new MailAddress("*****@*****.**", "flossy");
                var package = new PackageRegistration { Id = "smangit" };
                package.Owners = new[] {
                    new User {EmailAddress = "*****@*****.**", EmailAllowed = true },
                    new User {EmailAddress = "*****@*****.**", EmailAllowed = false }
                };
                var mailSender = new Mock<IMailSender>();
                var setting = new GallerySetting { GalleryOwnerName = "Joe Schmoe", GalleryOwnerEmail = "*****@*****.**" };
                var messageService = new MessageService(mailSender.Object, setting);

                var message = messageService.SendContactOwnersMessage(from, package, "Test message", "http://someurl/");

                Assert.Equal("*****@*****.**", message.To[0].Address);
                Assert.Equal(1, message.To.Count);
            }
            public void WillSendEmailToAllOwners()
            {
                var from = new MailAddress("*****@*****.**", "flossy");
                var package = new PackageRegistration { Id = "smangit" };
                package.Owners = new[] {
                    new User {EmailAddress = "*****@*****.**", EmailAllowed = true },
                    new User {EmailAddress = "*****@*****.**", EmailAllowed = true }
                };
                var mailSender = new Mock<IMailSender>();
                var setting = new GallerySetting { GalleryOwnerName = "NuGet Gallery", GalleryOwnerEmail = "*****@*****.**" };
                var messageService = new MessageService(mailSender.Object, setting);

                var message = messageService.SendContactOwnersMessage(from, package, "Test message", "http://someurl/");

                mailSender.Verify(m => m.Send(It.IsAny<MailMessage>()));
                Assert.Equal("*****@*****.**", message.To[0].Address);
                Assert.Equal("*****@*****.**", message.To[1].Address);
                Assert.Contains("[NuGet Gallery] Message for owners of the package 'smangit'", message.Subject);
                Assert.Contains("Test message", message.Body);
                Assert.Contains("User flossy &lt;[email protected]&gt; sends the following message to the owners of Package 'smangit'.", message.Body);
            }
            public void SendsPackageOwnerRequestConfirmationUrl()
            {
                var to = new User { Username = "******", EmailAddress = "*****@*****.**", EmailAllowed = true };
                var from = new User { Username = "******", EmailAddress = "*****@*****.**" };
                var mailSender = new Mock<IMailSender>();
                var setting = new GallerySetting { GalleryOwnerName = "NuGet Gallery", GalleryOwnerEmail = "*****@*****.**" };
                var messageService = new MessageService(mailSender.Object, setting);
                var package = new PackageRegistration { Id = "CoolStuff" };
                var confirmationUrl = "http://example.com/confirmation-token-url";

                var message = messageService.SendPackageOwnerRequest(from, to, package, confirmationUrl);

                Assert.Equal("*****@*****.**", message.To[0].Address);
                Assert.Equal("*****@*****.**", message.From.Address);
                Assert.Equal("[NuGet Gallery] The user 'Existing' wants to add you as an owner of the package 'CoolStuff'.", message.Subject);
                Assert.Contains(confirmationUrl, message.Body);
                Assert.Contains("The user 'Existing' wants to add you as an owner of the package 'CoolStuff'.", message.Body);
            }
            public void DoesNotSendRequestIfUserDoesNotAllowEmails()
            {
                var to = new User { Username = "******", EmailAddress = "*****@*****.**", EmailAllowed = false };
                var from = new User { Username = "******", EmailAddress = "*****@*****.**" };
                var mailSender = new Mock<IMailSender>();
                mailSender.Setup(s => s.Send(It.IsAny<MailMessage>())).Throws(new InvalidOperationException("Should not be called"));
                var setting = new GallerySetting { GalleryOwnerName = "NuGet Gallery", GalleryOwnerEmail = "*****@*****.**" };
                var messageService = new MessageService(mailSender.Object, setting);
                var package = new PackageRegistration { Id = "CoolStuff" };
                var confirmationUrl = "http://example.com/confirmation-token-url";

                var message = messageService.SendPackageOwnerRequest(from, to, package, confirmationUrl);

                Assert.Null(message);
            }