Пример #1
0
        public async Task <Package> GeneratePackageAsync(
            string id,
            PackageArchiveReader nugetPackage,
            PackageStreamMetadata packageStreamMetadata,
            User user)
        {
            var isPushAllowed        = _reservedNamespaceService.IsPushAllowed(id, user, out IReadOnlyCollection <ReservedNamespace> userOwnedNamespaces);
            var shouldMarkIdVerified = isPushAllowed && userOwnedNamespaces != null && userOwnedNamespaces.Any();

            var package = await _packageService.CreatePackageAsync(
                nugetPackage,
                packageStreamMetadata,
                user,
                isVerified : shouldMarkIdVerified);

            await _validationService.StartValidationAsync(package);

            if (shouldMarkIdVerified)
            {
                // Add all relevant package registrations to the applicable namespaces
                foreach (var rn in userOwnedNamespaces)
                {
                    _reservedNamespaceService.AddPackageRegistrationToNamespace(
                        rn.Value,
                        package.PackageRegistration);
                }
            }

            return(package);
        }
Пример #2
0
        public async Task <Package> GeneratePackageAsync(
            string id,
            PackageArchiveReader nugetPackage,
            PackageStreamMetadata packageStreamMetadata,
            User owner,
            User currentUser)
        {
            var shouldMarkIdVerified = _reservedNamespaceService.ShouldMarkNewPackageIdVerified(owner, id, out var ownedMatchingReservedNamespaces);

            var package = await _packageService.CreatePackageAsync(
                nugetPackage,
                packageStreamMetadata,
                owner,
                currentUser,
                isVerified : shouldMarkIdVerified);

            if (shouldMarkIdVerified)
            {
                // Add all relevant package registrations to the applicable namespaces
                foreach (var rn in ownedMatchingReservedNamespaces)
                {
                    _reservedNamespaceService.AddPackageRegistrationToNamespace(
                        rn.Value,
                        package.PackageRegistration);
                }
            }

            _vulnerabilityService.ApplyExistingVulnerabilitiesToPackage(package);

            return(package);
        }
        public async Task <IActionResult> CreatePackage(CreatePackageCommand command)
        {
            var result = await _packageService.CreatePackageAsync(command);

            return(result.Success
                ? StatusCode(StatusCodes.Status201Created, result)
                : StatusCode(StatusCodes.Status400BadRequest, result));
        }
        public async Task <Package> GeneratePackageAsync(string id, PackageArchiveReader nugetPackage, PackageStreamMetadata packageStreamMetadata, User user, bool commitChanges)
        {
            var isPushAllowed = _reservedNamespaceService.IsPushAllowed(id, user, out IReadOnlyCollection <ReservedNamespace> userOwnedNamespaces);

            var shouldMarkIdVerified = isPushAllowed && userOwnedNamespaces != null && userOwnedNamespaces.Any();
            var package = await _packageService.CreatePackageAsync(
                nugetPackage,
                packageStreamMetadata,
                user,
                isVerified : shouldMarkIdVerified,
                commitChanges : commitChanges);

            if (shouldMarkIdVerified)
            {
                // Add all relevant package registrations to the applicable namespaces
                await Task.WhenAll(userOwnedNamespaces
                                   .Select(rn => _reservedNamespaceService.AddPackageRegistrationToNamespaceAsync(rn.Value, package.PackageRegistration, commitChanges)));
            }

            return(package);
        }
Пример #5
0
        private async Task <bool> IsValidAsync(
            IPackageService packageService,
            RequirePackageMetadataState state,
            string packagePath)
        {
            if (!File.Exists(packagePath) && !Directory.Exists(packagePath))
            {
                OutputColor(
                    ConsoleColor.Red,
                    () =>
                {
                    _console.WriteLine("INVALID.");
                    _console.WriteLine(packagePath);
                    _console.WriteLine("The path does not exist.");
                });
                return(false);
            }

            if (File.GetAttributes(packagePath).HasFlag(FileAttributes.Directory))
            {
                OutputColor(
                    ConsoleColor.Red,
                    () =>
                {
                    _console.WriteLine("INVALID.");
                    _console.WriteLine(packagePath);
                    _console.WriteLine("The path is a directory, not a file.");
                });
                return(false);
            }

            Package package;

            using (var packageStream = File.OpenRead(packagePath))
            {
                var packageArchiveReader = new PackageArchiveReader(packageStream);

                var packageStreamMetadata = new PackageStreamMetadata
                {
                    HashAlgorithm = CoreConstants.Sha512HashAlgorithmId,
                    Hash          = CryptographyService.GenerateHash(
                        packageStream.AsSeekableStream(),
                        CoreConstants.Sha512HashAlgorithmId),
                    Size = packageStream.Length
                };

                var owner       = new User();
                var currentUser = owner;
                var isVerified  = true;

                package = await packageService.CreatePackageAsync(
                    packageArchiveReader,
                    packageStreamMetadata,
                    owner,
                    currentUser,
                    isVerified);
            }

            var isCompliant = RequirePackageMetadataComplianceUtility.IsPackageMetadataCompliant(
                package,
                state,
                out var complianceFailures);

            if (isCompliant)
            {
                OutputColor(
                    ConsoleColor.Green,
                    () =>
                {
                    _console.WriteLine("VALID.");
                    _console.WriteLine(packagePath);
                    _console.WriteLine($"The package {package.Id} {package.Version} is compliant.");
                });
                return(true);
            }
            else
            {
                OutputColor(
                    ConsoleColor.Red,
                    () =>
                {
                    var single = complianceFailures.Count == 1;
                    _console.WriteLine("INVALID.");
                    _console.WriteLine(packagePath);
                    _console.WriteLine($"The package {package.Id} {package.Version} is not compliant.");
                    _console.WriteLine($"There {(single ? "is" : "are")} {complianceFailures.Count} problem{(single ? string.Empty : "s")}.");
                    foreach (var failure in complianceFailures)
                    {
                        _console.WriteLine($"  - {failure}");
                    }
                });
                return(false);
            }
        }
Пример #6
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()));
                }

                var nugetPackage = await SafeCreatePackage(currentUser, uploadFile);

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

                var packageMetadata = PackageMetadata.FromNuspecReader(
                    nugetPackage.GetNuspecReader());

                // 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(packageMetadata.Id, formData.Id, StringComparison.OrdinalIgnoreCase) &&
                          String.Equals(packageMetadata.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 != packageMetadata.RequireLicenseAcceptance;

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

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

                var packageStreamMetadata = new PackageStreamMetadata
                {
                    HashAlgorithm = Constants.Sha512HashAlgorithmId,
                    Hash          = CryptographyService.GenerateHash(uploadFile.AsSeekableStream()),
                    Size          = uploadFile.Length,
                };

                // update relevant database tables
                try
                {
                    package = await _packageService.CreatePackageAsync(nugetPackage, packageStreamMetadata, currentUser, commitChanges : false);

                    Debug.Assert(package.PackageRegistration != null);
                }
                catch (EntityException ex)
                {
                    TempData["Message"] = ex.Message;
                    return(Redirect(Url.UploadPackage()));
                }

                await _packageService.PublishPackageAsync(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)
                {
                    await _packageService.MarkPackageUnlistedAsync(package, commitChanges : false);
                }

                await _autoCuratedPackageCmd.ExecuteAsync(package, nugetPackage, commitChanges : false);

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

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

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

                _messageService.SendPackageAddedNotice(package,
                                                       Url.Action("DisplayPackage", "Packages", routeValues: new { id = package.PackageRegistration.Id, version = package.Version }, protocol: Request.Url.Scheme),
                                                       Url.Action("ReportMyPackage", "Packages", routeValues: new { id = package.PackageRegistration.Id, version = package.Version }, protocol: Request.Url.Scheme),
                                                       Url.Action("Account", "Users", routeValues: null, protocol: Request.Url.Scheme));
            }

            // 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 }));
        }
        public async Task <ActionResult> CreatePackageForOneCatering([FromBody] CreatePackageRequest request, [FromRoute] Guid cateringId)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new ApiErrorResponse()
                {
                    ErrorType = "Bad Request",
                    StatusCode = 400,
                    Errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage)
                }));
            }

            var catering = await cateringService.GetCateringByIdAsync(cateringId);

            if (catering == null)
            {
                return(NotFound(new ApiErrorResponse()
                {
                    ErrorType = "Not Found",
                    StatusCode = 404,
                    Errors = new string[] { "Catering doesn't exist" }
                }));
            }

            var package = new Package
            {
                Name   = request.Name,
                Serves = request.Serves,
                ServicePresentation = request.ServicePresentation,
                SetupTime           = request.SetupTime,
                Description         = request.Description,
                Price = request.Price,
                Menus = request.Menus.Select(m => new Menu {
                    Name = m
                }).ToList(),
                Catering       = catering,
                PackageOptions = request.PackageOptions.Select(o => new PackageOption
                {
                    OptionsType        = o.OptionsType,
                    Title              = o.Title,
                    PackageOptionItems = o.PackageOptionItems.Select(i => new PackageOptionItem {
                        Name = i
                    }).ToList()
                }).ToList(),
                PackageRequirements = request.PackageRequirements.Select(r => new PackageRequirement {
                    Name = r
                }).ToList()
            };

            var created = await packageService.CreatePackageAsync(package);

            if (!created)
            {
                return(BadRequest(new ApiErrorResponse()
                {
                    ErrorType = "Bad Request",
                    StatusCode = 400,
                    Errors = new[] { "Unable to create a package." }
                }));
            }

            var baseUrl     = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.ToUriComponent()}";
            var locationUrl = baseUrl + "/" + ApiRoutes.Packages.Get.Replace("{packageId}", package.Id.ToString());

            var response = new CreatePackageSuccessResponse()
            {
                Id = package.Id
            };

            return(Created(locationUrl, response));
        }