コード例 #1
0
        public async Task Restore_TamperedPackage_FailsAsync()
        {
            // Arrange
            var nupkg = new SimpleTestPackageContext("A", "1.0.0");

            using (var pathContext = new SimpleTestPathContext())
                using (var testCertificate = new X509Certificate2(_trustedTestCert.Source.Cert))
                {
                    // Set up solution, project, and packages
                    var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);

                    var projectA = SimpleTestProjectContext.CreateNETCore(
                        "a",
                        pathContext.SolutionRoot,
                        NuGetFramework.Parse("NETStandard2.0"));

                    var packageX          = new SimpleTestPackageContext("X", "9.0.0");
                    var signedPackagePath = await SignedArchiveTestUtility.AuthorSignPackageAsync(testCertificate, packageX, pathContext.PackageSource);

                    SignedArchiveTestUtility.TamperWithPackage(signedPackagePath);

                    projectA.AddPackageToAllFrameworks(packageX);
                    solution.Projects.Add(projectA);
                    solution.Create(pathContext.SolutionRoot);

                    var args = new string[]
                    {
                        projectA.ProjectPath,
                        "-Source",
                        pathContext.PackageSource
                    };

                    // Act
                    var result   = RunRestore(_nugetExePath, pathContext, expectedExitCode: 1, additionalArgs: args);
                    var reader   = new LockFileFormat();
                    var lockFile = reader.Read(projectA.AssetsFileOutputPath);
                    var errors   = lockFile.LogMessages.Where(m => m.Level == LogLevel.Error);
                    var warnings = lockFile.LogMessages.Where(m => m.Level == LogLevel.Warning);

                    // Assert
                    result.ExitCode.Should().Be(1);
                    result.Errors.Should().Contain(_NU3008);
                    result.AllOutput.Should().Contain($"WARNING: {_NU3027}");

                    errors.Count().Should().Be(1);
                    errors.First().Code.Should().Be(NuGetLogCode.NU3008);
                    errors.First().Message.Should().Be(_NU3008Message);
                    errors.First().LibraryId.Should().Be(packageX.ToString());

                    warnings.Count().Should().Be(1);
                    warnings.First().Code.Should().Be(NuGetLogCode.NU3027);
                    warnings.First().Message.Should().Be(_NU3027Message);
                    warnings.First().LibraryId.Should().Be("X.9.0.0");
                }
        }
コード例 #2
0
        public async Task MsbuildRestore_PackageSourceMappingPatternMatchesMultipleSources_Succeed()
        {
            // Arrange
            using (var pathContext = new SimpleTestPathContext())
            {
                // Set up solution, project, and packages
                var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);

                var net461 = NuGetFramework.Parse("net461");

                var projectA = new SimpleTestProjectContext(
                    "a",
                    ProjectStyle.PackagesConfig,
                    pathContext.SolutionRoot);
                projectA.Frameworks.Add(new SimpleTestProjectFrameworkContext(net461));
                var projectAPackages = Path.Combine(pathContext.SolutionRoot, "packages");

                solution.Projects.Add(projectA);
                solution.Create(pathContext.SolutionRoot);

                using (var writer = new StreamWriter(Path.Combine(Path.GetDirectoryName(projectA.ProjectPath), "packages.config")))
                {
                    writer.Write(
                        @"<packages>
  <package id=""Contoso.MVC.ASP"" version=""1.0.0"" targetFramework=""net461"" />
</packages>");
                }

                var sharedRepositoryPath1 = pathContext.UserPackagesFolder;
                Directory.CreateDirectory(sharedRepositoryPath1);

                var packageContosoMvcReal1 = new SimpleTestPackageContext()
                {
                    Id      = "Contoso.MVC.ASP",
                    Version = "1.0.0"
                };
                packageContosoMvcReal1.AddFile("lib/net461/realA1.dll");

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    sharedRepositoryPath1,
                    packageContosoMvcReal1);

                var sharedRepositoryPath2 = pathContext.UserPackagesFolder;
                Directory.CreateDirectory(sharedRepositoryPath2);

                var packageContosoMvcReal2 = new SimpleTestPackageContext()
                {
                    Id      = "Contoso.MVC.ASP",
                    Version = "1.0.0"
                };
                packageContosoMvcReal2.AddFile("lib/net461/realA2.dll");

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    sharedRepositoryPath2,
                    packageContosoMvcReal2);

                // SimpleTestPathContext adds a NuGet.Config with a repositoryPath,
                // so we go ahead and remove that config before running MSBuild.
                var configPath = Path.Combine(Path.GetDirectoryName(pathContext.SolutionRoot), "NuGet.Config");
                var configText =
                    $@"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
    <packageSources>
    <!--To inherit the global NuGet package sources remove the <clear/> line below -->
    <clear />
    <add key=""SharedRepository1"" value=""{sharedRepositoryPath1}"" />
    <add key=""SharedRepository2"" value=""{sharedRepositoryPath2}"" />
    </packageSources>
    <packageSourceMapping>
        <packageSource key=""SharedRepository1"">
            <package pattern=""Contoso.MVC.*"" /> <!--Same package source mapping prefix matches both repository -->
        </packageSource>
        <packageSource key=""SharedRepository2"">
            <package pattern=""Contoso.MVC.*"" /> <!--Same package source mapping prefix matches both repository -->
        </packageSource>
    </packageSourceMapping>
</configuration>";
                using (var writer = new StreamWriter(configPath))
                {
                    writer.Write(configText);
                }

                // Act
                var result = _msbuildFixture.RunMsBuild(pathContext.WorkingDirectory, $"/t:restore {pathContext.SolutionRoot} /p:RestorePackagesConfig=true", ignoreExitCode: true);

                // Assert
                Assert.True(result.ExitCode == 0);
                var contosoRestorePath = Path.Combine(projectAPackages, packageContosoMvcReal1.ToString(), packageContosoMvcReal1.ToString() + ".nupkg");
                using (var nupkgReader = new PackageArchiveReader(contosoRestorePath))
                {
                    var allFiles = nupkgReader.GetFiles().ToList();
                    // Assert correct Contoso package was restored.
                    Assert.True(allFiles.Contains("lib/net461/realA1.dll") || allFiles.Contains("lib/net461/realA2.dll"));
                }
            }
        }
コード例 #3
0
        public async Task MsbuildRestore_PackageSourceMappingLongerMatches_Succeed()
        {
            // Arrange
            using (var pathContext = new SimpleTestPathContext())
            {
                // Set up solution, project, and packages
                var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);

                var net461 = NuGetFramework.Parse("net461");

                var projectA = new SimpleTestProjectContext(
                    "a",
                    ProjectStyle.PackagesConfig,
                    pathContext.SolutionRoot);
                projectA.Frameworks.Add(new SimpleTestProjectFrameworkContext(net461));
                var projectAPackages = Path.Combine(pathContext.SolutionRoot, "packages");

                solution.Projects.Add(projectA);
                solution.Create(pathContext.SolutionRoot);

                using (var writer = new StreamWriter(Path.Combine(Path.GetDirectoryName(projectA.ProjectPath), "packages.config")))
                {
                    writer.Write(
                        @"<packages>
  <package id=""Contoso.MVC.ASP"" version=""1.0.0"" targetFramework=""net461"" />
  <package id=""Contoso.Opensource.Buffers"" version=""1.0.0"" targetFramework=""net461"" />
</packages>");
                }

                var opensourceRepositoryPath = pathContext.PackageSource;
                Directory.CreateDirectory(opensourceRepositoryPath);

                var packageOpenSourceContosoMvc = new SimpleTestPackageContext()
                {
                    Id      = "Contoso.MVC.ASP", // Package Id conflict with internally created package
                    Version = "1.0.0"
                };
                packageOpenSourceContosoMvc.AddFile("lib/net461/openA.dll");

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    opensourceRepositoryPath,
                    packageOpenSourceContosoMvc);

                var packageContosoBuffersOpenSource = new SimpleTestPackageContext()
                {
                    Id      = "Contoso.Opensource.Buffers",
                    Version = "1.0.0"
                };
                packageContosoBuffersOpenSource.AddFile("lib/net461/openA.dll");

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    opensourceRepositoryPath,
                    packageContosoBuffersOpenSource);

                var sharedRepositoryPath = pathContext.UserPackagesFolder;
                Directory.CreateDirectory(sharedRepositoryPath);

                var packageContosoMvcReal = new SimpleTestPackageContext()
                {
                    Id      = "Contoso.MVC.ASP",
                    Version = "1.0.0"
                };
                packageContosoMvcReal.AddFile("lib/net461/realA.dll");

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    sharedRepositoryPath,
                    packageContosoMvcReal);

                // SimpleTestPathContext adds a NuGet.Config with a repositoryPath,
                // so we go ahead and remove that config before running MSBuild.
                var configPath = Path.Combine(Path.GetDirectoryName(pathContext.SolutionRoot), "NuGet.Config");
                var configText =
                    $@"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
    <packageSources>
    <!--To inherit the global NuGet package sources remove the <clear/> line below -->
    <clear />
    <add key=""PublicRepository"" value=""{opensourceRepositoryPath}"" />
    <add key=""SharedRepository"" value=""{sharedRepositoryPath}"" />
    </packageSources>
    <packageSourceMapping>
        <packageSource key=""PublicRepository"">
            <package pattern=""Contoso.Opensource.*"" />
            <package pattern=""Contoso.MVC.*"" />
        </packageSource>
        <packageSource key=""SharedRepository"">
            <package pattern=""Contoso.MVC.ASP"" />   <!-- Longer prefix prevails over Contoso.MVC.* -->
        </packageSource>
    </packageSourceMapping>
</configuration>";

                using (var writer = new StreamWriter(configPath))
                {
                    writer.Write(configText);
                }

                // Act
                var result = _msbuildFixture.RunMsBuild(pathContext.WorkingDirectory, $"/t:restore -v:d {pathContext.SolutionRoot} /p:RestorePackagesConfig=true", ignoreExitCode: true);

                // Assert
                Assert.True(result.ExitCode == 0);
                var contosoRestorePath = Path.Combine(projectAPackages, packageOpenSourceContosoMvc.ToString(), packageOpenSourceContosoMvc.ToString() + ".nupkg");
                using (var nupkgReader = new PackageArchiveReader(contosoRestorePath))
                {
                    var allFiles = nupkgReader.GetFiles().ToList();
                    // Assert correct Contoso package was restored.
                    Assert.Contains("lib/net461/realA.dll", allFiles);
                }

                Assert.True(result.ExitCode == 0);
                Assert.Contains("Package source mapping matches found for package ID 'Contoso.MVC.ASP' are: 'SharedRepository'", result.Output);
            }
        }
コード例 #4
0
        public async Task MsbuildRestore_PackageSourceMappingPartial_Fails()
        {
            // Arrange
            using (var pathContext = new SimpleTestPathContext())
            {
                // Set up solution, project, and packages
                var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);

                var net461 = NuGetFramework.Parse("net461");

                var projectA = new SimpleTestProjectContext(
                    "a",
                    ProjectStyle.PackagesConfig,
                    pathContext.SolutionRoot);
                projectA.Frameworks.Add(new SimpleTestProjectFrameworkContext(net461));
                var projectAPackages = Path.Combine(pathContext.SolutionRoot, "packages");

                solution.Projects.Add(projectA);
                solution.Create(pathContext.SolutionRoot);

                using (var writer = new StreamWriter(Path.Combine(Path.GetDirectoryName(projectA.ProjectPath), "packages.config")))
                {
                    writer.Write(
                        @"<packages>
<package id=""Contoso.MVC.ASP"" version=""1.0.0"" targetFramework=""net461"" />
<package id=""Contoso.Opensource.Buffers"" version=""1.0.0"" targetFramework=""net461"" />
</packages>");
                }

                var opensourceRepositoryPath = pathContext.PackageSource;
                Directory.CreateDirectory(opensourceRepositoryPath);

                var packageOpenSourceContosoMvc = new SimpleTestPackageContext()
                {
                    Id      = "Contoso.MVC.ASP", // Package Id conflict with internally created package
                    Version = "1.0.0"
                };
                packageOpenSourceContosoMvc.AddFile("lib/net461/openA.dll");

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    opensourceRepositoryPath,
                    packageOpenSourceContosoMvc);

                var packageContosoBuffersOpenSource = new SimpleTestPackageContext()
                {
                    Id      = "Contoso.Opensource.Buffers",
                    Version = "1.0.0"
                };
                packageContosoBuffersOpenSource.AddFile("lib/net461/openA.dll");

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    opensourceRepositoryPath,
                    packageContosoBuffersOpenSource);

                var sharedRepositoryPath = pathContext.UserPackagesFolder;
                Directory.CreateDirectory(sharedRepositoryPath);

                // SimpleTestPathContext adds a NuGet.Config with a repositoryPath,
                // so we go ahead and remove that config before running MSBuild.
                var configPath = Path.Combine(Path.GetDirectoryName(pathContext.SolutionRoot), "NuGet.Config");
                var configText =
                    $@"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<packageSources>
<!--To inherit the global NuGet package sources remove the <clear/> line below -->
<clear />
<add key=""PublicRepository"" value=""{opensourceRepositoryPath}"" />
<add key=""SharedRepository"" value=""{sharedRepositoryPath}"" />
</packageSources>
<packageSourceMapping>
    <packageSource key=""PublicRepository"">
        <package pattern=""Contoso.O*"" />
    </packageSource>
    <packageSource key=""SharedRepository"">
        <package pattern=""Contoso.M*"" />  <!--Contoso.MVC.ASP package doesn't exist in this repostiry, so it'll fail to restore -->
    </packageSource>
</packageSourceMapping>
</configuration>";
                using (var writer = new StreamWriter(configPath))
                {
                    writer.Write(configText);
                }

                // Act
                var result = _msbuildFixture.RunMsBuild(pathContext.WorkingDirectory, $"/t:restore {pathContext.SolutionRoot} /p:RestorePackagesConfig=true", ignoreExitCode: true);

                // Assert
                Assert.True(result.ExitCode == 1);
                var packageContosoBuffersPath = Path.Combine(projectAPackages, packageContosoBuffersOpenSource.ToString(), packageContosoBuffersOpenSource.ToString() + ".nupkg");
                Assert.True(File.Exists(packageContosoBuffersPath));
                // Assert Contoso.MVC.ASP is not restored.
                Assert.True(result.Output.Contains("Unable to find version '1.0.0' of package 'Contoso.MVC.ASP'."));
                var packageContosoMvcPath = Path.Combine(projectAPackages, packageOpenSourceContosoMvc.ToString(), packageOpenSourceContosoMvc.ToString() + ".nupkg");
                Assert.False(File.Exists(packageContosoMvcPath));
            }
        }
コード例 #5
0
        public async Task Restore_PackageWithCompressedSignature_RequireMode_FailsAndDoesNotExpandAsync()
        {
            // Arrange
            var packageX = new SimpleTestPackageContext();

            using (var pathContext = new SimpleTestPathContext())
                using (var packageStream = await packageX.CreateAsStreamAsync())
                    using (var testCertificate = new X509Certificate2(_trustedTestCert.Source.Cert))
                    {
                        var signature = await SignedArchiveTestUtility.CreateAuthorSignatureForPackageAsync(testCertificate, packageStream);

                        using (var package = new ZipArchive(packageStream, ZipArchiveMode.Update, leaveOpen: true))
                        {
                            var signatureEntry = package.CreateEntry(SigningSpecifications.V1.SignaturePath);
                            using (var signatureStream = new MemoryStream(signature.GetBytes()))
                                using (var signatureEntryStream = signatureEntry.Open())
                                {
                                    signatureStream.CopyTo(signatureEntryStream);
                                }
                        }

                        var packagePath = Path.Combine(pathContext.PackageSource, $"{packageX.ToString()}.nupkg");
                        packageStream.Seek(offset: 0, loc: SeekOrigin.Begin);

                        using (var fileStream = File.OpenWrite(packagePath))
                        {
                            packageStream.CopyTo(fileStream);
                        }

                        // Set up solution, project, and packages
                        var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);

                        var propsFile = Path.Combine(pathContext.SolutionRoot, "NuGet.Config");

                        using (var stream = File.OpenWrite(propsFile))
                            using (var textWritter = new StreamWriter(stream))
                            {
                                textWritter.Write(@"<configuration><config><add key=""signatureValidationMode"" value=""require"" /></config></configuration>");
                            }

                        var projectA = SimpleTestProjectContext.CreateNETCore(
                            "a",
                            pathContext.SolutionRoot,
                            NuGetFramework.Parse("NETStandard2.0"));

                        projectA.AddPackageToAllFrameworks(packageX);
                        solution.Projects.Add(projectA);
                        solution.Create(pathContext.SolutionRoot);

                        var args = new string[]
                        {
                            projectA.ProjectPath
                        };

                        // Act
                        var result          = RunRestore(_nugetExePath, pathContext, expectedExitCode: 1, additionalArgs: args);
                        var assetFileReader = new LockFileFormat();
                        var assetsFile      = assetFileReader.Read(projectA.AssetsFileOutputPath);
                        var errors          = assetsFile.LogMessages.Where(m => m.Level == LogLevel.Error);
                        var warnings        = assetsFile.LogMessages.Where(m => m.Level == LogLevel.Warning);

                        // Assert
                        result.ExitCode.Should().Be(1);
                        result.Errors.Should().Contain(string.Format(_NU3005, SigningTestUtility.AddSignatureLogPrefix(_NU3005CompressedMessage, packageX.Identity, pathContext.PackageSource)));

                        errors.Count().Should().Be(1);
                        errors.First().Code.Should().Be(NuGetLogCode.NU3005);
                        errors.First().Message.Should().Be(SigningTestUtility.AddSignatureLogPrefix(_NU3005CompressedMessage, packageX.Identity, pathContext.PackageSource));
                        errors.First().LibraryId.Should().Be(packageX.Identity.Id.ToString());

                        warnings.Count().Should().Be(0);

                        var installedPackageDir = Path.Combine(pathContext.UserPackagesFolder, packageX.Identity.Id);
                        Directory.Exists(installedPackageDir).Should().BeFalse();
                    }
        }
コード例 #6
0
        public async Task Restore_PackageSourceMapping_Succeed()
        {
            // Arrange
            using (var pathContext = new SimpleTestPathContext())
            {
                // Set up solution, project, and packages
                var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);

                var net461 = NuGetFramework.Parse("net461");

                var projectA = SimpleTestProjectContext.CreateLegacyPackageReference(
                    "a",
                    pathContext.SolutionRoot,
                    net461);
                var projectAPackages = Path.Combine(pathContext.SolutionRoot, "packages");

                var externalRepositoryPath = Path.Combine(pathContext.SolutionRoot, "ExternalRepository");
                Directory.CreateDirectory(externalRepositoryPath);

                var contosoRepositoryPath = Path.Combine(pathContext.SolutionRoot, "ContosoRepository");
                Directory.CreateDirectory(contosoRepositoryPath);

                var configPath = Path.Combine(pathContext.WorkingDirectory, "nuget.config");
                SettingsTestUtils.CreateConfigurationFile(configPath, $@"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
    <packageSources>
    <!--To inherit the global NuGet package sources remove the <clear/> line below -->
    <clear />
    <add key=""ExternalRepository"" value=""{externalRepositoryPath}"" />
    <add key=""ContosoRepository"" value=""{contosoRepositoryPath}"" />
    </packageSources>
    <packageSourceMapping>
        <packageSource key=""externalRepository"">
            <package pattern=""External.*"" />
            <package pattern=""Others.*"" />
        </packageSource>
        <packageSource key=""contosoRepository"">
            <package pattern=""Contoso.*"" />
            <package pattern=""Test.*"" />
        </packageSource>
    </packageSourceMapping>
</configuration>");

                var ContosoReal = new SimpleTestPackageContext()
                {
                    Id      = "Contoso.A",
                    Version = "1.0.0"
                };
                ContosoReal.AddFile("lib/net461/contosoA.dll");

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    contosoRepositoryPath,
                    PackageSaveMode.Defaultv3,
                    ContosoReal);

                var ExternalA = new SimpleTestPackageContext()
                {
                    Id      = "Contoso.A", // Initial version had package id conflict with Contoso repository
                    Version = "1.0.0"
                };
                ExternalA.AddFile("lib/net461/externalA.dll");

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    externalRepositoryPath,
                    PackageSaveMode.Defaultv3,
                    ExternalA);

                var ExternalB = new SimpleTestPackageContext()
                {
                    Id      = "External.B", // name conflict resolved.
                    Version = "2.0.0"
                };
                ExternalB.AddFile("lib/net461/externalB.dll");

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    externalRepositoryPath,
                    PackageSaveMode.Defaultv3,
                    ExternalB);

                Util.CreateFile(Path.GetDirectoryName(projectA.ProjectPath), "packages.config",
                                @"<packages>
  <package id=""Contoso.A"" version=""1.0.0"" targetFramework=""net461"" />
  <package id=""External.B"" version=""2.0.0"" targetFramework=""net461"" />
</packages>");

                solution.Projects.Add(projectA);
                solution.Create(pathContext.SolutionRoot);

                // Act
                var result = RunRestore(pathContext, _successExitCode);

                // Assert
                var contosoRestorePath = Path.Combine(projectAPackages, ContosoReal.ToString(), ContosoReal.ToString() + ".nupkg");
                using (var nupkgReader = new PackageArchiveReader(contosoRestorePath))
                {
                    var allFiles = nupkgReader.GetFiles().ToList();
                    // Assert correct Contoso package from Contoso repository was restored.
                    Assert.Contains("lib/net461/contosoA.dll", allFiles);
                }
                var externalRestorePath = Path.Combine(projectAPackages, ExternalB.ToString(), ExternalB.ToString() + ".nupkg");
                Assert.True(File.Exists(externalRestorePath));
            }
        }