Exemple #1
0
        public virtual async Task <ActionResult> GetPackage(string id, string version)
        {
            // some security paranoia about URL hacking somehow creating e.g. open redirects
            // validate user input: explicit calls to the same validators used during Package Registrations
            // Ideally shouldn't be necessary?
            if (!PackageIdValidator.IsValidPackageId(id ?? ""))
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, "The format of the package id is invalid"));
            }

            // if version is non-null, check if it's semantically correct and normalize it.
            if (!String.IsNullOrEmpty(version))
            {
                NuGetVersion dummy;
                if (!NuGetVersion.TryParse(version, out dummy))
                {
                    return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, "The package version is not a valid semantic version"));
                }

                // Normalize the version
                version = NuGetVersionNormalizer.Normalize(version);
            }
            else
            {
                // if version is null, get the latest version from the database.
                // This ensures that on package restore scenario where version will be non null, we don't hit the database.
                try
                {
                    var package = PackageService.FindPackageByIdAndVersion(id, version, allowPrerelease: false);
                    if (package == null)
                    {
                        return(new HttpStatusCodeWithBodyResult(HttpStatusCode.NotFound, String.Format(CultureInfo.CurrentCulture, Strings.PackageWithIdAndVersionNotFound, id, version)));
                    }
                    version = package.NormalizedVersion;
                }
                catch (SqlException e)
                {
                    QuietLog.LogHandledException(e);

                    // Database was unavailable and we don't have a version, return a 503
                    return(new HttpStatusCodeWithBodyResult(HttpStatusCode.ServiceUnavailable, Strings.DatabaseUnavailable_TrySpecificVersion));
                }
                catch (DataException e)
                {
                    QuietLog.LogHandledException(e);

                    // Database was unavailable and we don't have a version, return a 503
                    return(new HttpStatusCodeWithBodyResult(HttpStatusCode.ServiceUnavailable, Strings.DatabaseUnavailable_TrySpecificVersion));
                }
            }

            if (ConfigurationService.Features.TrackPackageDownloadCountInLocalDatabase)
            {
                await PackageService.IncrementDownloadCountAsync(id, version);
            }

            return(await PackageFileService.CreateDownloadPackageActionResultAsync(
                       HttpContext.Request.Url,
                       id, version));
        }
        public void ValidatePackageIdInvalidIdReturnsFalse(string packageId)
        {
            // Act
            bool isValid = PackageIdValidator.IsValidPackageId(packageId);

            // Assert
            Assert.False(isValid);
        }
        public void ValidatePackageIdWithValidIdReturnsTrue(string packageId)
        {
            // Act
            bool isValid = PackageIdValidator.IsValidPackageId(packageId);

            // Assert
            Assert.True(isValid);
        }
        public void NullThrowsException()
        {
            // Arrange
            string packageId = null;

            // Act & Assert
            Assert.Throws <ArgumentNullException>("packageId",
                                                  () => PackageIdValidator.IsValidPackageId(packageId));
        }
        public void ValidatePackageIdInvalidIdThrows(string packageId)
        {
            // Act & Assert
            Exception thrownException = null;

            try
            {
                PackageIdValidator.ValidatePackageId(packageId);
            }
            catch (Exception ex)
            {
                thrownException = ex;
            }

            Assert.NotNull(thrownException);
            Assert.Equal("The package ID '" + packageId + "' contains invalid characters. Examples of valid package IDs include 'MyPackage' and 'MyPackage.Sample'.", thrownException.Message);
        }
        public void IdExceedingMaxLengthThrows(int idTestLength)
        {
            // Arrange
            string packageId = new string('d', idTestLength);

            // Act && Assert
            Exception thrownException = null;

            try
            {
                PackageIdValidator.ValidatePackageId(packageId);
            }
            catch (Exception ex)
            {
                thrownException = ex;
            }

            Assert.NotNull(thrownException);
            Assert.Equal("Id must not exceed " + Constants.MaxPackageIdLength + " characters.", thrownException.Message);
        }
        private static IEnumerable <ValidationResult> ValidateCore(PackageMetadata packageMetadata)
        {
            // Validate the ID
            if (string.IsNullOrEmpty(packageMetadata.Id))
            {
                yield return(new ValidationResult(CoreStrings.Manifest_MissingId));
            }
            else
            {
                if (packageMetadata.Id.Length > NuGet.Packaging.PackageIdValidator.MaxPackageIdLength)
                {
                    yield return(new ValidationResult(CoreStrings.Manifest_IdTooLong));
                }
                else if (!PackageIdValidator.IsValidPackageId(packageMetadata.Id))
                {
                    yield return(new ValidationResult(String.Format(
                                                          CultureInfo.CurrentCulture,
                                                          CoreStrings.Manifest_InvalidId,
                                                          packageMetadata.Id)));
                }
            }

            // Check and validate URL properties
            foreach (var result in CheckUrls(
                         packageMetadata.GetValueFromMetadata("IconUrl"),
                         packageMetadata.GetValueFromMetadata("ProjectUrl"),
                         packageMetadata.GetValueFromMetadata("LicenseUrl")))
            {
                yield return(result);
            }

            // Check version
            if (packageMetadata.Version == null)
            {
                var version = packageMetadata.GetValueFromMetadata("version");

                yield return(new ValidationResult(String.Format(
                                                      CultureInfo.CurrentCulture,
                                                      CoreStrings.Manifest_InvalidVersion,
                                                      version)));
            }

            var versionValidationResult = ValidateVersion(packageMetadata.Version);

            if (versionValidationResult != null)
            {
                yield return(versionValidationResult);
            }

            // Check framework reference groups
            var frameworkReferenceGroups = packageMetadata.GetFrameworkReferenceGroups();

            if (frameworkReferenceGroups != null)
            {
                foreach (var frameworkReferenceGroup in frameworkReferenceGroups)
                {
                    var isUnsupportedFramework = frameworkReferenceGroup?.TargetFramework?.IsUnsupported;
                    if (isUnsupportedFramework.HasValue && isUnsupportedFramework.Value)
                    {
                        yield return(new ValidationResult(String.Format(
                                                              CultureInfo.CurrentCulture,
                                                              CoreStrings.Manifest_TargetFrameworkNotSupported,
                                                              frameworkReferenceGroup?.TargetFramework?.ToString())));
                    }
                }
            }

            // Check dependency groups
            var dependencyGroups = packageMetadata.GetDependencyGroups();

            if (dependencyGroups != null)
            {
                foreach (var dependencyGroup in dependencyGroups)
                {
                    // Keep track of duplicates
                    var dependencyIds = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

                    // Verify frameworks
                    var isUnsupportedFramework = dependencyGroup.TargetFramework?.IsUnsupported;
                    if (isUnsupportedFramework.HasValue && isUnsupportedFramework.Value)
                    {
                        yield return(new ValidationResult(String.Format(
                                                              CultureInfo.CurrentCulture,
                                                              CoreStrings.Manifest_TargetFrameworkNotSupported,
                                                              dependencyGroup.TargetFramework?.ToString())));
                    }

                    // Verify package id's and versions
                    foreach (var dependency in dependencyGroup.Packages)
                    {
                        bool duplicate = !dependencyIds.Add(dependency.Id);
                        if (duplicate)
                        {
                            yield return(new ValidationResult(String.Format(
                                                                  CultureInfo.CurrentCulture,
                                                                  CoreStrings.Manifest_DuplicateDependency,
                                                                  dependencyGroup.TargetFramework.GetShortFolderName(),
                                                                  dependency.Id)));
                        }

                        if (!PackageIdValidator.IsValidPackageId(dependency.Id))
                        {
                            yield return(new ValidationResult(String.Format(
                                                                  CultureInfo.CurrentCulture,
                                                                  CoreStrings.Manifest_InvalidDependency,
                                                                  dependency.Id,
                                                                  dependency.VersionRange.OriginalString)));
                        }

                        // Versions
                        if (dependency.VersionRange.MinVersion != null)
                        {
                            var versionRangeValidationResult = ValidateVersion(dependency.VersionRange.MinVersion);
                            if (versionRangeValidationResult != null)
                            {
                                yield return(versionRangeValidationResult);
                            }
                        }

                        if (dependency.VersionRange.MaxVersion != null &&
                            dependency.VersionRange.MaxVersion != dependency.VersionRange.MinVersion)
                        {
                            var versionRangeValidationResult = ValidateVersion(dependency.VersionRange.MaxVersion);
                            if (versionRangeValidationResult != null)
                            {
                                yield return(versionRangeValidationResult);
                            }
                        }
                    }
                }
            }
        }
Exemple #8
0
        public static IEnumerable <ValidationResult> Validate(ManifestMetadata metadata)
        {
            // Validate the ID
            if (String.IsNullOrEmpty(metadata.Id))
            {
                yield return(new ValidationResult(Strings.Manifest_MissingId));
            }
            else
            {
                if (metadata.Id.Length > MaxPackageIdLength)
                {
                    yield return(new ValidationResult(Strings.Manifest_IdTooLong));
                }
                else if (!PackageIdValidator.IsValidPackageId(metadata.Id))
                {
                    yield return(new ValidationResult(String.Format(
                                                          CultureInfo.CurrentCulture,
                                                          Strings.Manifest_InvalidId,
                                                          metadata.Id)));
                }
            }

            foreach (var result in CheckUrls(metadata.IconUrl, metadata.ProjectUrl, metadata.LicenseUrl))
            {
                yield return(result);
            }

            SemanticVersion __;

            if (!SemanticVersion.TryParse(metadata.Version, out __))
            {
                yield return(new ValidationResult(String.Format(
                                                      CultureInfo.CurrentCulture,
                                                      Strings.Manifest_InvalidVersion,
                                                      metadata.Version)));
            }

            if (metadata.DependencySets != null)
            {
                foreach (var dependency in metadata.DependencySets.SelectMany(set => set.Dependencies))
                {
                    IVersionSpec ___;
                    if (!PackageIdValidator.IsValidPackageId(dependency.Id) || (!string.IsNullOrEmpty(dependency.Version) && !VersionUtility.TryParseVersionSpec(dependency.Version, out ___)))
                    {
                        yield return(new ValidationResult(String.Format(
                                                              CultureInfo.CurrentCulture,
                                                              Strings.Manifest_InvalidDependency,
                                                              dependency.Id,
                                                              dependency.Version)));
                    }
                }
            }

            var fxes = Enumerable.Concat(
                metadata.FrameworkAssemblies == null ?
                Enumerable.Empty <string>() :
                (metadata.FrameworkAssemblies.Select(a => a.TargetFramework)),
                metadata.DependencySets == null ?
                Enumerable.Empty <string>() :
                (metadata.DependencySets.Select(s => s.TargetFramework)));

            foreach (var fx in fxes)
            {
                //if target framework is not specified, then continue. Validate only for wrong specification.
                if (string.IsNullOrEmpty(fx))
                {
                    continue;
                }
                ValidationResult result = null;
                try
                {
                    VersionUtility.ParseFrameworkName(fx);
                }
                catch (ArgumentException)
                {
                    // Can't yield in the body of a catch...
                    result = new ValidationResult(String.Format(
                                                      CultureInfo.CurrentCulture,
                                                      Strings.Manifest_InvalidTargetFramework,
                                                      fx));
                }

                if (result != null)
                {
                    yield return(result);
                }
            }
        }
Exemple #9
0
        private static IEnumerable <ValidationResult> ValidateCore(PackageMetadata packageMetadata)
        {
            // Validate the ID
            if (string.IsNullOrEmpty(packageMetadata.Id))
            {
                yield return(new ValidationResult(Strings.Manifest_MissingId));
            }
            else
            {
                if (packageMetadata.Id.Length > MaxPackageIdLength)
                {
                    yield return(new ValidationResult(Strings.Manifest_IdTooLong));
                }
                else if (!PackageIdValidator.IsValidPackageId(packageMetadata.Id))
                {
                    yield return(new ValidationResult(String.Format(
                                                          CultureInfo.CurrentCulture,
                                                          Strings.Manifest_InvalidId,
                                                          packageMetadata.Id)));
                }
            }

            // Check URL properties
            foreach (var result in CheckUrls(
                         packageMetadata.GetValueFromMetadata("IconUrl"),
                         packageMetadata.GetValueFromMetadata("ProjectUrl"),
                         packageMetadata.GetValueFromMetadata("LicenseUrl")))
            {
                yield return(result);
            }

            // Check version
            if (packageMetadata.Version == null)
            {
                var version = packageMetadata.GetValueFromMetadata("version");

                yield return(new ValidationResult(String.Format(
                                                      CultureInfo.CurrentCulture,
                                                      Strings.Manifest_InvalidVersion,
                                                      version)));
            }

            // Check dependency groups
            var dependencyGroups = packageMetadata.GetDependencyGroups();

            if (dependencyGroups != null)
            {
                foreach (var dependencyGroup in dependencyGroups)
                {
                    // Keep track of duplicates
                    var dependencyIds = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

                    // Verify package id's
                    foreach (var dependency in dependencyGroup.Packages)
                    {
                        bool duplicate = !dependencyIds.Add(dependency.Id);
                        if (duplicate)
                        {
                            yield return(new ValidationResult(String.Format(
                                                                  CultureInfo.CurrentCulture,
                                                                  Strings.Manifest_DuplicateDependency,
                                                                  dependencyGroup.TargetFramework.GetShortFolderName(),
                                                                  dependency.Id)));
                        }

                        if (!PackageIdValidator.IsValidPackageId(dependency.Id))
                        {
                            yield return(new ValidationResult(String.Format(
                                                                  CultureInfo.CurrentCulture,
                                                                  Strings.Manifest_InvalidDependency,
                                                                  dependency.Id,
                                                                  dependency.VersionRange.OriginalString)));
                        }
                    }
                }
            }
        }