Exemplo n.º 1
0
        public void TestDependencies_SML_CC2_ConfirmCorrectOrder()
        {
            var validator = new ManifestValidator();
            var tree      = new SortedCollection <string, QMod>();

            var cc2 = new QMod
            {
                Id           = "CustomCraft2SML",
                Dependencies = new[] { "SMLHelper" }
            };

            var sml = new QMod
            {
                Id = "SMLHelper"
            };

            validator.CheckRequiredMods(cc2);
            validator.CheckRequiredMods(sml);

            tree.AddSorted(cc2);
            tree.AddSorted(sml);

            List <QMod> list = tree.GetSortedList();

            Console.WriteLine(ListToString(list));

            Assert.AreEqual(2, list.Count);
            Assert.AreEqual("CustomCraft2SML", list[0].Id);
            Assert.AreEqual("SMLHelper", list[1].Id);
        }
Exemplo n.º 2
0
        public void CheckRequiredMods_WhenRequirementsRedundant_GetExpectedRequiredMod()
        {
            const string requiredMod           = "SMLHelper";
            const string requiredVersionString = "8.6.7";

            var versionDependentMod = new QMod
            {
                // Mod that redundantly includes the same mod both ID and minimum version.
                // Unnecessary, but should not cause errors.
                Dependencies        = new[] { requiredMod },
                VersionDependencies = new Dictionary <string, string>
                {
                    { requiredMod, requiredVersionString }
                }
            };

            var validator = new ManifestValidator();

            validator.CheckRequiredMods(versionDependentMod);

            // Only a single entry is added to RequiredMods.
            Assert.AreEqual(1, versionDependentMod.RequiredMods.Count());

            RequiredQMod expected = new RequiredQMod(requiredMod, requiredVersionString);
            RequiredQMod actual   = versionDependentMod.RequiredMods.First();

            Assert.AreEqual(requiredMod, actual.Id);
            Assert.AreEqual(expected.RequiresMinimumVersion, actual.RequiresMinimumVersion);
            Assert.AreEqual(expected.MinimumVersion, actual.MinimumVersion);
        }
Exemplo n.º 3
0
        public void CheckRequiredMods_WhenRequiresVersion_GetExpectedRequiredMod()
        {
            const string requiredMod           = "SMLHelper";
            const string requiredVersionString = "8.6.7";

            var versionDependentMod = new QMod
            {
                // Mod that requires a minimum version of another mod.
                VersionDependencies = new Dictionary <string, string>
                {
                    { requiredMod, requiredVersionString }
                }
            };

            var validator = new ManifestValidator();

            validator.CheckRequiredMods(versionDependentMod);

            Assert.AreEqual(1, versionDependentMod.RequiredMods.Count());

            RequiredQMod expected = new RequiredQMod(requiredMod, requiredVersionString);
            RequiredQMod actual   = versionDependentMod.RequiredMods.First();

            Assert.AreEqual(requiredMod, actual.Id);
            Assert.AreEqual(expected.RequiresMinimumVersion, actual.RequiresMinimumVersion);
            Assert.AreEqual(expected.MinimumVersion, actual.MinimumVersion);
        }
Exemplo n.º 4
0
        public void CheckRequiredMods_WhenRequiredVersionInvalid_GetExpectedRequiredMod()
        {
            const string requiredMod          = "SMLHelper";
            const string invalidVersionString = "1.X.0.Y";

            var versionDependentMod = new QMod
            {
                // Mod with a bad version string in its version dependencies.
                VersionDependencies = new Dictionary <string, string>
                {
                    { requiredMod, invalidVersionString }
                }
            };

            var validator = new ManifestValidator();

            validator.CheckRequiredMods(versionDependentMod);

            // The entry is added to RequiredMods but without a minimum version.
            Assert.AreEqual(1, versionDependentMod.RequiredMods.Count());

            RequiredQMod expected = new RequiredQMod(requiredMod);
            RequiredQMod actual   = versionDependentMod.RequiredMods.First();

            Assert.AreEqual(requiredMod, actual.Id);
            Assert.AreEqual(expected.RequiresMinimumVersion, actual.RequiresMinimumVersion);
            Assert.AreEqual(expected.MinimumVersion, actual.MinimumVersion);
        }
Exemplo n.º 5
0
        public void TestDependencies_SSS_SE_ConfirmCorrectOrder()
        {
            var validator = new ManifestValidator();
            var tree      = new SortedCollection <string, QMod>();

            var sss = new QMod
            {
                Id         = "SeamothStorageSlots",
                LoadBefore = new[] { "SlotExtender" }
            };

            var se = new QMod
            {
                Id = "SlotExtender"
            };

            validator.CheckRequiredMods(sss);
            validator.CheckRequiredMods(se);

            tree.AddSorted(sss);
            tree.AddSorted(se);

            List <QMod> list = tree.GetSortedList();

            Console.WriteLine(ListToString(list));

            Assert.AreEqual(2, list.Count);
            Assert.AreEqual("SeamothStorageSlots", list[0].Id);
            Assert.AreEqual("SlotExtender", list[1].Id);
        }
Exemplo n.º 6
0
            public void UgyldigNavnPåHoveddokumentValidererIkke()
            {
                var arkiv = DomeneUtility.GetAsicEArkivEnkel();

                var manifestXml        = arkiv.Manifest.Xml();
                var manifestValidering = new ManifestValidator();

                //Endre navn på hoveddokument til å være for kort
                var namespaceManager = new XmlNamespaceManager(manifestXml.NameTable);

                namespaceManager.AddNamespace("ns9", NavneromUtility.DifiSdpSchema10);
                namespaceManager.AddNamespace("ds", NavneromUtility.XmlDsig);

                var hoveddokumentNode = manifestXml.DocumentElement.SelectSingleNode("//ns9:hoveddokument",
                                                                                     namespaceManager);
                var gammelVerdi = hoveddokumentNode.Attributes["href"].Value;

                hoveddokumentNode.Attributes["href"].Value = "abc";

                var validert = manifestValidering.ValiderDokumentMotXsd(manifestXml.OuterXml);

                Assert.IsFalse(validert, manifestValidering.ValideringsVarsler);

                hoveddokumentNode.Attributes["href"].Value = gammelVerdi;
            }
Exemplo n.º 7
0
 public CacheAwareBundleCollectionInitializer(IEnumerable <IConfiguration <BundleCollection> > bundleConfigurations, IBundleCollectionCache cache, ExternalBundleGenerator externalBundleGenerator, ManifestValidator manifestValidator, CassetteSettings settings)
 {
     this.bundleConfigurations = bundleConfigurations;
     this.cache = cache;
     this.externalBundleGenerator = externalBundleGenerator;
     this.manifestValidator       = manifestValidator;
     this.settings = settings;
 }
Exemplo n.º 8
0
        public void CheckRequiredMods_WhenRequiresNothing_GetEmptyRequiredMods()
        {
            // Mod that requires no other mods.
            var standaloneMod = new QMod();

            var validator = new ManifestValidator();

            validator.CheckRequiredMods(standaloneMod);

            Assert.AreEqual(0, standaloneMod.RequiredMods.Count());
        }
        public void ValidereManifestMotXsdValiderer()
        {
            var arkiv = DomeneUtility.GetAsicEArkivEnkel();

            var manifestXml = arkiv.Manifest.Xml();

            var manifestValidering = new ManifestValidator();
            var validert           = manifestValidering.ValiderDokumentMotXsd(manifestXml.OuterXml);

            Assert.IsTrue(validert, manifestValidering.ValideringsVarsler);
        }
Exemplo n.º 10
0
        private static void ValiderArkivManifest(XmlDocument manifestXml)
        {
            const string preMessage = "Envelope validerer ikke: ";

            var manifestValidering = new ManifestValidator();
            var manifestValidert   = manifestValidering.ValiderDokumentMotXsd(manifestXml.OuterXml);

            if (!manifestValidert)
            {
                throw new XmlValidationException(preMessage + manifestValidering.ValideringsVarsler);
            }
        }
Exemplo n.º 11
0
        public ResponseBase <ManifestResponse> FindData(ManifestRequest request)
        {
            ManifestValidator validator;
            ValidationResult  results;
            ResponseBase <ManifestResponse> response;
            ManifestResponse manifestResponse;

            try
            {
                //throw new Exception("webeo");
                validator        = new ManifestValidator();
                results          = validator.Validate(request);
                manifestResponse = new ManifestResponse();

                if (results.IsValid)
                {
                    var queryResult = _context.TBL_MAN_MANIFEST.Where(x =>
                                                                      (x.VCH_DIRECTMASTERGUIDE == request.VCH_DIRECTMASTERGUIDE || request.VCH_DIRECTMASTERGUIDE == null) &&
                                                                      (x.DAT_DEPARTUREDATE >= request.DAT_STARTDATE || request.DAT_STARTDATE == null) && (x.DAT_DEPARTUREDATE <= request.DAT_ENDDATE || request.DAT_ENDDATE == null) &&
                                                                      (x.VCH_CONSIGNEE.Contains(request.VCH_CONSIGNEE) || request.VCH_CONSIGNEE == null) && (x.VCH_SHIPPER.Contains(request.VCH_SHIPPER) || request.VCH_SHIPPER == null) &&
                                                                      (x.VCH_DESCRIPTION.Contains(request.VCH_DESCRIPTION) || request.VCH_DESCRIPTION == null) && (x.VCH_AIRLINE.Contains(request.VCH_AIRLINE) || request.VCH_AIRLINE == null) &&
                                                                      (x.VCH_DESTINATION == request.VCH_DESTINATION || request.VCH_DESTINATION == null) &&
                                                                      ((x.DAT_DEPARTUREDATE.Value.Year == request.INT_YEAR && x.INT_WEEK >= request.INT_STARTWEEK && x.INT_WEEK <= request.INT_ENDWEEK) ||
                                                                       (request.INT_YEAR == null || request.INT_STARTWEEK == null || request.INT_ENDWEEK == null))).OrderByDescending(x => x.DAT_DEPARTUREDATE);

                    int pageCount     = queryResult.Count();
                    var listManifests = queryResult.Skip((request.INT_CURRENTPAGE - 1) * request.INT_LIMITPAGES).Take(request.INT_LIMITPAGES == 1000 ? pageCount : request.INT_LIMITPAGES).ToList();
                    manifestResponse.INT_TOTALREGISTERS = pageCount;
                    manifestResponse.INT_CURRENTPAGE    = request.INT_CURRENTPAGE;
                    manifestResponse.Manifests          = listManifests;

                    response = new UtilityResponse <ManifestResponse>().SetResponseBaseForObj(manifestResponse);
                }
                else
                {
                    response = new UtilityResponse <ManifestResponse>().SetResponseBaseFunctionalErrors(results);
                }
                return(response);
            }
            catch (Exception ex)
            {
                response = new UtilityResponse <ManifestResponse>().SetResponseBaseForException(ex);
                return(response);
            }
            finally
            {
                response  = null;
                validator = null;
                results   = null;
                _context.Database.Connection.Close();
            }
        }
Exemplo n.º 12
0
        public void FindPatchMethods_FetchPatchMethods()
        {
            var methodFinder = new ManifestValidator();

            methodFinder.FindPatchMethods(qmod);

            Assert.AreEqual(5, qmod.PatchMethods.Count);
            Assert.AreEqual(nameof(TestPatchClass.QPrePatch), qmod.PatchMethods[PatchingOrder.MetaPreInitialize].Method.Name);
            Assert.AreEqual(nameof(TestPatchClass.StandardPrePatch), qmod.PatchMethods[PatchingOrder.PreInitialize].Method.Name);
            Assert.AreEqual(nameof(TestPatchClass.QPatch), qmod.PatchMethods[PatchingOrder.NormalInitialize].Method.Name);
            Assert.AreEqual(nameof(TestPatchClass.StandardPostPatch), qmod.PatchMethods[PatchingOrder.PostInitialize].Method.Name);
            Assert.AreEqual(nameof(TestPatchClass.QPostPatch), qmod.PatchMethods[PatchingOrder.MetaPostInitialize].Method.Name);
        }
Exemplo n.º 13
0
        public void TestDependencies_Multiple_Mod_Dependencies_ConfirmCorrectOrder()
        {
            var validator = new ManifestValidator();
            var tree      = new SortedCollection <string, QMod>();

            var st = new QMod
            {
                Id           = "SpecialtyManifold",
                Dependencies = new[] { "NitrogenMod", "ScubaManifold" }
            };

            var no2 = new QMod
            {
                Id           = "NitrogenMod",
                Dependencies = new[] { "SMLHelper" }
            };

            var sm = new QMod
            {
                Id           = "ScubaManifold",
                Dependencies = new[] { "SMLHelper" }
            };

            var sml = new QMod
            {
                Id = "SMLHelper"
            };

            validator.CheckRequiredMods(st);
            validator.CheckRequiredMods(no2);
            validator.CheckRequiredMods(sm);
            validator.CheckRequiredMods(sml);

            tree.AddSorted(st);
            tree.AddSorted(no2);
            tree.AddSorted(sm);
            tree.AddSorted(sml);

            List <QMod> list = tree.GetSortedList();

            Console.WriteLine(ListToString(list));

            Assert.AreEqual(4, list.Count);
            Assert.AreEqual("SpecialtyManifold", list[0].Id);
            Assert.AreEqual("ScubaManifold", list[1].Id);
            Assert.AreEqual("NitrogenMod", list[2].Id);
            Assert.AreEqual("SMLHelper", list[3].Id);
        }
Exemplo n.º 14
0
        private static void ValidateSymbolPackage(PackageArchiveReader symbolPackage, PackageMetadata metadata)
        {
            PackageHelper.ValidateNuGetPackageMetadata(metadata);

            // Validate nuspec manifest.
            var errors = ManifestValidator.Validate(symbolPackage.GetNuspec(), out var nuspec, out var packageMetadata).ToArray();

            if (errors.Length > 0)
            {
                var errorsString = string.Join("', '", errors.Select(error => error.ErrorMessage));
                throw new InvalidDataException(string.Format(
                                                   CultureInfo.CurrentCulture,
                                                   errors.Length > 1 ? Strings.UploadPackage_InvalidNuspecMultiple : Strings.UploadPackage_InvalidNuspec,
                                                   errorsString));
            }

            // Validate that the PII is not embedded in nuspec
            var invalidItems = new List <string>();

            if (metadata.Authors != null &&
                (metadata.Authors.Count > 1 ||
                 !string.IsNullOrWhiteSpace(metadata.Authors.FirstOrDefault())))
            {
                invalidItems.Add("Authors");
            }

            if (metadata.Owners != null && metadata.Owners.Any())
            {
                invalidItems.Add("Owners");
            }

            if (invalidItems.Any())
            {
                throw new InvalidDataException(string.Format(Strings.SymbolsPackage_InvalidDataInNuspec, string.Join(",", invalidItems.ToArray())));
            }

            if (!CheckForAllowedFiles(symbolPackage))
            {
                throw new InvalidDataException(string.Format(Strings.SymbolsPackage_InvalidFiles, PDBExtension));
            }

            if (!CheckForPDBFiles(symbolPackage))
            {
                throw new InvalidDataException(string.Format(Strings.SymbolsPackage_NoSymbols));
            }
        }
Exemplo n.º 15
0
        public void CheckRequiredMods_WhenRequiresIdOnly_GetExpectedRequiredMod()
        {
            const string requiredMod        = "SMLHelper";
            var          simpleDependentMod = new QMod
            {
                // Mod that requires one other mod, only by ID.
                Dependencies = new[] { requiredMod }
            };

            var validator = new ManifestValidator();

            validator.CheckRequiredMods(simpleDependentMod);

            Assert.AreEqual(1, simpleDependentMod.RequiredMods.Count());

            RequiredQMod expected = new RequiredQMod(requiredMod);
            RequiredQMod actual   = simpleDependentMod.RequiredMods.First();

            Assert.AreEqual(requiredMod, actual.Id);
            Assert.AreEqual(expected.RequiresMinimumVersion, actual.RequiresMinimumVersion);
            Assert.AreEqual(expected.MinimumVersion, actual.MinimumVersion);
        }
Exemplo n.º 16
0
        public void CheckRequiredMods_WhenRequirementsMixed_GetExpectedRequiredMods()
        {
            const string requiredModA           = "SMLHelper";
            const string requiredModB           = "MoreCyclopsUpgrades";
            const string requiredVersionBString = "8.6.7";

            var versionDependentMod = new QMod
            {
                // Mod that requires one mod by id only and another at a minimum verison.
                Dependencies        = new[] { requiredModA },
                VersionDependencies = new Dictionary <string, string>
                {
                    { requiredModB, requiredVersionBString }
                }
            };

            var validator = new ManifestValidator();

            validator.CheckRequiredMods(versionDependentMod);

            Assert.AreEqual(2, versionDependentMod.RequiredMods.Count());

            RequiredQMod expectedA = new RequiredQMod(requiredModA);
            RequiredQMod actualA   = versionDependentMod.RequiredMods.ElementAt(0);

            Assert.AreEqual(requiredModA, actualA.Id);
            Assert.AreEqual(expectedA.RequiresMinimumVersion, actualA.RequiresMinimumVersion);
            Assert.AreEqual(expectedA.MinimumVersion, actualA.MinimumVersion);

            RequiredQMod expectedB = new RequiredQMod(requiredModB, requiredVersionBString);
            RequiredQMod actualB   = versionDependentMod.RequiredMods.ElementAt(1);

            Assert.AreEqual(requiredModB, actualB.Id);
            Assert.AreEqual(expectedB.RequiresMinimumVersion, actualB.RequiresMinimumVersion);
            Assert.AreEqual(expectedB.MinimumVersion, actualB.MinimumVersion);
        }
Exemplo n.º 17
0
        private async Task <ActionResult> CreatePackageInternal()
        {
            var policyResult = await SecurityPolicyService.EvaluateAsync(SecurityPolicyAction.PackagePush, HttpContext);

            if (!policyResult.Success)
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, policyResult.ErrorMessage));
            }

            // Get the user
            var currentUser = GetCurrentUser();

            using (var packageStream = ReadPackageFromRequest())
            {
                try
                {
                    using (var archive = new ZipArchive(packageStream, ZipArchiveMode.Read, leaveOpen: true))
                    {
                        var reference = DateTime.UtcNow.AddDays(1); // allow "some" clock skew

                        var entryInTheFuture = archive.Entries.FirstOrDefault(
                            e => e.LastWriteTime.UtcDateTime > reference);

                        if (entryInTheFuture != null)
                        {
                            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, string.Format(
                                                                        CultureInfo.CurrentCulture,
                                                                        Strings.PackageEntryFromTheFuture,
                                                                        entryInTheFuture.Name)));
                        }
                    }

                    using (var packageToPush = new PackageArchiveReader(packageStream, leaveStreamOpen: false))
                    {
                        try
                        {
                            PackageService.EnsureValid(packageToPush);
                        }
                        catch (Exception ex)
                        {
                            ex.Log();

                            var message = Strings.FailedToReadUploadFile;
                            if (ex is InvalidPackageException || ex is InvalidDataException || ex is EntityException)
                            {
                                message = ex.Message;
                            }

                            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, message));
                        }

                        NuspecReader nuspec;
                        var          errors = ManifestValidator.Validate(packageToPush.GetNuspec(), out nuspec).ToArray();
                        if (errors.Length > 0)
                        {
                            var errorsString = string.Join("', '", errors.Select(error => error.ErrorMessage));
                            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, string.Format(
                                                                        CultureInfo.CurrentCulture,
                                                                        errors.Length > 1 ? Strings.UploadPackage_InvalidNuspecMultiple : Strings.UploadPackage_InvalidNuspec,
                                                                        errorsString)));
                        }

                        if (nuspec.GetMinClientVersion() > Constants.MaxSupportedMinClientVersion)
                        {
                            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, string.Format(
                                                                        CultureInfo.CurrentCulture,
                                                                        Strings.UploadPackage_MinClientVersionOutOfRange,
                                                                        nuspec.GetMinClientVersion())));
                        }

                        User owner;

                        // Ensure that the user can push packages for this partialId.
                        var id                  = nuspec.GetId();
                        var version             = nuspec.GetVersion();
                        var packageRegistration = PackageService.FindPackageRegistrationById(id);
                        if (packageRegistration == null)
                        {
                            // Check if the current user's scopes allow pushing a new package ID
                            var apiScopeEvaluationResult = EvaluateApiScope(ActionsRequiringPermissions.UploadNewPackageId, new ActionOnNewPackageContext(id, ReservedNamespaceService), NuGetScopes.PackagePush);
                            owner = apiScopeEvaluationResult.Owner;
                            if (!apiScopeEvaluationResult.IsSuccessful())
                            {
                                // User cannot push a new package ID as the current user's scopes does not allow it
                                return(GetHttpResultFromFailedApiScopeEvaluationForPush(apiScopeEvaluationResult, id, version));
                            }
                        }
                        else
                        {
                            // Check if the current user's scopes allow pushing a new version of an existing package ID
                            var apiScopeEvaluationResult = EvaluateApiScope(ActionsRequiringPermissions.UploadNewPackageVersion, packageRegistration, NuGetScopes.PackagePushVersion, NuGetScopes.PackagePush);
                            owner = apiScopeEvaluationResult.Owner;
                            if (!apiScopeEvaluationResult.IsSuccessful())
                            {
                                // User cannot push a package as the current user's scopes does not allow it
                                await AuditingService.SaveAuditRecordAsync(
                                    new FailedAuthenticatedOperationAuditRecord(
                                        currentUser.Username,
                                        AuditedAuthenticatedOperationAction.PackagePushAttemptByNonOwner,
                                        attemptedPackage : new AuditedPackageIdentifier(
                                            id, version.ToNormalizedStringSafe())));

                                return(GetHttpResultFromFailedApiScopeEvaluationForPush(apiScopeEvaluationResult, id, version));
                            }

                            if (packageRegistration.IsLocked)
                            {
                                return(new HttpStatusCodeWithBodyResult(
                                           HttpStatusCode.Forbidden,
                                           string.Format(CultureInfo.CurrentCulture, Strings.PackageIsLocked, packageRegistration.Id)));
                            }

                            // Check if a particular Id-Version combination already exists. We eventually need to remove this check.
                            string normalizedVersion = version.ToNormalizedString();
                            bool   packageExists     =
                                packageRegistration.Packages.Any(
                                    p => string.Equals(
                                        p.NormalizedVersion,
                                        normalizedVersion,
                                        StringComparison.OrdinalIgnoreCase));

                            if (packageExists)
                            {
                                return(new HttpStatusCodeWithBodyResult(
                                           HttpStatusCode.Conflict,
                                           string.Format(CultureInfo.CurrentCulture, Strings.PackageExistsAndCannotBeModified,
                                                         id, nuspec.GetVersion().ToNormalizedStringSafe())));
                            }
                        }

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

                        var package = await PackageUploadService.GeneratePackageAsync(
                            id,
                            packageToPush,
                            packageStreamMetadata,
                            owner,
                            currentUser);

                        await AutoCuratePackage.ExecuteAsync(package, packageToPush, commitChanges : false);

                        PackageCommitResult commitResult;
                        using (Stream uploadStream = packageStream)
                        {
                            uploadStream.Position = 0;
                            commitResult          = await PackageUploadService.CommitPackageAsync(
                                package,
                                uploadStream.AsSeekableStream());
                        }

                        switch (commitResult)
                        {
                        case PackageCommitResult.Success:
                            break;

                        case PackageCommitResult.Conflict:
                            return(new HttpStatusCodeWithBodyResult(
                                       HttpStatusCode.Conflict,
                                       Strings.UploadPackage_IdVersionConflict));

                        default:
                            throw new NotImplementedException($"The package commit result {commitResult} is not supported.");
                        }

                        IndexingService.UpdatePackage(package);

                        // Write an audit record
                        await AuditingService.SaveAuditRecordAsync(
                            new PackageAuditRecord(package, AuditedPackageAction.Create, PackageCreatedVia.Api));

                        if (!(ConfigurationService.Current.AsynchronousPackageValidationEnabled && ConfigurationService.Current.BlockingAsynchronousPackageValidationEnabled))
                        {
                            // Notify user of push unless async validation in blocking mode is used
                            MessageService.SendPackageAddedNotice(package,
                                                                  Url.Package(package.PackageRegistration.Id, package.NormalizedVersion, relativeUrl: false),
                                                                  Url.ReportPackage(package.PackageRegistration.Id, package.NormalizedVersion, relativeUrl: false),
                                                                  Url.AccountSettings(relativeUrl: false));
                        }

                        TelemetryService.TrackPackagePushEvent(package, currentUser, User.Identity);

                        if (package.SemVerLevelKey == SemVerLevelKey.SemVer2)
                        {
                            return(new HttpStatusCodeWithServerWarningResult(HttpStatusCode.Created, Strings.WarningSemVer2PackagePushed));
                        }

                        return(new HttpStatusCodeResult(HttpStatusCode.Created));
                    }
                }
                catch (InvalidPackageException ex)
                {
                    return(BadRequestForExceptionMessage(ex));
                }
                catch (InvalidDataException ex)
                {
                    return(BadRequestForExceptionMessage(ex));
                }
                catch (EntityException ex)
                {
                    return(BadRequestForExceptionMessage(ex));
                }
                catch (FrameworkException ex)
                {
                    return(BadRequestForExceptionMessage(ex));
                }
            }
        }
Exemplo n.º 18
0
        public virtual async Task <ActionResult> UploadPackage(HttpPostedFileBase uploadFile)
        {
            var currentUser = GetCurrentUser();

            using (var existingUploadFile = await _uploadFileService.GetUploadFileAsync(currentUser.Key))
            {
                if (existingUploadFile != null)
                {
                    return(new HttpStatusCodeResult(409, "Cannot upload file because an upload is already in progress."));
                }
            }

            if (uploadFile == null)
            {
                ModelState.AddModelError(String.Empty, Strings.UploadFileIsRequired);
                return(View());
            }

            if (!Path.GetExtension(uploadFile.FileName).Equals(Constants.NuGetPackageFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                ModelState.AddModelError(String.Empty, Strings.UploadFileMustBeNuGetPackage);
                return(View());
            }

            using (var uploadStream = uploadFile.InputStream)
            {
                INupkg nuGetPackage;
                try
                {
                    nuGetPackage = CreatePackage(uploadStream);
                }
                catch (InvalidPackageException ipex)
                {
                    ipex.Log();
                    ModelState.AddModelError(String.Empty, ipex.Message);
                    return(View());
                }
                catch (Exception ex)
                {
                    ex.Log();
                    ModelState.AddModelError(String.Empty, Strings.FailedToReadUploadFile);
                    return(View());
                }
                finally
                {
                    _cacheService.RemoveProgress(currentUser.Username);
                }

                var errors = ManifestValidator.Validate(nuGetPackage).ToArray();
                if (errors.Length > 0)
                {
                    foreach (var error in errors)
                    {
                        ModelState.AddModelError(String.Empty, error.ErrorMessage);
                    }
                    return(View());
                }

                // Check min client version
                if (nuGetPackage.Metadata.MinClientVersion > typeof(Manifest).Assembly.GetName().Version)
                {
                    ModelState.AddModelError(
                        String.Empty,
                        String.Format(
                            CultureInfo.CurrentCulture,
                            Strings.UploadPackage_MinClientVersionOutOfRange,
                            nuGetPackage.Metadata.MinClientVersion));
                    return(View());
                }

                var packageRegistration = _packageService.FindPackageRegistrationById(nuGetPackage.Metadata.Id);
                if (packageRegistration != null && !packageRegistration.Owners.AnySafe(x => x.Key == currentUser.Key))
                {
                    ModelState.AddModelError(
                        String.Empty, String.Format(CultureInfo.CurrentCulture, Strings.PackageIdNotAvailable, packageRegistration.Id));
                    return(View());
                }

                var package = _packageService.FindPackageByIdAndVersion(nuGetPackage.Metadata.Id, nuGetPackage.Metadata.Version.ToStringSafe());
                if (package != null)
                {
                    ModelState.AddModelError(
                        String.Empty,
                        String.Format(
                            CultureInfo.CurrentCulture, Strings.PackageExistsAndCannotBeModified, package.PackageRegistration.Id, package.Version));
                    return(View());
                }

                await _uploadFileService.SaveUploadFileAsync(currentUser.Key, nuGetPackage.GetStream());
            }

            return(RedirectToRoute(RouteName.VerifyPackage));
        }
Exemplo n.º 19
0
        private async Task <ActionResult> CreatePackageInternal()
        {
            // Get the user
            var user = GetCurrentUser();

            using (var packageStream = ReadPackageFromRequest())
            {
                try
                {
                    using (var archive = new ZipArchive(packageStream, ZipArchiveMode.Read, leaveOpen: true))
                    {
                        var reference = DateTime.UtcNow.AddDays(1); // allow "some" clock skew

                        var entryInTheFuture = archive.Entries.FirstOrDefault(
                            e => e.LastWriteTime.UtcDateTime > reference);

                        if (entryInTheFuture != null)
                        {
                            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, string.Format(
                                                                        CultureInfo.CurrentCulture,
                                                                        Strings.PackageEntryFromTheFuture,
                                                                        entryInTheFuture.Name)));
                        }
                    }

                    using (var packageToPush = new PackageArchiveReader(packageStream, leaveStreamOpen: false))
                    {
                        try
                        {
                            PackageService.EnsureValid(packageToPush);
                        }
                        catch (Exception ex)
                        {
                            ex.Log();

                            var message = Strings.FailedToReadUploadFile;
                            if (ex is InvalidPackageException || ex is InvalidDataException || ex is EntityException)
                            {
                                message = ex.Message;
                            }

                            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, message));
                        }

                        NuspecReader nuspec;
                        var          errors = ManifestValidator.Validate(packageToPush.GetNuspec(), out nuspec).ToArray();
                        if (errors.Length > 0)
                        {
                            var errorsString = string.Join("', '", errors.Select(error => error.ErrorMessage));
                            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, string.Format(
                                                                        CultureInfo.CurrentCulture,
                                                                        errors.Length > 1 ? Strings.UploadPackage_InvalidNuspecMultiple : Strings.UploadPackage_InvalidNuspec,
                                                                        errorsString)));
                        }

                        if (nuspec.GetMinClientVersion() > Constants.MaxSupportedMinClientVersion)
                        {
                            return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, string.Format(
                                                                        CultureInfo.CurrentCulture,
                                                                        Strings.UploadPackage_MinClientVersionOutOfRange,
                                                                        nuspec.GetMinClientVersion())));
                        }

                        // Ensure that the user can push packages for this partialId.
                        var packageRegistration = PackageService.FindPackageRegistrationById(nuspec.GetId());
                        if (packageRegistration == null)
                        {
                            // Check if API key allows pushing a new package id
                            if (!ApiKeyScopeAllows(
                                    subject: nuspec.GetId(),
                                    requestedActions: NuGetScopes.PackagePush))
                            {
                                // User cannot push a new package ID as the API key scope does not allow it
                                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Unauthorized, Strings.ApiKeyNotAuthorized));
                            }
                        }
                        else
                        {
                            // Is the user allowed to push this Id?
                            if (!packageRegistration.IsOwner(user))
                            {
                                // Audit that a non-owner tried to push the package
                                await AuditingService.SaveAuditRecord(
                                    new FailedAuthenticatedOperationAuditRecord(
                                        user.Username,
                                        AuditedAuthenticatedOperationAction.PackagePushAttemptByNonOwner,
                                        attemptedPackage : new AuditedPackageIdentifier(
                                            nuspec.GetId(), nuspec.GetVersion().ToNormalizedStringSafe())));

                                // User cannot push a package to an ID owned by another user.
                                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Conflict,
                                                                        string.Format(CultureInfo.CurrentCulture, Strings.PackageIdNotAvailable,
                                                                                      nuspec.GetId())));
                            }

                            // Check if API key allows pushing the current package id
                            if (!ApiKeyScopeAllows(
                                    packageRegistration.Id,
                                    NuGetScopes.PackagePushVersion, NuGetScopes.PackagePush))
                            {
                                // User cannot push a package as the API key scope does not allow it
                                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Unauthorized, Strings.ApiKeyNotAuthorized));
                            }

                            // Check if a particular Id-Version combination already exists. We eventually need to remove this check.
                            string normalizedVersion = nuspec.GetVersion().ToNormalizedString();
                            bool   packageExists     =
                                packageRegistration.Packages.Any(
                                    p => string.Equals(
                                        p.NormalizedVersion,
                                        normalizedVersion,
                                        StringComparison.OrdinalIgnoreCase));

                            if (packageExists)
                            {
                                return(new HttpStatusCodeWithBodyResult(
                                           HttpStatusCode.Conflict,
                                           string.Format(CultureInfo.CurrentCulture, Strings.PackageExistsAndCannotBeModified,
                                                         nuspec.GetId(), nuspec.GetVersion().ToNormalizedStringSafe())));
                            }
                        }

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

                        var package = await PackageService.CreatePackageAsync(
                            packageToPush,
                            packageStreamMetadata,
                            user,
                            commitChanges : false);

                        await AutoCuratePackage.ExecuteAsync(package, packageToPush, commitChanges : false);

                        using (Stream uploadStream = packageStream)
                        {
                            uploadStream.Position = 0;

                            try
                            {
                                await PackageFileService.SavePackageFileAsync(package, uploadStream.AsSeekableStream());
                            }
                            catch (InvalidOperationException ex)
                            {
                                ex.Log();

                                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.Conflict, Strings.UploadPackage_IdVersionConflict));
                            }
                        }

                        try
                        {
                            await EntitiesContext.SaveChangesAsync();
                        }
                        catch
                        {
                            // If saving to the DB fails for any reason, we need to delete the package we just saved.
                            await PackageFileService.DeletePackageFileAsync(nuspec.GetId(), nuspec.GetVersion().ToNormalizedString());

                            throw;
                        }

                        IndexingService.UpdatePackage(package);

                        // Write an audit record
                        await AuditingService.SaveAuditRecord(
                            new PackageAuditRecord(package, AuditedPackageAction.Create, PackageCreatedVia.Api));

                        // Notify user of push
                        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));

                        return(new HttpStatusCodeResult(HttpStatusCode.Created));
                    }
                }
                catch (InvalidPackageException ex)
                {
                    return(BadRequestForExceptionMessage(ex));
                }
                catch (InvalidDataException ex)
                {
                    return(BadRequestForExceptionMessage(ex));
                }
                catch (EntityException ex)
                {
                    return(BadRequestForExceptionMessage(ex));
                }
                catch (FrameworkException ex)
                {
                    return(BadRequestForExceptionMessage(ex));
                }
            }
        }
Exemplo n.º 20
0
 public void SetUp()
 {
     _manifest  = TestHelpers.CreateManifest();
     _validator = new ManifestValidator();
 }