Пример #1
0
        public virtual ActionResult VerifyPackage(bool? listed)
        {
            var currentUser = userSvc.FindByUsername(GetIdentity().Name);

            IPackage nugetPackage;
            using (var uploadFile = uploadFileSvc.GetUploadFile(currentUser.Key))
            {
                if (uploadFile == null) return HttpNotFound();
                nugetPackage = ReadNuGetPackage(uploadFile);
            }

            Package package;
            using (var tx = new TransactionScope())
            {
                package = packageSvc.CreatePackage(nugetPackage, currentUser);
                packageSvc.PublishPackage(package.PackageRegistration.Id, package.Version);
                if (listed.HasValue && listed.Value == false) packageSvc.MarkPackageUnlisted(package);
                uploadFileSvc.DeleteUploadFile(currentUser.Key);
                autoCuratedPackageCmd.Execute(package, nugetPackage);
                tx.Complete();
            }

            TempData["Message"] = string.Format(
                "You have successfully created '{0}' version '{1}'. The package is now under review by the moderators and will show up once approved.", package.PackageRegistration.Id, package.Version);
            return RedirectToRoute(
                RouteName.DisplayPackage, new
                {
                    package.PackageRegistration.Id,
                    package.Version
                });
        }
        private ActionResult CreatePackageInternal(Guid apiKey)
        {
            var user = userSvc.FindByApiKey(apiKey);

            if (user == null)
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Forbidden, String.Format(CultureInfo.CurrentCulture, Strings.ApiKeyNotAuthorized, "push")));
            }

            var packageToPush = ReadPackageFromRequest();

            // Ensure that the user can push packages for this id.
            var packageRegistration = packageSvc.FindPackageRegistrationById(packageToPush.Id);

            if (packageRegistration != null)
            {
                if (!packageRegistration.IsOwner(user))
                {
                    return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Forbidden, String.Format(CultureInfo.CurrentCulture, Strings.ApiKeyNotAuthorized, "push")));
                }

                // Check if a particular Id-Version combination already exists. We eventually need to remove this check.
                bool packageExists = packageRegistration.Packages.Any(p => p.Version.Equals(packageToPush.Version.ToString(), StringComparison.OrdinalIgnoreCase));
                if (packageExists)
                {
                    return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Conflict,
                                                            String.Format(CultureInfo.CurrentCulture, Strings.PackageExistsAndCannotBeModified, packageToPush.Id, packageToPush.Version.ToString())));
                }
            }

            packageSvc.CreatePackage(packageToPush, user);
            return(new HttpStatusCodeResult(201));
        }
Пример #3
0
        public virtual ActionResult VerifyPackage(bool?listed)
        {
            var currentUser = userSvc.FindByUsername(GetIdentity().Name);

            IPackage nugetPackage;

            using (var uploadFile = uploadFileSvc.GetUploadFile(currentUser.Key))
            {
                if (uploadFile == null)
                {
                    return(HttpNotFound());
                }

                nugetPackage = ReadNuGetPackage(uploadFile);
            }

            Package package;

            using (var tx = new TransactionScope())
            {
                package = packageSvc.CreatePackage(nugetPackage, currentUser);
                packageSvc.PublishPackage(package.PackageRegistration.Id, package.Version);
                if (listed.HasValue && listed.Value == false)
                {
                    packageSvc.MarkPackageUnlisted(package);
                }
                uploadFileSvc.DeleteUploadFile(currentUser.Key);
                tx.Complete();
            }

            TempData["Message"] = String.Format(Strings.SuccessfullyUploadedPackage, package.PackageRegistration.Id, package.Version);
            return(RedirectToRoute(RouteName.DisplayPackage, new { package.PackageRegistration.Id, package.Version }));
        }
Пример #4
0
        private ActionResult CreatePackageInternal(string apiKey)
        {
            Guid parsedApiKey;

            if (!Guid.TryParse(apiKey, out parsedApiKey))
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, string.Format(CultureInfo.CurrentCulture, Strings.InvalidApiKey, apiKey)));
            }

            var user = userSvc.FindByApiKey(parsedApiKey);

            if (user == null)
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Forbidden, String.Format(CultureInfo.CurrentCulture, Strings.ApiKeyNotAuthorized, "push")));
            }

            var packageToPush = ReadPackageFromRequest();

            // Ensure that the user can push packages for this partialId.
            var packageRegistration = packageSvc.FindPackageRegistrationById(packageToPush.Id, useCache: false);

            if (packageRegistration != null)
            {
                if (!packageRegistration.IsOwner(user))
                {
                    return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Forbidden, String.Format(CultureInfo.CurrentCulture, Strings.ApiKeyNotAuthorized, "push")));
                }

                var existingPackage = packageRegistration.Packages.FirstOrDefault(p => p.Version.Equals(packageToPush.Version.ToString(), StringComparison.OrdinalIgnoreCase));

                if (existingPackage != null)
                {
                    switch (existingPackage.Status)
                    {
                    case PackageStatusType.Rejected:
                        return(new HttpStatusCodeWithBodyResult(
                                   HttpStatusCode.Conflict, string.Format("This package has been {0} and can no longer be submitted.", existingPackage.Status.GetDescriptionOrValue().ToLower())));

                    case PackageStatusType.Submitted:
                        //continue on
                        break;

                    default:
                        return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Conflict, String.Format(CultureInfo.CurrentCulture, Strings.PackageExistsAndCannotBeModified, packageToPush.Id, packageToPush.Version)));
                    }
                }
            }

            try
            {
                packageSvc.CreatePackage(packageToPush, user);
            }
            catch (Exception ex)
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Conflict, string.Format("This package had an issue pushing: {0}", ex.Message)));
            }

            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Created, "Package has been pushed and will show up once moderated and approved."));
        }
Пример #5
0
        public async Task <ActionResult <Package> > Create(Package entity)
        {
            var name = HttpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;

            entity.User = await _userManager.FindByNameAsync(name);

            return(await _service.CreatePackage(entity));
        }
Пример #6
0
        public IActionResult Create([FromBody] CreatePackageOptions options)
        {
            var pack = packageService_.CreatePackage(options);

            if (!pack.Success)
            {
                return(StatusCode((int)pack.ErrorCode, pack.ErrorText));
            }

            return(Json(pack));
        }
Пример #7
0
        public IActionResult Create([FromBody] CreatePackageOptions options)
        {
            var result = packageService.CreatePackage(options);

            if (!result.Success)
            {
                return(StatusCode((int)result.ErrorCode, result.ErrorText));
            }

            return(Ok());
        }
Пример #8
0
        public ActionResult CreatePackage([FromBody] PackageModel packageModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid Request"));
            }



            return(Ok(_packageService.CreatePackage(packageModel))); // Was created
        }
Пример #9
0
        public virtual async Task <ActionResult> VerifyPackage(bool?listed)
        {
            var currentUser = _userService.FindByUsername(GetIdentity().Name);

            Package package;

            using (Stream uploadFile = await _uploadFileService.GetUploadFileAsync(currentUser.Key))
            {
                if (uploadFile == null)
                {
                    return(HttpNotFound());
                }

                INupkg nugetPackage = CreatePackage(uploadFile);

                // update relevant database tables
                package = _packageService.CreatePackage(nugetPackage, currentUser, commitChanges: false);
                Debug.Assert(package.PackageRegistration != null);

                _packageService.PublishPackage(package, commitChanges: false);

                if (listed == false)
                {
                    _packageService.MarkPackageUnlisted(package, commitChanges: false);
                }

                _autoCuratedPackageCmd.Execute(package, nugetPackage, commitChanges: false);

                // save package to blob storage
                uploadFile.Position = 0;
                await _packageFileService.SavePackageFileAsync(package, uploadFile);

                // commit all changes to database as an atomic transaction
                _entitiesContext.SaveChanges();

                // tell Lucene to update index for the new package
                _indexingService.UpdateIndex();

                // If we're pushing a new stable version of NuGet.CommandLine, update the extracted executable.
                if (package.PackageRegistration.Id.Equals(Constants.NuGetCommandLinePackageId, StringComparison.OrdinalIgnoreCase) &&
                    package.IsLatestStable)
                {
                    await _nugetExeDownloaderService.UpdateExecutableAsync(nugetPackage);
                }
            }

            // delete the uploaded binary in the Uploads container
            await _uploadFileService.DeleteUploadFileAsync(currentUser.Key);

            TempData["Message"] = String.Format(
                CultureInfo.CurrentCulture, Strings.SuccessfullyUploadedPackage, package.PackageRegistration.Id, package.Version);

            return(RedirectToRoute(RouteName.DisplayPackage, new { package.PackageRegistration.Id, package.Version }));
        }
Пример #10
0
 public KeyValuePair <StatusCode, object> CreatePackage(Package package)
 {
     try
     {
         _packageService.CreatePackage(package);
         return(new KeyValuePair <StatusCode, object>(StatusCode.Created, package));
     }
     catch (Exception e)
     {
         return(HandleException(e));
     }
 }
Пример #11
0
        private ActionResult CreatePackageInternal(string apiKey)
        {
            Guid parsedApiKey;

            if (!Guid.TryParse(apiKey, out parsedApiKey))
            {
                return(new HttpStatusCodeWithBodyResult(
                           HttpStatusCode.BadRequest, String.Format(CultureInfo.CurrentCulture, Strings.InvalidApiKey, apiKey)));
            }

            var user = _userSvc.FindByApiKey(parsedApiKey);

            if (user == null)
            {
                return(new HttpStatusCodeWithBodyResult(
                           HttpStatusCode.Forbidden, String.Format(CultureInfo.CurrentCulture, Strings.ApiKeyNotAuthorized, "push")));
            }

            var packageToPush = ReadPackageFromRequest();

            // Ensure that the user can push packages for this partialId.
            var packageRegistration = _packageSvc.FindPackageRegistrationById(packageToPush.Id);

            if (packageRegistration != null)
            {
                if (!packageRegistration.IsOwner(user))
                {
                    return(new HttpStatusCodeWithBodyResult(
                               HttpStatusCode.Forbidden, String.Format(CultureInfo.CurrentCulture, Strings.ApiKeyNotAuthorized, "push")));
                }

                // Check if a particular Id-Version combination already exists. We eventually need to remove this check.
                bool packageExists =
                    packageRegistration.Packages.Any(p => p.Version.Equals(packageToPush.Version.ToString(), StringComparison.OrdinalIgnoreCase));
                if (packageExists)
                {
                    return(new HttpStatusCodeWithBodyResult(
                               HttpStatusCode.Conflict,
                               String.Format(CultureInfo.CurrentCulture, Strings.PackageExistsAndCannotBeModified, packageToPush.Id, packageToPush.Version)));
                }
            }

            var package = _packageSvc.CreatePackage(packageToPush, user);

            if (packageToPush.Id.Equals(Constants.NuGetCommandLinePackageId, StringComparison.OrdinalIgnoreCase) && package.IsLatestStable)
            {
                // If we're pushing a new stable version of NuGet.CommandLine, update the extracted executable.
                _nugetExeDownloaderSvc.UpdateExecutable(packageToPush);
            }

            return(new HttpStatusCodeResult(201));
        }
        public ActionResult Download(string p)
        {
            if (!Services.Authorizer.Authorize(Permissions.DownloadPackages, T("Not allowed to download packages")))
            {
                return(new HttpUnauthorizedResult());
            }

            string fileName = _packageService.CreatePackage(p, _tempPackageStoragePath.Value);

            if (!string.IsNullOrWhiteSpace(fileName) && System.IO.File.Exists(fileName))
            {
                var filePathResult = new FilePathResult(fileName, _mimeTypeProvider.GetMimeType(fileName));
                filePathResult.FileDownloadName = Path.GetFileName(fileName);
                return(filePathResult);
            }
            return(new HttpNotFoundResult());
        }
Пример #13
0
        public virtual ActionResult VerifyPackage(bool?listed)
        {
            var currentUser = userSvc.FindByUsername(GetIdentity().Name);

            IPackage nugetPackage;

            using (var uploadFile = uploadFileSvc.GetUploadFile(currentUser.Key))
            {
                if (uploadFile == null)
                {
                    return(HttpNotFound());
                }
                nugetPackage = ReadNuGetPackage(uploadFile);
            }

            Package package;

            using (var tx = new TransactionScope())
            {
                package = packageSvc.CreatePackage(nugetPackage, currentUser);
                packageSvc.PublishPackage(package.PackageRegistration.Id, package.Version);
                if (listed.HasValue && listed.Value == false)
                {
                    packageSvc.MarkPackageUnlisted(package);
                }
                uploadFileSvc.DeleteUploadFile(currentUser.Key);
                autoCuratedPackageCmd.Execute(package, nugetPackage);
                tx.Complete();
            }

            if (package.PackageRegistration.Id.Equals(Constants.NuGetCommandLinePackageId, StringComparison.OrdinalIgnoreCase) && package.IsLatestStable)
            {
                // If we're pushing a new stable version of NuGet.CommandLine, update the extracted executable.
                nugetExeDownloaderSvc.UpdateExecutable(nugetPackage);
            }

            TempData["Message"] = string.Format(
                "You have successfully created '{0}' version '{1}'. The package is now under review by the moderators and will show up once approved.", package.PackageRegistration.Id, package.Version);
            return(RedirectToRoute(
                       RouteName.DisplayPackage, new
            {
                package.PackageRegistration.Id,
                package.Version
            }));
        }
Пример #14
0
        private ActionResult CreatePackageInternal(Guid apiKey)
        {
            var user = userSvc.FindByApiKey(apiKey);

            if (user == null)
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Forbidden, string.Format(CultureInfo.CurrentCulture, Strings.ApiKeyNotAuthorized, "push")));
            }

            var packageToPush = ReadPackageFromRequest();

            var package = packageSvc.FindPackageByIdAndVersion(packageToPush.Id, packageToPush.Version.ToString());

            if (package != null)
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Conflict, string.Format(Strings.PackageExistsAndCannotBeModified, packageToPush.Id, packageToPush.Version.ToString())));
            }

            package = packageSvc.CreatePackage(packageToPush, user);
            return(new HttpStatusCodeResult(201));
        }
Пример #15
0
 public OutPutDto Post([FromBody] PackagesDto PackagesDto)
 {
     return(_PackagesService.CreatePackage(PackagesDto));
 }
Пример #16
0
 public async Task <string> CreatePackage(PackageInfo package)
 {
     return(await _packageService.CreatePackage(package));
 }
Пример #17
0
        [ValidateInput(false)] // Security note: Disabling ASP.Net input validation which does things like disallow angle brackets in submissions. See http://go.microsoft.com/fwlink/?LinkID=212874
        public virtual async Task <ActionResult> VerifyPackage(VerifyPackageRequest formData)
        {
            var currentUser = GetCurrentUser();

            Package package;

            using (Stream uploadFile = await _uploadFileService.GetUploadFileAsync(currentUser.Key))
            {
                if (uploadFile == null)
                {
                    TempData["Message"] = "Your attempt to verify the package submission failed, because we could not find the uploaded package file. Please try again.";
                    return(new RedirectResult(Url.UploadPackage()));
                }

                INupkg nugetPackage = await SafeCreatePackage(currentUser, uploadFile);

                if (nugetPackage == null)
                {
                    // Send the user back
                    return(new RedirectResult(Url.UploadPackage()));
                }
                Debug.Assert(nugetPackage != null);

                // Rule out problem scenario with multiple tabs - verification request (possibly with edits) was submitted by user
                // viewing a different package to what was actually most recently uploaded
                if (!(String.IsNullOrEmpty(formData.Id) || String.IsNullOrEmpty(formData.Version)))
                {
                    if (!(String.Equals(nugetPackage.Metadata.Id, formData.Id, StringComparison.OrdinalIgnoreCase) &&
                          String.Equals(nugetPackage.Metadata.Version.ToNormalizedString(), formData.Version, StringComparison.OrdinalIgnoreCase)))
                    {
                        TempData["Message"] = "Your attempt to verify the package submission failed, because the package file appears to have changed. Please try again.";
                        return(new RedirectResult(Url.VerifyPackage()));
                    }
                }

                bool pendEdit = false;
                if (formData.Edit != null)
                {
                    pendEdit = pendEdit || formData.Edit.RequiresLicenseAcceptance != nugetPackage.Metadata.RequireLicenseAcceptance;

                    pendEdit = pendEdit || IsDifferent(formData.Edit.IconUrl, nugetPackage.Metadata.IconUrl.ToEncodedUrlStringOrNull());
                    pendEdit = pendEdit || IsDifferent(formData.Edit.ProjectUrl, nugetPackage.Metadata.ProjectUrl.ToEncodedUrlStringOrNull());

                    pendEdit = pendEdit || IsDifferent(formData.Edit.Authors, nugetPackage.Metadata.Authors.Flatten());
                    pendEdit = pendEdit || IsDifferent(formData.Edit.Copyright, nugetPackage.Metadata.Copyright);
                    pendEdit = pendEdit || IsDifferent(formData.Edit.Description, nugetPackage.Metadata.Description);
                    pendEdit = pendEdit || IsDifferent(formData.Edit.ReleaseNotes, nugetPackage.Metadata.ReleaseNotes);
                    pendEdit = pendEdit || IsDifferent(formData.Edit.Summary, nugetPackage.Metadata.Summary);
                    pendEdit = pendEdit || IsDifferent(formData.Edit.Tags, nugetPackage.Metadata.Tags);
                    pendEdit = pendEdit || IsDifferent(formData.Edit.VersionTitle, nugetPackage.Metadata.Title);
                }

                // update relevant database tables
                package = _packageService.CreatePackage(nugetPackage, currentUser, commitChanges: false);
                Debug.Assert(package.PackageRegistration != null);

                _packageService.PublishPackage(package, commitChanges: false);

                if (pendEdit)
                {
                    // Add the edit request to a queue where it will be processed in the background.
                    _editPackageService.StartEditPackageRequest(package, formData.Edit, currentUser);
                }

                if (!formData.Listed)
                {
                    _packageService.MarkPackageUnlisted(package, commitChanges: false);
                }

                _autoCuratedPackageCmd.Execute(package, nugetPackage, commitChanges: false);

                // save package to blob storage
                uploadFile.Position = 0;
                await _packageFileService.SavePackageFileAsync(package, uploadFile);

                // commit all changes to database as an atomic transaction
                _entitiesContext.SaveChanges();

                // tell Lucene to update index for the new package
                _indexingService.UpdateIndex();
            }

            // delete the uploaded binary in the Uploads container
            await _uploadFileService.DeleteUploadFileAsync(currentUser.Key);

            TempData["Message"] = String.Format(
                CultureInfo.CurrentCulture, Strings.SuccessfullyUploadedPackage, package.PackageRegistration.Id, package.Version);

            return(RedirectToRoute(RouteName.DisplayPackage, new { package.PackageRegistration.Id, package.Version }));
        }
Пример #18
0
        private ActionResult CreatePackageInternal(string apiKey)
        {
            Guid parsedApiKey;

            if (!Guid.TryParse(apiKey, out parsedApiKey))
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, Strings.InvalidApiKey));
            }

            var user = userSvc.FindByApiKey(parsedApiKey);

            if (user == null)
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Forbidden, String.Format(CultureInfo.CurrentCulture, Strings.ApiKeyNotAuthorized, "push")));
            }
            var requestIp   = GetIpAddress();
            var cfRay       = Request.Headers["CF-RAY"].to_string();
            var cfRequestId = Request.Headers["CF-REQUEST-ID"].to_string();
            var requestId   = "{0}|{1}|{2}|{3}".format_with(cfRay, cfRequestId, requestIp, user.Username);

            if (string.IsNullOrWhiteSpace(cfRay))
            {
                // we are not using cloudflare, so remove some items
                requestId = "{0}|{1}".format_with(requestIp, user.Username);
            }

            Trace.TraceInformation("[{0}] - New package being pushed by {1} from ip address {2}".format_with(requestId, user.Username, requestIp));

            if (user.IsBanned)
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Created, "Package has been pushed and will show up once moderated and approved."));
            }


            Trace.TraceInformation("[{0}] - Package has a content length of: {1} MB".format_with(requestId, Request.ContentLength / ONE_MB));

            if (Request.ContentLength > MAX_ALLOWED_CONTENT_LENGTH)
            {
                Trace.TraceError("[{0}] - Package is too large at '{1}' (max size allowed is '{2}'".format_with(requestId, Request.ContentLength, MAX_ALLOWED_CONTENT_LENGTH));
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.RequestEntityTooLarge, String.Format(CultureInfo.CurrentCulture, Strings.PackageTooLarge, MAX_ALLOWED_CONTENT_LENGTH / ONE_MB)));
            }

            // Tempfile to store the package from stream.
            // Based on https://github.com/NuGet/NuGetGallery/issues/3042
            var temporaryFile = Path.GetTempFileName();

            Trace.TraceInformation("[{0}] - Saving temp file for package at '{1}'".format_with(requestId, temporaryFile));
            var packageToPush = ReadPackageFromRequest(temporaryFile);

            var packageId      = packageToPush.Id;
            var packageVersion = packageToPush.Version;

            Trace.TraceInformation("[{0}] - Package being pushed is {1} (v{2})".format_with(requestId, packageId, packageVersion.to_string()));
            requestId += "|{0}|{1}".format_with(packageId, packageVersion);

            // don't allow forbidden package names to be pushed
            if (_forbiddenPackageNames.Contains(packageId, StringComparer.InvariantCultureIgnoreCase))
            {
                Trace.TraceError("[{0}] - Package is using a forbidden name of '{1}'".format_with(requestId, packageId));
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Forbidden, String.Format(CultureInfo.CurrentCulture, Strings.ApiKeyNotAuthorized, "push")));
            }

            // Ensure that the user can push packages for this partialId.
            var packageRegistration = packageSvc.FindPackageRegistrationById(packageId, useCache: false);

            if (packageRegistration != null)
            {
                if (!packageRegistration.IsOwner(user))
                {
                    Trace.TraceError("[{0}] - User '{1}' doesn't have rights to push package '{2}'".format_with(requestId, user.Username, packageId));
                    return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Forbidden, String.Format(CultureInfo.CurrentCulture, Strings.ApiKeyNotAuthorized, "push")));
                }

                var existingPackage = packageRegistration.Packages.FirstOrDefault(p => p.Version.Equals(packageToPush.Version.ToString(), StringComparison.OrdinalIgnoreCase));

                if (existingPackage != null)
                {
                    switch (existingPackage.Status)
                    {
                    case PackageStatusType.Rejected:
                        var testReporterUser = userSvc.FindByUserId(settings.PackageOperationsUserKey);

                        if (existingPackage.PackageCleanupResultDate.HasValue &&
                            testReporterUser != null &&
                            existingPackage.ReviewedById == testReporterUser.Key
                            )
                        {
                            Trace.TraceInformation("[{0}] - Package version has been rejected, but change is allowed by cleanup service.".format_with(requestId));
                            //allow rejected by cleanup to return a value
                            break;
                        }

                        Trace.TraceError("[{0}] - Package version has been rejected and can no longer be submitted.".format_with(requestId));
                        return(new HttpStatusCodeWithBodyResult(
                                   HttpStatusCode.Conflict, string.Format("This package has been {0} and can no longer be submitted.", existingPackage.Status.GetDescriptionOrValue().ToLower())));

                    case PackageStatusType.Submitted:
                        //continue on
                        break;

                    default:
                        Trace.TraceError("[{0}] - Package version is in state {1} and can no longer be submitted.".format_with(requestId, existingPackage.Status.GetDescriptionOrValue().ToLower()));
                        return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Conflict, String.Format(CultureInfo.CurrentCulture, Strings.PackageExistsAndCannotBeModified, packageToPush.Id, packageToPush.Version)));
                    }
                }
                else if (!packageRegistration.Packages.Any(p => !p.IsPrerelease && p.Status == PackageStatusType.Approved) &&
                         packageRegistration.Packages.Any(p => p.Status == PackageStatusType.Submitted))
                {
                    Trace.TraceError("[{0}] - Package has a previous version in a submitted state with no approved stable releases.".format_with(requestId));
                    return(new HttpStatusCodeWithBodyResult(
                               HttpStatusCode.Forbidden,
                               string.Format("The package {0} has a previous version in a submitted state, and no approved stable releases. Please work to have the existing package version approved or rejected first.",
                                             packageId),
                               string.Format(@"
Please wait until a minimum of 1 version of the {0} package have been approved,
before pushing a new version.

If the package is currently failing, please see any failure emails sent
out on why it could be failing, as well as instructions on how to fix
any moderation related failures.",
                                             packageId)));
                }

                var allowedNumberOfPackageVersionsInSubmittedStatus = 10;
                var packageVersionsInModerationCount = packageRegistration.Packages.Count(p => p.Status == PackageStatusType.Submitted);
                if (packageVersionsInModerationCount >= allowedNumberOfPackageVersionsInSubmittedStatus)
                {
                    Trace.TraceError("[{0}] - Package has {1} versions currently in submitted state. We limit to {2} versions in moderation at a time.".format_with(requestId, packageVersionsInModerationCount, allowedNumberOfPackageVersionsInSubmittedStatus));
                    return(new HttpStatusCodeWithBodyResult(
                               HttpStatusCode.Forbidden,
                               string.Format("The package {0} has {1} versions currently in a submitted state. For moderation purposes we limit to {2} versions in moderation at a time. Please wait to have the existing package version(s) approved or rejected first.",
                                             packageId, packageVersionsInModerationCount, allowedNumberOfPackageVersionsInSubmittedStatus),
                               string.Format(@"
Please wait to submit more versions of {0} until the current versions are approved or rejected.

If the package is currently failing, please see any failure emails sent
out on why it could be failing, as well as instructions on how to fix
any moderation related failures.",
                                             packageId)));
                }
            }

            try
            {
                Trace.TraceInformation("[{0}] - Creating/updating package information in database.".format_with(requestId));
                packageSvc.CreatePackage(packageToPush, user, requestId);

                packageToPush = null;
            }
            catch (DbEntityValidationException dbvex)
            {
                Trace.TraceError("[{0}] - Pushing package '{1}' (v{2}) had error(s):", requestId, packageId, packageVersion.to_string());
                Trace.TraceError("[{0}] - {1}", requestId, dbvex.Message);

                foreach (var entityValidationError in dbvex.EntityValidationErrors)
                {
                    Trace.TraceError("[{0}] - Entity of type '{1}' in state '{2}' has the following validation errors:", requestId, entityValidationError.Entry.Entity.GetType().Name, entityValidationError.Entry.State);
                    foreach (var validationError in entityValidationError.ValidationErrors)
                    {
                        Trace.TraceError("[{0}]   - Property: '{1}', Error: '{2}'", requestId, validationError.PropertyName, validationError.ErrorMessage);
                    }
                }

                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Conflict, string.Format("This package had an issue pushing: {0}", dbvex.Message)));
            }
            catch (Exception ex)
            {
                var errorMessage = new StringBuilder();
                errorMessage.Append(ex.Message);
                foreach (var innerException in ex.get_inner_exceptions().OrEmptyListIfNull())
                {
                    errorMessage.AppendLine(innerException.Message);
                }

                // NOTE: The following code was added to establish whether a lack of hard drive space on the webhosts was causing
                // the Out of Memory exceptions that were occuring when pushing embedded packages.  It was found that lack of hard
                // drive space was not the issue.  As such, this logging has been commented out, and left for reference, should
                // it be needed again.
                //// Capture the amount of hard drive space left on the web server
                //// There is a suspicion that the web server might be having an issue with clearing up resources
                ////Trace.TraceInformation("[{0}] - Available Hard Drive Space:".format_with(requestId));
                ////DriveInfo[] allDrives = DriveInfo.GetDrives();
                ////foreach (DriveInfo drive in allDrives)
                ////{
                ////    Trace.TraceInformation("[{0}]   - Drive {1}".format_with(requestId, drive.Name));
                ////    if (drive.IsReady == true)
                ////    {
                ////        Trace.TraceInformation("[{0}]     - Available space to current user: {1} MBs. Total available space: {2} MBs. Total size of drive: {3} MBs", requestId, drive.AvailableFreeSpace / ONE_MB, drive.TotalFreeSpace / ONE_MB, drive.TotalSize / ONE_MB);
                ////    }
                ////}

                Trace.TraceError("[{0}] - Pushing package '{1}' (v{2}) had error(s):{3} {4}", requestId, packageId, packageVersion.to_string(), Environment.NewLine, errorMessage.to_string());
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Conflict, string.Format("This package had an issue pushing: {0}", ex.Message)));
            }
            finally
            {
                OptimizedZipPackage.PurgeCache();

                try
                {
                    Trace.TraceInformation("[{0}] - Deleting the temp file at '{1}'.".format_with(requestId, temporaryFile));
                    System.IO.File.Delete(temporaryFile);
                }
                catch (Exception ex)
                {
                    Trace.TraceError("[{0}] - Unable to delete temporary file at '{1}':{2} {3}.".format_with(requestId, temporaryFile, Environment.NewLine, ex.to_string()));
                    ErrorSignal.FromCurrentContext().Raise(ex);
                    //todo: is this really an error if we can't remove a file? Everything else was successful for the user
                    //return new HttpStatusCodeWithBodyResult(HttpStatusCode.InternalServerError, "Could not remove temporary upload file: {0}", ex.Message);
                }
            }

            Trace.TraceInformation("[{0}] - Package {1} (v{2}) has been pushed successfully.".format_with(requestId, packageId, packageVersion.to_string()));
            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Created, "Package has been pushed and will show up once moderated and approved."));
        }
Пример #19
0
        private ActionResult CreatePackageInternal(string apiKey)
        {
            Guid parsedApiKey;

            if (!Guid.TryParse(apiKey, out parsedApiKey))
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, Strings.InvalidApiKey));
            }

            var user = userSvc.FindByApiKey(parsedApiKey);

            if (user == null)
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Forbidden, String.Format(CultureInfo.CurrentCulture, Strings.ApiKeyNotAuthorized, "push")));
            }

            if (user.IsBanned)
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Created, "Package has been pushed and will show up once moderated and approved."));
            }

            if (Request.ContentLength > MAX_ALLOWED_CONTENT_LENGTH)
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.RequestEntityTooLarge, String.Format(CultureInfo.CurrentCulture, Strings.PackageTooLarge, MAX_ALLOWED_CONTENT_LENGTH / ONE_MB)));
            }

            var packageToPush = ReadPackageFromRequest();

            // Ensure that the user can push packages for this partialId.
            var packageRegistration = packageSvc.FindPackageRegistrationById(packageToPush.Id, useCache: false);

            if (packageRegistration != null)
            {
                if (!packageRegistration.IsOwner(user))
                {
                    return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Forbidden, String.Format(CultureInfo.CurrentCulture, Strings.ApiKeyNotAuthorized, "push")));
                }

                var existingPackage = packageRegistration.Packages.FirstOrDefault(p => p.Version.Equals(packageToPush.Version.ToString(), StringComparison.OrdinalIgnoreCase));

                if (existingPackage != null)
                {
                    switch (existingPackage.Status)
                    {
                    case PackageStatusType.Rejected:
                        var testReporterUser = userSvc.FindByUserId(settings.PackageOperationsUserKey);

                        if (existingPackage.PackageCleanupResultDate.HasValue &&
                            testReporterUser != null &&
                            existingPackage.ReviewedById == testReporterUser.Key
                            )
                        {
                            //allow rejected by cleanup to return a value
                            break;
                        }

                        return(new HttpStatusCodeWithBodyResult(
                                   HttpStatusCode.Conflict, string.Format("This package has been {0} and can no longer be submitted.", existingPackage.Status.GetDescriptionOrValue().ToLower())));

                    case PackageStatusType.Submitted:
                        //continue on
                        break;

                    default:
                        return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Conflict, String.Format(CultureInfo.CurrentCulture, Strings.PackageExistsAndCannotBeModified, packageToPush.Id, packageToPush.Version)));
                    }
                }
                else if (!packageRegistration.Packages.Any(p => !p.IsPrerelease && p.Status == PackageStatusType.Approved) &&
                         packageRegistration.Packages.Any(p => p.Status == PackageStatusType.Submitted))
                {
                    return(new HttpStatusCodeWithBodyResult(
                               HttpStatusCode.Forbidden,
                               string.Format("The package {0} have a previous version in a submitted state, and no approved stable releases.",
                                             packageToPush.Id),
                               string.Format(@"
Please wait until a minimum of 1 version of the {0} package have been approved,
before pushing a new version.

If the package is currently failing, please see any failure emails sent
out on why it could be failing, as well as instructions on how to fix
any moderation related failures.",
                                             packageToPush.Id)));
                }
            }

            try
            {
                packageSvc.CreatePackage(packageToPush, user);
            }
            catch (Exception ex)
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Conflict, string.Format("This package had an issue pushing: {0}", ex.Message)));
            }

            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Created, "Package has been pushed and will show up once moderated and approved."));
        }
Пример #20
0
        private ActionResult CreatePackageInternal(string apiKey)
        {
            Guid parsedApiKey;

            if (!Guid.TryParse(apiKey, out parsedApiKey))
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, Strings.InvalidApiKey));
            }

            var user = userSvc.FindByApiKey(parsedApiKey);

            if (user == null)
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Forbidden, String.Format(CultureInfo.CurrentCulture, Strings.ApiKeyNotAuthorized, "push")));
            }

            if (user.IsBanned)
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Created, "Package has been pushed and will show up once moderated and approved."));
            }

            if (Request.ContentLength > MAX_ALLOWED_CONTENT_LENGTH)
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.RequestEntityTooLarge, String.Format(CultureInfo.CurrentCulture, Strings.PackageTooLarge, MAX_ALLOWED_CONTENT_LENGTH / ONE_MB)));
            }

            // Tempfile to store the package from stream.
            // Based on https://github.com/NuGet/NuGetGallery/issues/3042
            var temporaryFile = Path.GetTempFileName();

            var packageToPush = ReadPackageFromRequest(temporaryFile);

            // Ensure that the user can push packages for this partialId.
            var packageRegistration = packageSvc.FindPackageRegistrationById(packageToPush.Id, useCache: false);

            if (packageRegistration != null)
            {
                if (!packageRegistration.IsOwner(user))
                {
                    return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Forbidden, String.Format(CultureInfo.CurrentCulture, Strings.ApiKeyNotAuthorized, "push")));
                }

                var existingPackage = packageRegistration.Packages.FirstOrDefault(p => p.Version.Equals(packageToPush.Version.ToString(), StringComparison.OrdinalIgnoreCase));

                if (existingPackage != null)
                {
                    switch (existingPackage.Status)
                    {
                    case PackageStatusType.Rejected:
                        var testReporterUser = userSvc.FindByUserId(settings.PackageOperationsUserKey);

                        if (existingPackage.PackageCleanupResultDate.HasValue &&
                            testReporterUser != null &&
                            existingPackage.ReviewedById == testReporterUser.Key
                            )
                        {
                            //allow rejected by cleanup to return a value
                            break;
                        }

                        return(new HttpStatusCodeWithBodyResult(
                                   HttpStatusCode.Conflict, string.Format("This package has been {0} and can no longer be submitted.", existingPackage.Status.GetDescriptionOrValue().ToLower())));

                    case PackageStatusType.Submitted:
                        //continue on
                        break;

                    default:
                        return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Conflict, String.Format(CultureInfo.CurrentCulture, Strings.PackageExistsAndCannotBeModified, packageToPush.Id, packageToPush.Version)));
                    }
                }
                else if (!packageRegistration.Packages.Any(p => !p.IsPrerelease && p.Status == PackageStatusType.Approved) &&
                         packageRegistration.Packages.Any(p => p.Status == PackageStatusType.Submitted))
                {
                    return(new HttpStatusCodeWithBodyResult(
                               HttpStatusCode.Forbidden,
                               string.Format("The package {0} has a previous version in a submitted state, and no approved stable releases. Please work to have the existing package version approved or rejected first.",
                                             packageToPush.Id),
                               string.Format(@"
Please wait until a minimum of 1 version of the {0} package have been approved,
before pushing a new version.

If the package is currently failing, please see any failure emails sent
out on why it could be failing, as well as instructions on how to fix
any moderation related failures.",
                                             packageToPush.Id)));
                }

                var allowedNumberOfPackageVersionsInSubmittedStatus = 10;
                if (packageRegistration.Packages.Count(p => p.Status == PackageStatusType.Submitted) >= allowedNumberOfPackageVersionsInSubmittedStatus)
                {
                    return(new HttpStatusCodeWithBodyResult(
                               HttpStatusCode.Forbidden,
                               string.Format("The package {0} has {1} versions currently in a submitted state. For moderation purposes we limit to {1} versions in moderation at a time. Please wait to have the existing package version(s) approved or rejected first.",
                                             packageToPush.Id, allowedNumberOfPackageVersionsInSubmittedStatus),
                               string.Format(@"
Please wait to submit more versions of {0} until the current versions are approved or rejected.

If the package is currently failing, please see any failure emails sent
out on why it could be failing, as well as instructions on how to fix
any moderation related failures.",
                                             packageToPush.Id)));
                }
            }

            try
            {
                packageSvc.CreatePackage(packageToPush, user);

                packageToPush = null;

                try
                {
                    System.IO.File.Delete(temporaryFile);
                }
                catch (Exception ex)
                {
                    return(new HttpStatusCodeWithBodyResult(HttpStatusCode.InternalServerError, "Could not remove temporary upload file: {0}", ex.Message));
                }
            }
            catch (Exception ex)
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Conflict, string.Format("This package had an issue pushing: {0}", ex.Message)));
            }
            finally
            {
                OptimizedZipPackage.PurgeCache();
            }

            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Created, "Package has been pushed and will show up once moderated and approved."));
        }
Пример #21
0
 public string CreatePackage(PackageDTO packageDto)
 {
     return(_packageService.CreatePackage(packageDto));
 }