public TestableCuratedPackagesController()
            {
                Fakes = new Fakes();

                StubCuratedFeed = new CuratedFeed
                    { Key = 0, Name = "aFeedName", Managers = new HashSet<User>(new[] { Fakes.User }) };
                StubPackageRegistration = new PackageRegistration { Key = 0, Id = "anId" };

                OwinContext = Fakes.CreateOwinContext();

                EntitiesContext = new FakeEntitiesContext();
                EntitiesContext.CuratedFeeds.Add(StubCuratedFeed);
                EntitiesContext.PackageRegistrations.Add(StubPackageRegistration);

                var curatedFeedRepository = new EntityRepository<CuratedFeed>(
                    EntitiesContext);

                var curatedPackageRepository = new EntityRepository<CuratedPackage>(
                    EntitiesContext);

                base.CuratedFeedService = new CuratedFeedService(
                    curatedFeedRepository,
                    curatedPackageRepository);

                var httpContext = new Mock<HttpContextBase>();
                TestUtility.SetupHttpContextMockForUrlGeneration(httpContext, this);
            }
        public bool ConfirmPackageOwner(PackageRegistration package, User pendingOwner, string token)
        {
            if (package == null)
            {
                throw new ArgumentNullException("package");
            }

            if (pendingOwner == null)
            {
                throw new ArgumentNullException("pendingOwner");
            }

            if (String.IsNullOrEmpty(token))
            {
                throw new ArgumentNullException("token");
            }

            if (package.IsOwner(pendingOwner))
            {
                return true;
            }

            var request = FindExistingPackageOwnerRequest(package, pendingOwner);
            if (request != null && request.ConfirmationCode == token)
            {
                AddPackageOwner(package, pendingOwner);
                return true;
            }

            return false;
        }
            public async Task CreatePackageWillSavePackageFileToFileStorage()
            {
                // Arrange
                var guid = Guid.NewGuid().ToString();

                var fakeUser = new User();
                var userService = new Mock<IUserService>();
                userService.Setup(x => x.FindByApiKey(It.IsAny<Guid>())).Returns(fakeUser);

                var packageRegistration = new PackageRegistration();
                packageRegistration.Owners.Add(fakeUser);

                var packageService = new Mock<IPackageService>();
                packageService.Setup(p => p.FindPackageRegistrationById(It.IsAny<string>())).Returns(packageRegistration);

                var packageFileService = new Mock<IPackageFileService>();
                packageFileService.Setup(p => p.SavePackageFileAsync(It.IsAny<Package>(), It.IsAny<Stream>())).Returns(Task.FromResult(0)).Verifiable();

                var nuGetPackage = new Mock<INupkg>();
                nuGetPackage.Setup(x => x.Metadata.Id).Returns("theId");
                nuGetPackage.Setup(x => x.Metadata.Version).Returns(new SemanticVersion("1.0.42"));

                var controller = CreateController(
                    fileService: packageFileService,
                    userService: userService,
                    packageService: packageService,
                    packageFromInputStream: nuGetPackage);

                // Act
                await controller.CreatePackagePut(guid);

                // Assert
                packageFileService.Verify();
            }
Esempio n. 4
0
            public async Task CreatePackageWillSavePackageFileToFileStorage()
            {
                // Arrange
                var user = new User() { EmailAddress = "*****@*****.**" };
                var packageRegistration = new PackageRegistration();
                packageRegistration.Id = "theId";
                packageRegistration.Owners.Add(user);
                var package = new Package();
                package.PackageRegistration = packageRegistration;
                package.Version = "1.0.42";
                packageRegistration.Packages.Add(package);

                var controller = new TestableApiController();
                controller.SetCurrentUser(user);
                controller.MockPackageFileService.Setup(p => p.SavePackageFileAsync(It.IsAny<Package>(), It.IsAny<Stream>()))
                    .Returns(Task.CompletedTask).Verifiable();
                controller.MockPackageService.Setup(p => p.FindPackageRegistrationById(It.IsAny<string>()))
                    .Returns(packageRegistration);
                controller.MockPackageService.Setup(p => p.CreatePackageAsync(It.IsAny<PackageArchiveReader>(), It.IsAny<PackageStreamMetadata>(), It.IsAny<User>(), false))
                    .Returns(Task.FromResult(package));

                var nuGetPackage = TestPackage.CreateTestPackageStream("theId", "1.0.42");
                controller.SetupPackageFromInputStream(nuGetPackage);

                // Act
                await controller.CreatePackagePut();

                // Assert
                controller.MockPackageFileService.Verify();
            }
            public void WillReturnConflictIfAPackageWithTheIdAndSemanticVersionAlreadyExists()
            {
                var version = new SemanticVersion("1.0.42");
                var nuGetPackage = new Mock<IPackage>();
                nuGetPackage.Setup(x => x.Id).Returns("theId");
                nuGetPackage.Setup(x => x.Version).Returns(version);

                var user = new User();

                var packageRegistration = new PackageRegistration
                {
                    Packages = new List<Package> { new Package { Version = version.ToString() } },
                    Owners = new List<User> { user }
                };

                var packageSvc = new Mock<IPackageService>();
                packageSvc.Setup(x => x.FindPackageRegistrationById(It.IsAny<string>())).Returns(packageRegistration);
                var userSvc = new Mock<IUserService>();
                userSvc.Setup(x => x.FindByApiKey(It.IsAny<Guid>())).Returns(user);
                var controller = CreateController(userSvc: userSvc, packageSvc: packageSvc, packageFromInputStream: nuGetPackage.Object);

                // Act
                var result = controller.CreatePackagePut(Guid.NewGuid().ToString());

                // Assert
                Assert.IsType<HttpStatusCodeWithBodyResult>(result);
                var statusCodeResult = (HttpStatusCodeWithBodyResult)result;
                Assert.Equal(409, statusCodeResult.StatusCode);
                Assert.Equal(String.Format(Strings.PackageExistsAndCannotBeModified, "theId", "1.0.42"), statusCodeResult.StatusDescription);
            }
        public void IdConflictsWithExistingPackageTitleTests(string existingPackageId, string existingPackageTitle, string newPackageId, bool shouldBeConflict)
        {
            // Arrange
            var existingPackageRegistration = new PackageRegistration
            {
                Id = existingPackageId,
                Owners = new HashSet<User>()
            };
            var existingPackage = new Package
            {
                PackageRegistration = existingPackageRegistration,
                Version = "1.0.0",
                Title = existingPackageTitle
            };

            var packageRegistrationRepository = new Mock<IEntityRepository<PackageRegistration>>();
            packageRegistrationRepository.Setup(r => r.GetAll()).Returns(new[] { existingPackageRegistration }.AsQueryable());

            var packageRepository = new Mock<IEntityRepository<Package>>();
            packageRepository.Setup(r => r.GetAll()).Returns(new[] { existingPackage }.AsQueryable());

            var target = new PackageNamingConflictValidator(packageRegistrationRepository.Object, packageRepository.Object);
            
            // Act
            var result = target.IdConflictsWithExistingPackageTitle(newPackageId);

            // Assert
            Assert.True(result == shouldBeConflict);
        }
            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 CuratedPackage Execute(
            CuratedFeed curatedFeed, 
            PackageRegistration packageRegistration, 
            bool included = false, 
            bool automaticallyCurated = false,
            string notes = null,
            bool commitChanges = true)
        {
            if (curatedFeed == null)
            {
                throw new ArgumentNullException("curatedFeed");
            }

            if (packageRegistration == null)
            {
                throw new ArgumentNullException("packageRegistration");
            }

            var curatedPackage = new CuratedPackage
            {
                PackageRegistrationKey = packageRegistration.Key,
                Included = included,
                AutomaticallyCurated = automaticallyCurated,
                Notes = notes,
            };

            curatedFeed.Packages.Add(curatedPackage);

            if (commitChanges)
            {
                Entities.SaveChanges();
            }

            return curatedPackage;
        }
            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);
                MailMessage message = null;
                mailSender.Setup(m => m.Send(It.IsAny<MailMessage>())).Callback<MailMessage>(m => { message = m; });

                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 TestableCreateCuratedPackageCommand()
     : base(null)
 {
     StubCuratedFeed = new CuratedFeed { Key = 0, Name = "aName", };
     StubEntitiesContext = new Mock<IEntitiesContext>();
     StubPackageRegistration = new PackageRegistration { Key = 0, };
     Entities = StubEntitiesContext.Object;
 }
            public TestableCuratedPackagesController()
            {
                StubCuratedFeed = new CuratedFeed
                    { Key = 0, Name = "aFeedName", Managers = new HashSet<User>(new[] { Fakes.User }) };
                StubPackageRegistration = new PackageRegistration { Key = 0, Id = "anId" };
                StubPackage = new Package
                {
                    Key = 34,
                    PackageRegistration = StubPackageRegistration,
                    PackageRegistrationKey = StubPackageRegistration.Key,
                    Version = "1.0.0"
                };
                StubLatestPackage = new Package
                {
                    Key = 42,
                    PackageRegistration = StubPackageRegistration,
                    PackageRegistrationKey = StubPackageRegistration.Key,
                    Version = "2.0.1-alpha",
                    IsLatest = true,
                    IsPrerelease = true
                };
                StubLatestStablePackage = new Package
                {
                    Key = 41,
                    PackageRegistration = StubPackageRegistration,
                    PackageRegistrationKey = StubPackageRegistration.Key,
                    Version = "2.0.0",
                    IsLatestStable = true
                };

                OwinContext = Fakes.CreateOwinContext();

                EntitiesContext = new FakeEntitiesContext();
                EntitiesContext.CuratedFeeds.Add(StubCuratedFeed);
                EntitiesContext.PackageRegistrations.Add(StubPackageRegistration);

                StubPackageRegistration.Packages.Add(StubPackage);
                StubPackageRegistration.Packages.Add(StubLatestPackage);
                StubPackageRegistration.Packages.Add(StubLatestStablePackage);

                var curatedFeedRepository = new EntityRepository<CuratedFeed>(
                    EntitiesContext);

                var curatedPackageRepository = new EntityRepository<CuratedPackage>(
                    EntitiesContext);

                base.CuratedFeedService = new CuratedFeedService(
                    curatedFeedRepository,
                    curatedPackageRepository);

                var httpContext = new Mock<HttpContextBase>();
                TestUtility.SetupHttpContextMockForUrlGeneration(httpContext, this);
            }
Esempio n. 12
0
        public void AddPackageOwner(PackageRegistration package, User user)
        {
            package.Owners.Add(user);
            packageRepo.CommitChanges();

            var request = FindExistingPackageOwnerRequest(package, user);
            if (request != null)
            {
                packageOwnerRequestRepository.DeleteOnCommit(request);
                packageOwnerRequestRepository.CommitChanges();
            }
        }
        protected void InterceptPackageRegistrationMaterialized(PackageRegistration packageRegistration)
        {
            if (packageRegistration == null)
            {
                return;
            }

            int downloadCount;
            if (_downloadCountService.TryGetDownloadCountForPackageRegistration(packageRegistration.Id, out downloadCount))
            {
                packageRegistration.DownloadCount = downloadCount;
            }
        }
        private static JObject ToJson_PackageRegistration(PackageRegistration packageRegistration)
        {
            JArray owners = ToJson_Owners(packageRegistration.Owners);

            JObject obj = new JObject();

            obj.Add("Key", packageRegistration.Key);
            obj.Add("Id", packageRegistration.Id);
            obj.Add("DownloadCount", packageRegistration.DownloadCount);
            obj.Add("Owners", owners);

            return obj;
        }
Esempio n. 15
0
                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<ConfigurationService>(MockBehavior.Strict);
                    configuration.Setup(c => c.GetSiteRoot(It.IsAny<bool>())).Returns("https://localhost:8081/");
                    var searchService = new Mock<ISearchService>(MockBehavior.Strict);
                    searchService.Setup(s => s.Search(It.IsAny<SearchFilter>())).Returns
                        <IQueryable<Package>, string>((_, __) => Task.FromResult(new SearchResults(_.Count(), DateTime.UtcNow, _)));
                    searchService.Setup(s => s.ContainsAllVersions).Returns(false);
                    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 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 CuratedPackage CreatedCuratedPackage(
            CuratedFeed curatedFeed,
            PackageRegistration packageRegistration,
            bool included = false,
            bool automaticallyCurated = false,
            string notes = null,
            bool commitChanges = true)
        {
            if (curatedFeed == null)
            {
                throw new ArgumentNullException("curatedFeed");
            }

            if (packageRegistration == null)
            {
                throw new ArgumentNullException("packageRegistration");
            }

            var curatedPackage = curatedFeed.Packages
                .SingleOrDefault(cp => cp.PackageRegistrationKey == packageRegistration.Key);

            if (curatedPackage == null)
            {
                curatedPackage = new CuratedPackage
                {
                    PackageRegistration = packageRegistration,
                    Included = included,
                    AutomaticallyCurated = automaticallyCurated,
                    Notes = notes,
                };

                curatedFeed.Packages.Add(curatedPackage);
            }

            if (commitChanges)
            {
                CuratedFeedRepository.CommitChanges();
            }

            return curatedPackage;
        }
            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);
                MailMessage message = null;
                mailSender.Setup(m => m.Send(It.IsAny<MailMessage>())).Callback<MailMessage>(m => { message = m; });


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

                Assert.Equal("*****@*****.**", message.To[0].Address);
                Assert.Equal(1, message.To.Count);
            }
        public void SendContactOwnersMessage(
            MailAddress fromAddress, PackageRegistration packageRegistration, string message, string emailSettingsUrl)
        {
            string subject = "[{0}] Message for owners of the package '{1}'";
            string body = @"_User {0} &lt;{1}&gt; sends the following message to the owners of Package '{2}'._

            {3}

            -----------------------------------------------
            <em style=""font-size: 0.8em;"">
            To stop receiving contact emails as an owner of this package, sign in to the {4} and
            [change your email notification settings]({5}).
            </em>";

            body = String.Format(
                CultureInfo.CurrentCulture,
                body,
                fromAddress.DisplayName,
                fromAddress.Address,
                packageRegistration.Id,
                message,
                _settings.GalleryOwnerName,
                emailSettingsUrl);

            subject = String.Format(CultureInfo.CurrentCulture, subject, _settings.GalleryOwnerName, packageRegistration.Id);

            using (var mailMessage = new MailMessage())
            {
                mailMessage.Subject = subject;
                mailMessage.Body = body;
                mailMessage.From = fromAddress;

                AddOwnersToMailMessage(packageRegistration, mailMessage);
                if (mailMessage.To.Any())
                {
                    SendMessage(mailMessage);
                }
            }
        }
        private void TitleConflictsWithExistingRegistrationIdTests(string existingRegistrationId, string newPackageTitle, bool shouldBeConflict)
        {
            // Arrange
            var existingPackageRegistration = new PackageRegistration
            {
                Id = existingRegistrationId,
                Owners = new HashSet<User>()
            };

            var packageRegistrationRepository = new Mock<IEntityRepository<PackageRegistration>>();
            packageRegistrationRepository.Setup(r => r.GetAll()).Returns(new[] { existingPackageRegistration }.AsQueryable());

            var packageRepository = new Mock<IEntityRepository<Package>>();

            var target = new PackageNamingConflictValidator(packageRegistrationRepository.Object, packageRepository.Object);

            // Act
            var result = target.TitleConflictsWithExistingRegistrationId("NewPackageId", newPackageTitle);

            // Assert
            Assert.True(result == shouldBeConflict);
        }
            public TestableCuratedPackagesController()
            {
                StubCuratedFeed = new CuratedFeed
                    { Key = 0, Name = "aFeedName", Managers = new HashSet<User>(new[] { new User { Username = "******" } }) };
                StubIdentity = new Mock<IIdentity>();
                StubPackageRegistration = new PackageRegistration { Key = 0, Id = "anId" };

                StubIdentity.Setup(stub => stub.IsAuthenticated).Returns(true);
                StubIdentity.Setup(stub => stub.Name).Returns("aUsername");

                EntitiesContext = new FakeEntitiesContext();
                EntitiesContext.CuratedFeeds.Add(StubCuratedFeed);
                EntitiesContext.PackageRegistrations.Add(StubPackageRegistration);

                var curatedFeedRepository = new EntityRepository<CuratedFeed>(
                    EntitiesContext);

                var curatedPackageRepository = new EntityRepository<CuratedPackage>(
                    EntitiesContext);

                base.CuratedFeedService = new CuratedFeedService(
                    curatedFeedRepository,
                    curatedPackageRepository);
            }
Esempio n. 22
0
            public async Task CreatePackageWillSavePackageFileToFileStorage()
            {
                // Arrange
                var user = new User() { EmailAddress = "*****@*****.**" }; 
                var userService = new Mock<IUserService>();
                var packageRegistration = new PackageRegistration();
                packageRegistration.Owners.Add(user);

                var controller = new TestableApiController();
                controller.SetCurrentUser(user);
                controller.MockPackageFileService.Setup(p => p.SavePackageFileAsync(It.IsAny<Package>(), It.IsAny<Stream>())).Returns(Task.FromResult(0)).Verifiable();
                controller.MockPackageService.Setup(p => p.FindPackageRegistrationById(It.IsAny<string>())).Returns(packageRegistration);

                var nuGetPackage = new Mock<INupkg>();
                nuGetPackage.Setup(x => x.Metadata.Id).Returns("theId");
                nuGetPackage.Setup(x => x.Metadata.Version).Returns(new SemanticVersion("1.0.42"));
                controller.SetupPackageFromInputStream(nuGetPackage);

                // Act
                await controller.CreatePackagePut();

                // Assert
                controller.MockPackageFileService.Verify();
            }
 public PackageOwnerRequest GetPackageOwnershipRequest(PackageRegistration package, User pendingOwner, string token)
 {
     return(_packageOwnerRequestService.GetPackageOwnershipRequest(package, pendingOwner, token));
 }
 public IEnumerable <PackageOwnerRequest> GetPackageOwnershipRequests(PackageRegistration package = null, User requestingOwner = null, User newOwner = null)
 {
     return(_packageOwnerRequestService.GetPackageOwnershipRequests(package, requestingOwner, newOwner));
 }
Esempio n. 25
0
 protected virtual PackageAuditRecord CreateAuditRecord(Package package, PackageRegistration packageRegistration, AuditedPackageAction action, string reason)
 {
     return(new PackageAuditRecord(package, action, reason));
 }
Esempio n. 26
0
 public ManagePackageOwnerModel(PackageRegistration package, User user, User currentUser)
 {
     Package     = package;
     User        = user;
     CurrentUser = currentUser;
 }
Esempio n. 27
0
 private bool IsFirstPropagatingOwner(PackageRegistration package, User user)
 {
     return(RequireSecurePushForCoOwnersPolicy.IsSubscribed(user) &&
            !package.Owners.Any(RequireSecurePushForCoOwnersPolicy.IsSubscribed));
 }
Esempio n. 28
0
 protected override PackageAuditRecord CreateAuditRecord(Package package, PackageRegistration packageRegistration, AuditedPackageAction action, string reason)
 {
     LastAuditRecord = base.CreateAuditRecord(package, packageRegistration, action, reason);
     return(LastAuditRecord);
 }
Esempio n. 29
0
            public void CommitIfCommitChangesIsTrue()
            {
                // Arrange
                var packageRegistration = new PackageRegistration();
                var package = new Package { PackageRegistration = packageRegistration };
                var packageRepository = new Mock<IEntityRepository<Package>>();

                var service = CreateService(packageRepository: packageRepository, setup:
                        mockService => { mockService.Setup(x => x.FindPackageByIdAndVersion(It.IsAny<string>(), It.IsAny<string>(), true)).Returns(package); });

                // Act
                service.DeletePackage("hot", "1.0", commitChanges: true);

                // Assert
                packageRepository.Verify(r => r.CommitChanges(), Times.Once());
            }
Esempio n. 30
0
        private Package CreatePackageFromNuGetPackage(PackageRegistration packageRegistration, PackageArchiveReader nugetPackage, PackageMetadata packageMetadata, PackageStreamMetadata packageStreamMetadata, User user)
        {
            var package = packageRegistration.Packages.SingleOrDefault(pv => pv.Version == packageMetadata.Version.ToString());

            if (package != null)
            {
                throw new EntityException(
                          "A package with identifier '{0}' and version '{1}' already exists.", packageRegistration.Id, package.Version);
            }

            package = new Package
            {
                // Version must always be the exact string from the nuspec, which ToString will return to us.
                // However, we do also store a normalized copy for looking up later.
                Version           = packageMetadata.Version.ToString(),
                NormalizedVersion = packageMetadata.Version.ToNormalizedString(),

                Description               = packageMetadata.Description,
                ReleaseNotes              = packageMetadata.ReleaseNotes,
                HashAlgorithm             = packageStreamMetadata.HashAlgorithm,
                Hash                      = packageStreamMetadata.Hash,
                PackageFileSize           = packageStreamMetadata.Size,
                Language                  = packageMetadata.Language,
                Copyright                 = packageMetadata.Copyright,
                FlattenedAuthors          = packageMetadata.Authors.Flatten(),
                IsPrerelease              = packageMetadata.Version.IsPrerelease,
                Listed                    = true,
                PackageRegistration       = packageRegistration,
                RequiresLicenseAcceptance = packageMetadata.RequireLicenseAcceptance,
                Summary                   = packageMetadata.Summary,
                Tags                      = PackageHelper.ParseTags(packageMetadata.Tags),
                Title                     = packageMetadata.Title,
                User                      = user,
            };

            package.IconUrl          = packageMetadata.IconUrl.ToEncodedUrlStringOrNull();
            package.LicenseUrl       = packageMetadata.LicenseUrl.ToEncodedUrlStringOrNull();
            package.ProjectUrl       = packageMetadata.ProjectUrl.ToEncodedUrlStringOrNull();
            package.MinClientVersion = packageMetadata.MinClientVersion.ToStringOrNull();

#pragma warning disable 618 // TODO: remove Package.Authors completely once prodution services definitely no longer need it
            foreach (var author in packageMetadata.Authors)
            {
                package.Authors.Add(new PackageAuthor {
                    Name = author
                });
            }
#pragma warning restore 618

            var supportedFrameworks = GetSupportedFrameworks(nugetPackage).Select(fn => fn.ToShortNameOrNull()).ToArray();
            if (!supportedFrameworks.AnySafe(sf => sf == null))
            {
                ValidateSupportedFrameworks(supportedFrameworks);

                foreach (var supportedFramework in supportedFrameworks)
                {
                    package.SupportedFrameworks.Add(new PackageFramework {
                        TargetFramework = supportedFramework
                    });
                }
            }

            package.Dependencies = packageMetadata
                                   .GetDependencyGroups()
                                   .AsPackageDependencyEnumerable()
                                   .ToList();
            package.FlattenedDependencies = package.Dependencies.Flatten();

            return(package);
        }
Esempio n. 31
0
        private Package CreatePackageFromNuGetPackage(PackageRegistration packageRegistration, INupkg nugetPackage)
        {
            var package = packageRegistration.Packages.SingleOrDefault(pv => pv.Version == nugetPackage.Metadata.Version.ToString());

            if (package != null)
            {
                throw new EntityException(
                          "A package with identifier '{0}' and version '{1}' already exists.", packageRegistration.Id, package.Version);
            }

            var now = DateTime.UtcNow;
            var packageFileStream = nugetPackage.GetStream();

            package = new Package
            {
                Version      = nugetPackage.Metadata.Version.ToString(),
                Description  = nugetPackage.Metadata.Description,
                ReleaseNotes = nugetPackage.Metadata.ReleaseNotes,
                RequiresLicenseAcceptance = nugetPackage.Metadata.RequireLicenseAcceptance,
                HashAlgorithm             = Constants.Sha512HashAlgorithmId,
                Hash                = _cryptoService.GenerateHash(packageFileStream.ReadAllBytes()),
                PackageFileSize     = packageFileStream.Length,
                Created             = now,
                Language            = nugetPackage.Metadata.Language,
                LastUpdated         = now,
                Published           = now,
                Copyright           = nugetPackage.Metadata.Copyright,
                IsPrerelease        = !nugetPackage.Metadata.IsReleaseVersion(),
                Listed              = true,
                PackageRegistration = packageRegistration,
                Summary             = nugetPackage.Metadata.Summary,
                Tags                = nugetPackage.Metadata.Tags,
                Title               = nugetPackage.Metadata.Title,
            };

            package.IconUrl          = nugetPackage.Metadata.IconUrl.ToStringOrNull();
            package.LicenseUrl       = nugetPackage.Metadata.LicenseUrl.ToStringOrNull();
            package.ProjectUrl       = nugetPackage.Metadata.ProjectUrl.ToStringOrNull();
            package.MinClientVersion = nugetPackage.Metadata.MinClientVersion.ToStringOrNull();

            foreach (var author in nugetPackage.Metadata.Authors)
            {
                package.Authors.Add(new PackageAuthor {
                    Name = author
                });
            }

            var supportedFrameworks = GetSupportedFrameworks(nugetPackage).Select(fn => fn.ToShortNameOrNull()).ToArray();

            if (!supportedFrameworks.AnySafe(sf => sf == null))
            {
                foreach (var supportedFramework in supportedFrameworks)
                {
                    package.SupportedFrameworks.Add(new PackageFramework {
                        TargetFramework = supportedFramework
                    });
                }
            }

            foreach (var dependencySet in nugetPackage.Metadata.DependencySets)
            {
                if (dependencySet.Dependencies.Count == 0)
                {
                    package.Dependencies.Add(
                        new PackageDependency
                    {
                        Id              = null,
                        VersionSpec     = null,
                        TargetFramework = dependencySet.TargetFramework.ToShortNameOrNull()
                    });
                }
                else
                {
                    foreach (var dependency in dependencySet.Dependencies.Select(d => new { d.Id, d.VersionSpec, dependencySet.TargetFramework }))
                    {
                        package.Dependencies.Add(
                            new PackageDependency
                        {
                            Id              = dependency.Id,
                            VersionSpec     = dependency.VersionSpec == null ? null : dependency.VersionSpec.ToString(),
                            TargetFramework = dependency.TargetFramework.ToShortNameOrNull()
                        });
                    }
                }
            }

            package.FlattenedAuthors      = package.Authors.Flatten();
            package.FlattenedDependencies = package.Dependencies.Flatten();

            return(package);
        }
        public void SendPackageOwnerRequestCancellationNotice(User requestingOwner, User newOwner, PackageRegistration package)
        {
            var subject = string.Format(CultureInfo.CurrentCulture, $"[{Config.GalleryOwner.DisplayName}] Package ownership request for '{package.Id}' cancelled");

            var body = string.Format(CultureInfo.CurrentCulture, $@"The user '{requestingOwner.Username}' has cancelled their request for {(newOwner is Organization ? "your organization" : "you")} to be added as an owner of the package '{package.Id}'.

Thanks,
The {Config.GalleryOwner.DisplayName} Team");

            using (var mailMessage = new MailMessage())
            {
                mailMessage.Subject = subject;
                mailMessage.Body    = body;
                mailMessage.From    = Config.GalleryNoReplyAddress;
                mailMessage.ReplyToList.Add(requestingOwner.ToMailAddress());

                if (!AddAddressesForPackageOwnershipManagementToEmail(mailMessage, newOwner))
                {
                    return;
                }

                SendMessage(mailMessage);
            }
        }
        public void SendPackageOwnerRequestInitiatedNotice(User requestingOwner, User receivingOwner, User newOwner, PackageRegistration package, string cancellationUrl)
        {
            var subject = string.Format(CultureInfo.CurrentCulture, $"[{Config.GalleryOwner.DisplayName}] Package ownership request for '{package.Id}'");

            var body = string.Format(CultureInfo.CurrentCulture, $@"The user '{requestingOwner.Username}' has requested that user '{newOwner.Username}' be added as an owner of the package '{package.Id}'.

To cancel this request:

[{cancellationUrl}]({cancellationUrl})

Thanks,
The {Config.GalleryOwner.DisplayName} Team");

            using (var mailMessage = new MailMessage())
            {
                mailMessage.Subject = subject;
                mailMessage.Body    = body;
                mailMessage.From    = Config.GalleryNoReplyAddress;
                mailMessage.ReplyToList.Add(newOwner.ToMailAddress());

                if (!AddAddressesForPackageOwnershipManagementToEmail(mailMessage, receivingOwner))
                {
                    return;
                }

                SendMessage(mailMessage);
            }
        }
Esempio n. 34
0
 protected virtual PackageAuditRecord CreateAuditRecord(Package package, PackageRegistration packageRegistration, PackageAuditAction action, string reason)
 {
     return(new PackageAuditRecord(package, ConvertToDataTable(package), ConvertToDataTable(packageRegistration), action, reason));
 }
Esempio n. 35
0
 public async Task AddPackageOwnerAsync(PackageRegistration package, User newOwner)
 {
     package.Owners.Add(newOwner);
     await _packageRepository.CommitChangesAsync();
 }
Esempio n. 36
0
            private void WillSaveTheCreatedPackageWhenThePackageRegistrationAlreadyExisted()
            {
                var currentUser = new User();
                var packageRegistration = new PackageRegistration
                    {
                        Id = "theId",
                        Owners = new HashSet<User> { currentUser },
                    };
                var packageRegistrationRepository = new Mock<IEntityRepository<PackageRegistration>>();
                var service = CreateService(packageRegistrationRepository: packageRegistrationRepository, setup:
                        mockPackageService => { mockPackageService.Setup(x => x.FindPackageRegistrationById(It.IsAny<string>())).Returns(packageRegistration); });
                var nugetPackage = CreateNuGetPackage();

                var package = service.CreatePackage(nugetPackage.Object, currentUser);

                Assert.Same(packageRegistration.Packages.ElementAt(0), package);
                packageRegistrationRepository.Verify(x => x.CommitChanges());
            }
Esempio n. 37
0
            public void CreatesPackageOwnerRequest()
            {
                var packageOwnerRequestRepository = new Mock<IEntityRepository<PackageOwnerRequest>>();
                var service = CreateService(packageOwnerRequestRepo: packageOwnerRequestRepository);
                var package = new PackageRegistration { Key = 1 };
                var owner = new User { Key = 100 };
                var newOwner = new User { Key = 200 };

                service.CreatePackageOwnerRequest(package, owner, newOwner);

                packageOwnerRequestRepository.Verify(
                    r => r.InsertOnCommit(
                        It.Is<PackageOwnerRequest>(req => req.PackageRegistrationKey == 1 && req.RequestingOwnerKey == 100 && req.NewOwnerKey == 200))
                    );
            }
Esempio n. 38
0
 public bool WillPackageBeOrphanedIfOwnerRemoved(PackageRegistration package, User ownerToRemove)
 {
     return(WillPackageBeOrphanedIfOwnerRemovedHelper(package.Owners, ownerToRemove));
 }
Esempio n. 39
0
            public void WillNotDeleteThePackageRegistrationIfThereAreOtherPackages()
            {
                var packageRegistration = new PackageRegistration { Packages = new HashSet<Package>() };
                var package = new Package { PackageRegistration = packageRegistration, Version = "1.0" };
                packageRegistration.Packages.Add(package);
                packageRegistration.Packages.Add(new Package { Version = "0.9" });
                var packageRegistrationRepository = new Mock<IEntityRepository<PackageRegistration>>();
                var packageRepository = new Mock<IEntityRepository<Package>>(MockBehavior.Strict);
                packageRepository.Setup(r => r.DeleteOnCommit(package)).Callback(() => { packageRegistration.Packages.Remove(package); });
                packageRepository.Setup(r => r.CommitChanges()).Verifiable();
                var service = CreateService(packageRegistrationRepository: packageRegistrationRepository, packageRepository: packageRepository, setup:
                        mockService => { mockService.Setup(x => x.FindPackageByIdAndVersion(It.IsAny<string>(), It.IsAny<string>(), true)).Returns(package); });

                service.DeletePackage("theId", "1.0.42");

                packageRegistrationRepository.Verify(x => x.DeleteOnCommit(packageRegistration), Times.Never());
            }
 public PackageHeadingModel(User currentUser, PackageRegistration packageRegistration, string pageHeading)
     : this(packageRegistration.Id, pageHeading)
 {
     ShowProfileBreadcrumb =
         ActionsRequiringPermissions.ShowProfileBreadcrumb.CheckPermissionsOnBehalfOfAnyAccount(currentUser, packageRegistration) == PermissionsCheckResult.Allowed;
 }
Esempio n. 41
0
 public static string Package(this UrlHelper url, PackageRegistration package)
 {
     return(url.Package(package.Id));
 }
Esempio n. 42
0
        Package CreatePackageFromNuGetPackage(PackageRegistration packageRegistration, IPackage nugetPackage)
        {
            var package = packageRegistration.Packages
                          .Where(pv => pv.Version == nugetPackage.Version.ToString())
                          .SingleOrDefault();

            if (package != null)
            {
                throw new EntityException("A package with identifier '{0}' and version '{1}' already exists.", packageRegistration.Id, package.Version);
            }

            // TODO: add flattened authors, and other properties
            // TODO: add package size
            var now = DateTime.UtcNow;
            var packageFileStream = nugetPackage.GetStream();

            package = new Package
            {
                Version      = nugetPackage.Version.ToString(),
                Description  = nugetPackage.Description,
                ReleaseNotes = nugetPackage.ReleaseNotes,
                RequiresLicenseAcceptance = nugetPackage.RequireLicenseAcceptance,
                HashAlgorithm             = Constants.Sha512HashAlgorithmId,
                Hash            = cryptoSvc.GenerateHash(packageFileStream.ReadAllBytes()),
                PackageFileSize = packageFileStream.Length,
                Created         = now,
                LastUpdated     = now,
                Published       = DateTime.UtcNow,
                Copyright       = nugetPackage.Copyright,
                IsPrerelease    = !nugetPackage.IsReleaseVersion(),
                Listed          = true
            };

            if (nugetPackage.IconUrl != null)
            {
                package.IconUrl = nugetPackage.IconUrl.ToString();
            }
            if (nugetPackage.LicenseUrl != null)
            {
                package.LicenseUrl = nugetPackage.LicenseUrl.ToString();
            }
            if (nugetPackage.ProjectUrl != null)
            {
                package.ProjectUrl = nugetPackage.ProjectUrl.ToString();
            }
            if (nugetPackage.Summary != null)
            {
                package.Summary = nugetPackage.Summary;
            }
            if (nugetPackage.Tags != null)
            {
                package.Tags = nugetPackage.Tags;
            }
            if (nugetPackage.Title != null)
            {
                package.Title = nugetPackage.Title;
            }

            foreach (var author in nugetPackage.Authors)
            {
                package.Authors.Add(new PackageAuthor {
                    Name = author
                });
            }

            foreach (var dependency in nugetPackage.Dependencies)
            {
                package.Dependencies.Add(new PackageDependency {
                    Id = dependency.Id, VersionSpec = dependency.VersionSpec.ToStringSafe()
                });
            }

            package.FlattenedAuthors      = package.Authors.Flatten();
            package.FlattenedDependencies = package.Dependencies.Flatten();

            return(package);
        }
Esempio n. 43
0
 private IEnumerable <string> GetPropagatingOwners(PackageRegistration package)
 {
     return(package.Owners.Where(RequireSecurePushForCoOwnersPolicy.IsSubscribed).Select(o => o.Username));
 }
Esempio n. 44
0
 private PackageOwnerRequest FindExistingPackageOwnerRequest(PackageRegistration package, User pendingOwner)
 {
     return((from request in packageOwnerRequestRepository.GetAll()
             where request.PackageRegistrationKey == package.Key && request.NewOwnerKey == pendingOwner.Key
             select request).FirstOrDefault());
 }
        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", versionConstraints: null)
                         .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]);
        }
Esempio n. 46
0
        /// <summary>
        /// This method fetches the reserved namespace matching the prefix and removes the
        /// package registration entry from the reserved namespace, the provided package registration
        /// should be an entry in the database. It is the caller's responsibility to commit the
        /// changes to the entity context.
        /// </summary>
        /// <param name="prefix">The prefix value of the reserved namespace to modify</param>
        /// <param name="packageRegistration">The package registration entity to be removed.</param>
        /// <returns>Awaitable task</returns>
        public void RemovePackageRegistrationFromNamespace(ReservedNamespace reservedNamespace, PackageRegistration packageRegistration)
        {
            if (reservedNamespace == null)
            {
                throw new ArgumentNullException(nameof(reservedNamespace));
            }

            if (packageRegistration == null)
            {
                throw new ArgumentNullException(nameof(packageRegistration));
            }

            reservedNamespace.PackageRegistrations.Remove(packageRegistration);
            packageRegistration.ReservedNamespaces.Remove(reservedNamespace);
        }
Esempio n. 47
0
        Package CreatePackageFromNuGetPackage(PackageRegistration packageRegistration, IPackage nugetPackage)
        {
            var package = packageRegistration.Packages
                          .Where(pv => pv.Version == nugetPackage.Version.ToString())
                          .SingleOrDefault();

            if (package != null)
            {
                throw new EntityException("A package with identifier '{0}' and version '{1}' already exists.", packageRegistration.Id, package.Version);
            }

            var now = DateTime.UtcNow;
            var packageFileStream = nugetPackage.GetStream();

            package = new Package
            {
                Version      = nugetPackage.Version.ToString(),
                Description  = nugetPackage.Description,
                ReleaseNotes = nugetPackage.ReleaseNotes,
                RequiresLicenseAcceptance = nugetPackage.RequireLicenseAcceptance,
                HashAlgorithm             = Constants.Sha512HashAlgorithmId,
                Hash            = cryptoSvc.GenerateHash(packageFileStream.ReadAllBytes()),
                PackageFileSize = packageFileStream.Length,
                Created         = now,
                Language        = nugetPackage.Language,
                LastUpdated     = now,
                Published       = now,
                Copyright       = nugetPackage.Copyright,
                IsPrerelease    = !nugetPackage.IsReleaseVersion(),
                Listed          = true,
            };

            if (nugetPackage.IconUrl != null)
            {
                package.IconUrl = nugetPackage.IconUrl.ToString();
            }
            if (nugetPackage.LicenseUrl != null)
            {
                package.LicenseUrl = nugetPackage.LicenseUrl.ToString();
            }
            if (nugetPackage.ProjectUrl != null)
            {
                package.ProjectUrl = nugetPackage.ProjectUrl.ToString();
            }
            if (nugetPackage.Summary != null)
            {
                package.Summary = nugetPackage.Summary;
            }
            if (nugetPackage.Tags != null)
            {
                package.Tags = nugetPackage.Tags;
            }
            if (nugetPackage.Title != null)
            {
                package.Title = nugetPackage.Title;
            }

            foreach (var author in nugetPackage.Authors)
            {
                package.Authors.Add(new PackageAuthor {
                    Name = author
                });
            }

            var supportedFrameworks = GetSupportedFrameworks(nugetPackage).Select(fn => fn.ToShortNameOrNull()).ToArray();

            if (!supportedFrameworks.AnySafe(sf => sf == null))
            {
                foreach (var supportedFramework in supportedFrameworks)
                {
                    package.SupportedFrameworks.Add(new PackageFramework {
                        TargetFramework = supportedFramework
                    });
                }
            }

            foreach (var dependencySet in nugetPackage.DependencySets)
            {
                if (dependencySet.Dependencies.Count == 0)
                {
                    package.Dependencies.Add(new PackageDependency
                    {
                        Id              = null,
                        VersionSpec     = null,
                        TargetFramework = dependencySet.TargetFramework.ToShortNameOrNull()
                    });
                }
                else
                {
                    foreach (var dependency in dependencySet.Dependencies.Select(d => new { d.Id, d.VersionSpec, dependencySet.TargetFramework }))
                    {
                        package.Dependencies.Add(new PackageDependency
                        {
                            Id              = dependency.Id,
                            VersionSpec     = dependency.VersionSpec == null ? null : dependency.VersionSpec.ToString(),
                            TargetFramework = dependency.TargetFramework.ToShortNameOrNull()
                        });
                    }
                }
            }

            foreach (var packageFile in nugetPackage.GetFiles().OrEmptyListIfNull())
            {
                var filePath    = packageFile.Path;
                var fileContent = " ";

                IList <string> extensions         = new List <string>();
                var            approvedExtensions = Configuration.ReadAppSettings("PackageFileTextExtensions");
                if (!string.IsNullOrWhiteSpace(approvedExtensions))
                {
                    foreach (var extension in approvedExtensions.Split(',', ';'))
                    {
                        extensions.Add("." + extension);
                    }
                }

                try
                {
                    if (extensions.Contains(Path.GetExtension(filePath)))
                    {
                        fileContent = packageFile.GetStream().ReadToEnd();
                    }
                }
                catch (Exception ex)
                {
                    // Log but swallow the exception
                    Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                }

                package.Files.Add(new PackageFile
                {
                    FilePath    = filePath,
                    FileContent = fileContent,
                });
            }

            package.FlattenedAuthors      = package.Authors.Flatten();
            package.FlattenedDependencies = package.Dependencies.Flatten();

            return(package);
        }
 /// <summary>
 /// Is <paramref name="currentPrincipal"/> allowed to perform an action with a requirement of <paramref name="permissionsRequirement"/> on <paramref name="packageRegistration"/>?
 /// </summary>
 public static bool IsRequirementSatisfied(PermissionsRequirement permissionsRequirement, IPrincipal currentPrincipal, PackageRegistration packageRegistration)
 {
     return(IsRequirementSatisfied(permissionsRequirement, currentPrincipal, packageRegistration.Owners));
 }
 /// <summary>
 /// Is <paramref name="currentUser"/> allowed to perform an action with a requirement of <paramref name="permissionsRequirement"/> on <paramref name="packageRegistration"/>?
 /// </summary>
 public static bool IsRequirementSatisfied(PermissionsRequirement permissionsRequirement, User currentUser, PackageRegistration packageRegistration)
 {
     return(IsRequirementSatisfied(permissionsRequirement, currentUser, packageRegistration.Owners));
 }
        public virtual async Task UpdateIsLatestAsync(PackageRegistration packageRegistration, bool commitChanges = true)
        {
            if (!packageRegistration.Packages.Any())
            {
                return;
            }

            // TODO: improve setting the latest bit; this is horrible. Trigger maybe?
            var currentUtcTime = DateTime.UtcNow;

            foreach (var pv in packageRegistration.Packages.Where(p => p.IsLatest || p.IsLatestStable || p.IsLatestSemVer2 || p.IsLatestStableSemVer2))
            {
                pv.IsLatest              = false;
                pv.IsLatestStable        = false;
                pv.IsLatestSemVer2       = false;
                pv.IsLatestStableSemVer2 = false;
                pv.LastUpdated           = currentUtcTime;
            }

            // If the last listed package was just unlisted, then we won't find another one
            var latestPackage = FindPackage(
                packageRegistration.Packages.AsQueryable(),
                ps => ps
                .Where(SemVerLevelKey.IsUnknownPredicate())
                .Where(p => p.PackageStatusKey == PackageStatus.Available && p.Listed));

            var latestSemVer2Package = FindPackage(
                packageRegistration.Packages.AsQueryable(),
                ps => ps
                .Where(SemVerLevelKey.IsSemVer2Predicate())
                .Where(p => p.PackageStatusKey == PackageStatus.Available && p.Listed));

            if (latestPackage != null)
            {
                latestPackage.IsLatest    = true;
                latestPackage.LastUpdated = currentUtcTime;

                if (latestPackage.IsPrerelease)
                {
                    // If the newest uploaded package is a prerelease package, we need to find an older package that is
                    // a release version and set it to IsLatest.
                    var latestReleasePackage = FindPackage(packageRegistration
                                                           .Packages
                                                           .AsQueryable()
                                                           .Where(SemVerLevelKey.IsUnknownPredicate())
                                                           .Where(p => !p.IsPrerelease && p.PackageStatusKey == PackageStatus.Available && p.Listed));

                    if (latestReleasePackage != null)
                    {
                        // We could have no release packages
                        latestReleasePackage.IsLatestStable = true;
                        latestReleasePackage.LastUpdated    = currentUtcTime;
                    }
                }
                else
                {
                    // Only release versions are marked as IsLatestStable.
                    latestPackage.IsLatestStable = true;
                }
            }

            if (latestSemVer2Package != null)
            {
                latestSemVer2Package.IsLatestSemVer2 = true;
                latestSemVer2Package.LastUpdated     = currentUtcTime;

                if (latestSemVer2Package.IsPrerelease)
                {
                    // If the newest uploaded package is a prerelease package, we need to find an older package that is
                    // a release version and set it to IsLatest.
                    var latestSemVer2ReleasePackage = FindPackage(packageRegistration
                                                                  .Packages
                                                                  .AsQueryable()
                                                                  .Where(SemVerLevelKey.IsSemVer2Predicate())
                                                                  .Where(p => !p.IsPrerelease && p.PackageStatusKey == PackageStatus.Available && p.Listed));

                    if (latestSemVer2ReleasePackage != null)
                    {
                        // We could have no release packages
                        latestSemVer2ReleasePackage.IsLatestStableSemVer2 = true;
                        latestSemVer2ReleasePackage.LastUpdated           = currentUtcTime;
                    }
                }
                else
                {
                    // Only release versions are marked as IsLatestStable.
                    latestSemVer2Package.IsLatestStableSemVer2 = true;
                }
            }

            if (commitChanges)
            {
                await _packageRepository.CommitChangesAsync();
            }
        }
 public async Task <PackageOwnerRequest> AddPackageOwnershipRequestAsync(PackageRegistration packageRegistration, User requestingOwner, User newOwner)
 {
     return(await _packageOwnerRequestService.AddPackageOwnershipRequest(packageRegistration, requestingOwner, newOwner));
 }
Esempio n. 52
0
        public void SendPackageOwnerRequestCancellationNotice(User requestingOwner, User newOwner, PackageRegistration package)
        {
            if (!newOwner.EmailAllowed)
            {
                return;
            }

            var subject = string.Format(CultureInfo.CurrentCulture, $"[{Config.GalleryOwner.DisplayName}] The user '{requestingOwner.Username}' has cancelled their request for you to be added as an owner of the package '{package.Id}'.");

            var body = string.Format(CultureInfo.CurrentCulture, $@"The user '{requestingOwner.Username}' has cancelled their request for you to be added as an owner of the package '{package.Id}'.

Thanks,
The {Config.GalleryOwner.DisplayName} Team");

            using (var mailMessage = new MailMessage())
            {
                mailMessage.Subject = subject;
                mailMessage.Body    = body;
                mailMessage.From    = Config.GalleryNoReplyAddress;
                mailMessage.ReplyToList.Add(requestingOwner.ToMailAddress());

                mailMessage.To.Add(newOwner.ToMailAddress());
                SendMessage(mailMessage);
            }
        }
Esempio n. 53
0
            private void WillThrowIfThePackageRegistrationAlreadyExistsAndTheCurrentUserIsNotAnOwner()
            {
                var currentUser = new User();
                var packageRegistration = new PackageRegistration
                    {
                        Id = "theId",
                        Owners = new HashSet<User>()
                    };
                var packageRegistrationRepository = new Mock<IEntityRepository<PackageRegistration>>();
                var service = CreateService(packageRegistrationRepository: packageRegistrationRepository, setup:
                        mockPackageService => { mockPackageService.Setup(x => x.FindPackageRegistrationById(It.IsAny<string>())).Returns(packageRegistration); });
                var nugetPackage = CreateNuGetPackage();

                var ex = Assert.Throws<EntityException>(() => service.CreatePackage(nugetPackage.Object, currentUser, true));

                Assert.Equal(String.Format(Strings.PackageIdNotAvailable, "theId"), ex.Message);
            }
Esempio n. 54
0
 private ApiScopeEvaluationResult EvaluateApiScope(IActionRequiringEntityPermissions <PackageRegistration> action, PackageRegistration packageRegistration, params string[] requestedActions)
 {
     return(ApiScopeEvaluator.Evaluate(
                GetCurrentUser(),
                User.Identity.GetScopesFromClaim(),
                action,
                packageRegistration,
                requestedActions));
 }
Esempio n. 55
0
            public void ReturnsExistingMatchingPackageOwnerRequest()
            {
                var packageOwnerRequestRepository = new Mock<IEntityRepository<PackageOwnerRequest>>();
                packageOwnerRequestRepository.Setup(r => r.GetAll()).Returns(
                    new[]
                        {
                            new PackageOwnerRequest
                                {
                                    PackageRegistrationKey = 1,
                                    RequestingOwnerKey = 99,
                                    NewOwnerKey = 200
                                }
                        }.AsQueryable());
                var service = CreateService(packageOwnerRequestRepo: packageOwnerRequestRepository);
                var package = new PackageRegistration { Key = 1 };
                var owner = new User { Key = 100 };
                var newOwner = new User { Key = 200 };

                var request = service.CreatePackageOwnerRequest(package, owner, newOwner);

                Assert.Equal(99, request.RequestingOwnerKey);
            }
Esempio n. 56
0
        private async Task <PackageValidationResult> ValidateSignatureFilePresenceAsync(
            PackageRegistration packageRegistration,
            PackageArchiveReader nugetPackage,
            User owner,
            User currentUser)
        {
            if (await nugetPackage.IsSignedAsync(CancellationToken.None))
            {
                if (_config.RejectSignedPackagesWithNoRegisteredCertificate &&
                    !packageRegistration.IsSigningAllowed())
                {
                    var requiredSigner    = packageRegistration.RequiredSigners.FirstOrDefault();
                    var hasRequiredSigner = requiredSigner != null;

                    if (hasRequiredSigner)
                    {
                        if (requiredSigner == currentUser)
                        {
                            return(PackageValidationResult.Invalid(new PackageShouldNotBeSignedUserFixableValidationMessage()));
                        }
                        else
                        {
                            return(PackageValidationResult.Invalid(
                                       string.Format(
                                           Strings.UploadPackage_PackageIsSignedButMissingCertificate_RequiredSigner,
                                           requiredSigner.Username)));
                        }
                    }
                    else
                    {
                        var isCurrentUserAnOwner = packageRegistration.Owners.Contains(currentUser);

                        // Technically, if there is no required signer, any one of the owners can register a
                        // certificate to resolve this issue. However, we favor either the current user or the provided
                        // owner since these are both accounts the current user can push on behalf of. In other words
                        // we provide a message that leads the current user to remedying the problem rather than asking
                        // someone else for help.
                        if (isCurrentUserAnOwner)
                        {
                            return(PackageValidationResult.Invalid(new PackageShouldNotBeSignedUserFixableValidationMessage()));
                        }
                        else
                        {
                            return(PackageValidationResult.Invalid(
                                       string.Format(
                                           Strings.UploadPackage_PackageIsSignedButMissingCertificate_RequiredSigner,
                                           owner.Username)));
                        }
                    }
                }
            }
            else
            {
                if (packageRegistration.IsSigningRequired())
                {
                    return(PackageValidationResult.Invalid(Strings.UploadPackage_PackageIsNotSigned));
                }
            }

            return(null);
        }
Esempio n. 57
0
            public void WillDeleteThePackage()
            {
                var packageRegistration = new PackageRegistration();
                var package = new Package { PackageRegistration = packageRegistration };
                var packageRepository = new Mock<IEntityRepository<Package>>();
                var service = CreateService(packageRepository: packageRepository, setup:
                        mockService => { mockService.Setup(x => x.FindPackageByIdAndVersion(It.IsAny<string>(), It.IsAny<string>(), true)).Returns(package); });

                service.DeletePackage("theId", "1.0.42");

                packageRepository.Verify(x => x.DeleteOnCommit(package));
                packageRepository.Verify(x => x.CommitChanges());
            }
Esempio n. 58
0
 public static string Package(this UrlHelper url, PackageRegistration package, bool relativeUrl = true)
 {
     return(url.Package(package.Id, relativeUrl));
 }
Esempio n. 59
0
            public void WillUpdateIsLatest()
            {
                // Arrange
                var packages = new HashSet<Package>();
                var packageRegistration = new PackageRegistration { Packages = packages };
                var package100 = new Package { PackageRegistration = packageRegistration, Version = "1.0.0" };
                packages.Add(package100);
                var package10A = new Package { PackageRegistration = packageRegistration, Version = "1.0.0-a", IsPrerelease = true };
                packages.Add(package10A);
                var package09 = new Package { PackageRegistration = packageRegistration, Version = "0.9.0" };
                packages.Add(package09);
                var packageRepository = new Mock<IEntityRepository<Package>>(MockBehavior.Strict);
                packageRepository.Setup(r => r.DeleteOnCommit(package100)).Callback(() => { packages.Remove(package100); }).Verifiable();
                packageRepository.Setup(r => r.CommitChanges()).Verifiable();
                var service = CreateService(packageRepository: packageRepository, setup:
                        mockService => { mockService.Setup(x => x.FindPackageByIdAndVersion(It.IsAny<string>(), It.IsAny<string>(), true)).Returns(package100); });

                // Act
                service.DeletePackage("A", "1.0.0");

                // Assert
                Assert.True(package10A.IsLatest);
                Assert.False(package10A.IsLatestStable);
                Assert.False(package09.IsLatest);
                Assert.True(package09.IsLatestStable);
                packageRepository.Verify();
            }
Esempio n. 60
0
 public async Task RemovePackageOwnerAsync(PackageRegistration package, User user)
 {
     // To support the delete account scenario, the admin can delete the last owner of a package.
     package.Owners.Remove(user);
     await _packageRepository.CommitChangesAsync();
 }