public void SourcesCommandTest_AddSource(string source, bool shouldWarn) { using (SimpleTestPathContext pathContext = new SimpleTestPathContext()) { TestDirectory workingPath = pathContext.WorkingDirectory; SimpleTestSettingsContext settings = pathContext.Settings; // Arrange string nugetexe = Util.GetNuGetExePath(); var args = new string[] { "sources", "Add", "-Name", "test_source", "-Source", source, "-ConfigFile", settings.ConfigPath }; // Act CommandRunnerResult result = CommandRunner.Run(nugetexe, workingPath, string.Join(" ", args), true); // Assert Assert.Equal(0, result.ExitCode); ISettings loadedSettings = Configuration.Settings.LoadDefaultSettings(workingPath, null, null); SettingSection packageSourcesSection = loadedSettings.GetSection("packageSources"); SourceItem sourceItem = packageSourcesSection?.GetFirstItemWithAttribute <SourceItem>("key", "test_source"); Assert.Equal(source, sourceItem.GetValueAsPath()); Assert.Equal(shouldWarn, result.Output.Contains("WARNING: You are running the 'add source' operation with an 'HTTP' source")); } }
public void Sources_WarnWhenAdding(string source, bool shouldWarn) { using (SimpleTestPathContext pathContext = new SimpleTestPathContext()) { TestDirectory workingPath = pathContext.WorkingDirectory; SimpleTestSettingsContext settings = pathContext.Settings; // Arrange var args = new string[] { "nuget", "add", "source", source, "--name", "test_source", "--configfile", settings.ConfigPath }; // Act CommandRunnerResult result = _fixture.RunDotnet(workingPath, string.Join(" ", args), ignoreExitCode: true); // Assert Assert.True(result.Success, result.Output + " " + result.Errors); ISettings loadedSettings = Settings.LoadDefaultSettings(root: workingPath, configFileName: null, machineWideSettings: null); SettingSection packageSourcesSection = loadedSettings.GetSection("packageSources"); SourceItem sourceItem = packageSourcesSection?.GetFirstItemWithAttribute <SourceItem>("key", "test_source"); Assert.Equal(source, sourceItem.GetValueAsPath()); Assert.Equal(shouldWarn, result.Output.Contains("warn : You are running the 'add source' operation with an 'HTTP' source")); } }
public void SetApiKey_DefaultSource() { using (var testFolder = TestDirectory.Create()) { var configFile = Path.Combine(testFolder, "nuget.config"); Util.CreateFile(configFile, "<configuration/>"); var testApiKey = Guid.NewGuid().ToString(); // Act var result = CommandRunner.Run( NuGetExePath, testFolder, $"setApiKey {testApiKey} -ConfigFile {configFile}", waitForExit: true); // Assert Assert.True(0 == result.ExitCode, $"{result.Output} {result.Errors}"); Assert.Contains($"The API Key '{testApiKey}' was saved for the NuGet gallery (https://www.nuget.org)", result.Output); Assert.DoesNotContain($"symbol", result.Output); var settings = Configuration.Settings.LoadDefaultSettings( Path.GetDirectoryName(configFile), Path.GetFileName(configFile), null); var actualApiKey = SettingsUtility.GetDecryptedValueForAddItem(settings, ConfigurationConstants.ApiKeys, NuGetConstants.DefaultGalleryServerUrl); Assert.NotNull(actualApiKey); Assert.Equal(testApiKey, actualApiKey); XElement apiKeySection = SimpleTestSettingsContext.GetOrAddSection(XmlUtility.Load(configFile), ConfigurationConstants.ApiKeys); Assert.Equal(1, apiKeySection.Elements().Count()); } }
public async Task Verify_RepositorySignedPackage_WithAuthorItemUntrustedCertificate_Fails(string allowUntrustedRoot, bool verifyCertificateFingerprint) { IX509StoreCertificate storeCertificate = _signFixture.UntrustedSelfIssuedCertificateInCertificateStore; // Arrange using (var pathContext = new SimpleTestPathContext()) { var nupkg = new SimpleTestPackageContext("A", "1.0.0"); string testDirectory = pathContext.WorkingDirectory; await SimpleTestPackageUtility.CreatePackagesAsync(testDirectory, nupkg); string packagePath = Path.Combine(testDirectory, nupkg.PackageName); //Act string certificateFingerprintString = SignatureTestUtility.GetFingerprint(storeCertificate.Certificate, HashAlgorithmName.SHA256); string repoServiceIndex = "https://serviceindex.test/v3/index.json"; string signedPackagePath = await SignedArchiveTestUtility.RepositorySignPackageAsync(storeCertificate.Certificate, packagePath, pathContext.PackageSource, new Uri(repoServiceIndex)); // Arrange string trustedSignersSectionContent = $@" <trustedSigners> <author name=""MyCert""> <certificate fingerprint=""{certificateFingerprintString}"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""{allowUntrustedRoot}"" /> </author> </trustedSigners> "; SimpleTestSettingsContext.AddSectionIntoNuGetConfig(pathContext.WorkingDirectory, trustedSignersSectionContent, "configuration"); string fingerprint = verifyCertificateFingerprint ? $"--certificate-fingerprint {certificateFingerprintString} --certificate-fingerprint def" : string.Empty; //Act CommandRunnerResult verifyResult = _msbuildFixture.RunDotnet( testDirectory, $"nuget verify {signedPackagePath} {fingerprint}", ignoreExitCode: true); // Assert verifyResult.Success.Should().BeFalse(because: verifyResult.AllOutput); verifyResult.AllOutput.Should().Contain(_noTimestamperWarningCode); verifyResult.AllOutput.Should().Contain(_noMatchingCertErrorCode); verifyResult.AllOutput.Should().Contain("This package is signed but not by a trusted signer."); if (bool.TryParse(allowUntrustedRoot, out bool parsed) && !parsed) { verifyResult.AllOutput.Should().Contain(_primarySignatureInvalidErrorCode); } else { verifyResult.AllOutput.Should().NotContain(_primarySignatureInvalidErrorCode); } } }
public async Task Verify_RepositorySignedPackage_WithRepositoryItemTrustedCertificate_AllowUntrustedRootSet_CorrectOwners_Succeeds(string allowUntrustedRoot, bool verifyCertificateFingerprint) { // Arrange IX509StoreCertificate storeCertificate = _signFixture.DefaultCertificate; using (var pathContext = new SimpleTestPathContext()) { var package = new SimpleTestPackageContext(); string certFingerprint = SignatureTestUtility.GetFingerprint(storeCertificate.Certificate, HashAlgorithmName.SHA256); var packageOwners = new List <string>() { "nuget", "contoso" }; string repoServiceIndex = "https://serviceindex.test/v3/index.json"; string signedPackagePath = await SignedArchiveTestUtility.RepositorySignPackageAsync( storeCertificate.Certificate, package, pathContext.PackageSource, new Uri(repoServiceIndex), timestampService : null, packageOwners); string testDirectory = pathContext.WorkingDirectory; string trustedSignersSectionContent = $@" <trustedSigners> <repository name=""NuGetTrust"" serviceIndex=""{repoServiceIndex}""> <certificate fingerprint=""{certFingerprint}"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""{allowUntrustedRoot}"" /> <owners>nuget;Contoso</owners> </repository> </trustedSigners> "; SimpleTestSettingsContext.AddSectionIntoNuGetConfig(testDirectory, trustedSignersSectionContent, "configuration"); string fingerprint = verifyCertificateFingerprint ? $"--certificate-fingerprint {certFingerprint} --certificate-fingerprint DEF" : string.Empty; //Act CommandRunnerResult verifyResult = _msbuildFixture.RunDotnet( testDirectory, $"nuget verify {signedPackagePath} {fingerprint}", ignoreExitCode: true); // Assert // For certificate with trusted root setting allowUntrustedRoot value true/false doesn't matter. // Owners is casesensitive, here owner "nuget" matches verifyResult.Success.Should().BeTrue(); verifyResult.AllOutput.Should().Contain(_noTimestamperWarningCode); } }
public async Task Verify_RepositorySignedPackage_WithRepositoryItemUntrustedCertificate_AllowUntrustedRootSetTrue_WrongOwners_Fails(string allowUntrustedRoot, bool verifyCertificateFingerprint) { IX509StoreCertificate storeCertificate = _signFixture.UntrustedSelfIssuedCertificateInCertificateStore; // Arrange using (var pathContext = new SimpleTestPathContext()) { var nupkg = new SimpleTestPackageContext("A", "1.0.0"); await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.WorkingDirectory, nupkg); string packagePath = Path.Combine(pathContext.WorkingDirectory, nupkg.PackageName); //Act var certificateFingerprintString = SignatureTestUtility.GetFingerprint(storeCertificate.Certificate, HashAlgorithmName.SHA256); var packageOwners = new List <string>() { "nuget", "contoso" }; string repoServiceIndex = "https://serviceindex.test/v3/index.json"; string signedPackagePath = await SignedArchiveTestUtility.RepositorySignPackageAsync(storeCertificate.Certificate, packagePath, pathContext.PackageSource, new Uri(repoServiceIndex), null, packageOwners); // Arrange string trustedSignersSectionContent = $@" <trustedSigners> <repository name=""MyCert"" serviceIndex = ""{repoServiceIndex}""> <certificate fingerprint=""{certificateFingerprintString}"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""{allowUntrustedRoot}"" /> <owners>Nuget;Contoso</owners> </repository> </trustedSigners> "; SimpleTestSettingsContext.AddSectionIntoNuGetConfig(pathContext.WorkingDirectory, trustedSignersSectionContent, "configuration"); string fingerprint = verifyCertificateFingerprint ? $"--certificate-fingerprint {certificateFingerprintString} --certificate-fingerprint DEF" : string.Empty; //Act CommandRunnerResult verifyResult = _msbuildFixture.RunDotnet( pathContext.WorkingDirectory, $"nuget verify {signedPackagePath} {fingerprint}", ignoreExitCode: true); // Assert // Owners is casesensitive, owner info should be "nuget;contoso" not "Nuget;Contoso" verifyResult.Success.Should().BeFalse(because: verifyResult.AllOutput); verifyResult.AllOutput.Should().Contain(_noMatchingCertErrorCode); verifyResult.AllOutput.Should().Contain("This package is signed but not by a trusted signer."); } }
public async Task Verify_RepositorySignedPackage_WithRepositoryItemUntrustedCertificate_AllowUntrustedRootSetTrue_CorrectOwners_Succeeds(string allowUntrustedRoot, bool verifyCertificateFingerprint) { // Arrange using (var pathContext = new SimpleTestPathContext()) using (var testCertificate = new X509Certificate2(_testFixture.UntrustedSelfIssuedCertificateInCertificateStore)) { var nupkg = new SimpleTestPackageContext("A", "1.0.0"); await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.WorkingDirectory, nupkg); string packagePath = Path.Combine(pathContext.WorkingDirectory, nupkg.PackageName); //Act string certificateFingerprintString = SignatureTestUtility.GetFingerprint(testCertificate, HashAlgorithmName.SHA256); var packageOwners = new List <string>() { "nuget", "contoso" }; string repoServiceIndex = "https://serviceindex.test/v3/index.json"; string signedPackagePath = await SignedArchiveTestUtility.RepositorySignPackageAsync(testCertificate, packagePath, pathContext.PackageSource, new Uri(repoServiceIndex), null, packageOwners); // Arrange string trustedSignersSectionContent = $@" <trustedSigners> <repository name=""MyCert"" serviceIndex = ""{repoServiceIndex}""> <certificate fingerprint=""{certificateFingerprintString}"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""{allowUntrustedRoot}"" /> <owners>nuget;Contoso</owners> </repository> </trustedSigners> "; SimpleTestSettingsContext.AddSectionIntoNuGetConfig(pathContext.WorkingDirectory, trustedSignersSectionContent, "configuration"); string fingerprint = verifyCertificateFingerprint ? $"-CertificateFingerprint {certificateFingerprintString};def" : string.Empty; // Act CommandRunnerResult verifyResult = CommandRunner.Run( _nugetExePath, pathContext.PackageSource, $"verify {signedPackagePath} -Signatures {fingerprint}", waitForExit: true); // Assert // Owners is casesensitive, here owner "nuget" matches verifyResult.Success.Should().BeTrue(); verifyResult.AllOutput.Should().Contain(_noTimestamperWarningCode); } }
public async Task Verify_RepositorySignedPackage_WithRepositoryItemTrustedCertificate_AllowUntrustedRootSet_WrongOwners_Fails(string allowUntrustedRoot, bool verifyCertificateFingerprint) { // Arrange TrustedTestCert <TestCertificate> cert = _testFixture.TrustedTestCertificateChain.Leaf; using (var pathContext = new SimpleTestPathContext()) { var package = new SimpleTestPackageContext(); string certFingerprint = SignatureTestUtility.GetFingerprint(cert.Source.Cert, HashAlgorithmName.SHA256); var packageOwners = new List <string>() { "nuget", "contoso" }; string repoServiceIndex = "https://serviceindex.test/v3/index.json"; string signedPackagePath = await SignedArchiveTestUtility.RepositorySignPackageAsync(cert.Source.Cert, package, pathContext.PackageSource, new Uri(repoServiceIndex), null, packageOwners); string testDirectory = pathContext.WorkingDirectory; // Arrange string trustedSignersSectionContent = $@" <trustedSigners> <repository name=""NuGetTrust"" serviceIndex=""{repoServiceIndex}""> <certificate fingerprint=""{certFingerprint}"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""{allowUntrustedRoot}"" /> <owners>Nuget;Contoso</owners> </repository> </trustedSigners> "; SimpleTestSettingsContext.AddSectionIntoNuGetConfig(testDirectory, trustedSignersSectionContent, "configuration"); string fingerprint = verifyCertificateFingerprint ? $"-CertificateFingerprint {certFingerprint};def" : string.Empty; //Act CommandRunnerResult verifyResult = CommandRunner.Run( _nugetExePath, pathContext.PackageSource, $"verify {signedPackagePath} -Signatures {fingerprint}", waitForExit: true); // Assert // Owners is casesensitive, owner info should be "nuget;contoso" not "Nuget;Contoso" verifyResult.Success.Should().BeFalse(); verifyResult.AllOutput.Should().Contain(_noMatchingCertErrorCode); } }
public async Task Verify_RepositorySignedPackage_WithRepositoryItemUntrustedCertificate_AllowUntrustedRootSetFalse_Fails(string allowUntrustedRoot, bool verifyCertificateFingerprint) { // Arrange using (var pathContext = new SimpleTestPathContext()) using (var testCertificate = new X509Certificate2(_testFixture.UntrustedSelfIssuedCertificateInCertificateStore)) { var nupkg = new SimpleTestPackageContext("A", "1.0.0"); string testDirectory = pathContext.WorkingDirectory; await SimpleTestPackageUtility.CreatePackagesAsync(testDirectory, nupkg); string packagePath = Path.Combine(testDirectory, nupkg.PackageName); //Act string certificateFingerprintString = SignatureTestUtility.GetFingerprint(testCertificate, HashAlgorithmName.SHA256); string repoServiceIndex = "https://serviceindex.test/v3/index.json"; string signedPackagePath = await SignedArchiveTestUtility.RepositorySignPackageAsync(testCertificate, packagePath, pathContext.PackageSource, new Uri(repoServiceIndex)); // Arrange string trustedSignersSectionContent = $@" <trustedSigners> <repository name=""MyCert"" serviceIndex = ""{repoServiceIndex}""> <certificate fingerprint=""{certificateFingerprintString}"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""{allowUntrustedRoot}"" /> </repository> </trustedSigners> "; SimpleTestSettingsContext.AddSectionIntoNuGetConfig(pathContext.WorkingDirectory, trustedSignersSectionContent, "configuration"); string fingerprint = verifyCertificateFingerprint ? $"-CertificateFingerprint {certificateFingerprintString};def" : string.Empty; // Act CommandRunnerResult verifyResult = CommandRunner.Run( _nugetExePath, pathContext.PackageSource, $"verify {signedPackagePath} -Signatures {fingerprint}", waitForExit: true); // Assert // Unless allowUntrustedRoot is set true in nuget.config verify always fails for cert without trusted root. verifyResult.Success.Should().BeFalse(because: verifyResult.AllOutput); verifyResult.AllOutput.Should().Contain(_noTimestamperWarningCode); verifyResult.AllOutput.Should().Contain(_primarySignatureInvalidErrorCode); verifyResult.AllOutput.Should().Contain("The repository primary signature's signing certificate is not trusted by the trust provider."); } }
public async Task VerifyCommand_AuthorSignedPackage_WithUntrustedCertificate_AllowUntrustedRootIsSetTrue_WrongNugetConfig_Fails() { IX509StoreCertificate storeCertificate = _signFixture.UntrustedSelfIssuedCertificateInCertificateStore; // Arrange using (var pathContext = new SimpleTestPathContext()) { var nupkg = new SimpleTestPackageContext("A", "1.0.0"); //Act string signedPackagePath = await SignedArchiveTestUtility.AuthorSignPackageAsync(storeCertificate.Certificate, nupkg, pathContext.WorkingDirectory); string certificateFingerprintString = SignatureTestUtility.GetFingerprint(storeCertificate.Certificate, HashAlgorithmName.SHA256); // Arrange string nugetConfigPath = Path.Combine(pathContext.WorkingDirectory, NuGet.Configuration.Settings.DefaultSettingsFileName); string nugetConfigPath2 = Path.Combine(pathContext.WorkingDirectory, "nuget2.config"); // nuget2.config doesn't have change for trustedSigners File.Copy(nugetConfigPath, nugetConfigPath2); string trustedSignersSectionContent = $@" <trustedSigners> <author name=""MyCert""> <certificate fingerprint=""{certificateFingerprintString}"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""true"" /> </author> </trustedSigners> "; SimpleTestSettingsContext.AddSectionIntoNuGetConfig(pathContext.WorkingDirectory, trustedSignersSectionContent, "configuration"); //Act // pass custom nuget2.config file, but doesn't have trustedSigners section CommandRunnerResult verifyResult = _msbuildFixture.RunDotnet( pathContext.WorkingDirectory, $"nuget verify {signedPackagePath} --all --certificate-fingerprint {certificateFingerprintString} --certificate-fingerprint def --configfile {nugetConfigPath2}", ignoreExitCode: true); // Assert // allowUntrustedRoot is not set true in nuget2.config, but in nuget.config, so verify fails. verifyResult.Success.Should().BeFalse(); verifyResult.AllOutput.Should().Contain(_noTimestamperWarningCode); verifyResult.AllOutput.Should().Contain(_primarySignatureInvalidErrorCode); } }
public async Task VerifyCommand_AuthorSignedPackage_WithUntrustedCertificate_AllowUntrustedRootIsSetTrue_CorrectNugetConfig_Succeed() { // Arrange using (var pathContext = new SimpleTestPathContext()) using (var testCertificate = new X509Certificate2(_testFixture.UntrustedSelfIssuedCertificateInCertificateStore)) { var nupkg = new SimpleTestPackageContext("A", "1.0.0"); //Act string signedPackagePath = await SignedArchiveTestUtility.AuthorSignPackageAsync(testCertificate, nupkg, pathContext.WorkingDirectory); string certificateFingerprintString = SignatureTestUtility.GetFingerprint(testCertificate, HashAlgorithmName.SHA256); // Arrange string nugetConfigPath = Path.Combine(pathContext.WorkingDirectory, NuGet.Configuration.Settings.DefaultSettingsFileName); string nugetConfigPath2 = Path.Combine(pathContext.WorkingDirectory, "nuget2.config"); File.Copy(nugetConfigPath, nugetConfigPath2); string trustedSignersSectionContent = $@" <trustedSigners> <author name=""MyCert""> <certificate fingerprint=""{certificateFingerprintString}"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""true"" /> </author> </trustedSigners> "; SimpleTestSettingsContext.AddSectionIntoNuGetConfig(nugetConfigPath2, trustedSignersSectionContent, "configuration"); // Act // pass custom nuget2.config file, it has trustedSigners section CommandRunnerResult verifyResult = CommandRunner.Run( _nugetExePath, pathContext.PackageSource, $"verify {signedPackagePath} -All -CertificateFingerprint {certificateFingerprintString};def -ConfigFile {nugetConfigPath2}", waitForExit: true); // Assert // allowUntrustedRoot is set true in nuget2.config, so verify succeeds. verifyResult.Success.Should().BeTrue(); verifyResult.AllOutput.Should().Contain(_noTimestamperWarningCode); } }
public async Task Verify_RepositorySignedPackage_WithRepositoryItemUntrustedCertificate_AllowUntrustedRootSetTrue_Succeeds(string allowUntrustedRoot, bool verifyCertificateFingerprint) { IX509StoreCertificate storeCertificate = _signFixture.UntrustedSelfIssuedCertificateInCertificateStore; // Arrange using (var pathContext = new SimpleTestPathContext()) { var nupkg = new SimpleTestPackageContext("A", "1.0.0"); string testDirectory = pathContext.WorkingDirectory; await SimpleTestPackageUtility.CreatePackagesAsync(testDirectory, nupkg); string packagePath = Path.Combine(testDirectory, nupkg.PackageName); //Act string certificateFingerprintString = SignatureTestUtility.GetFingerprint(storeCertificate.Certificate, HashAlgorithmName.SHA256); string repoServiceIndex = "https://serviceindex.test/v3/index.json"; string signedPackagePath = await SignedArchiveTestUtility.RepositorySignPackageAsync(storeCertificate.Certificate, packagePath, pathContext.PackageSource, new Uri(repoServiceIndex)); // Arrange string trustedSignersSectionContent = $@" <trustedSigners> <repository name=""MyCert"" serviceIndex = ""{repoServiceIndex}""> <certificate fingerprint=""{certificateFingerprintString}"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""{allowUntrustedRoot}"" /> </repository> </trustedSigners> "; SimpleTestSettingsContext.AddSectionIntoNuGetConfig(pathContext.WorkingDirectory, trustedSignersSectionContent, "configuration"); string fingerprint = verifyCertificateFingerprint ? $"--certificate-fingerprint {certificateFingerprintString} --certificate-fingerprint def" : string.Empty; //Act CommandRunnerResult verifyResult = _msbuildFixture.RunDotnet( testDirectory, $"nuget verify {signedPackagePath} {fingerprint}", ignoreExitCode: true); // Assert // If allowUntrustedRoot is set true in nuget.config then verify succeeds for cert with untrusted root. verifyResult.Success.Should().BeTrue(); verifyResult.AllOutput.Should().Contain(_noTimestamperWarningCode); } }
public async Task Verify_AuthorSignedPackage_WithRepositoryItemTrustedCertificate_Fails(string allowUntrustedRoot, bool verifyCertificateFingerprint) { // Arrange TrustedTestCert <TestCertificate> cert = _testFixture.TrustedTestCertificateChain.Leaf; using (var pathContext = new SimpleTestPathContext()) { var nupkg = new SimpleTestPackageContext("A", "1.0.0"); string testDirectory = pathContext.WorkingDirectory; await SimpleTestPackageUtility.CreatePackagesAsync(testDirectory, nupkg); //Act string certificateFingerprintString = SignatureTestUtility.GetFingerprint(cert.Source.Cert, HashAlgorithmName.SHA256); string signedPackagePath = await SignedArchiveTestUtility.AuthorSignPackageAsync(cert.Source.Cert, nupkg, testDirectory); // Arrange string trustedSignersSectionContent = $@" <trustedSigners> <repository name=""MyCert"" serviceIndex=""{pathContext.PackageSource}""> <certificate fingerprint=""{certificateFingerprintString}"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""{allowUntrustedRoot}"" /> </repository> </trustedSigners> "; SimpleTestSettingsContext.AddSectionIntoNuGetConfig(pathContext.WorkingDirectory, trustedSignersSectionContent, "configuration"); string fingerprint = verifyCertificateFingerprint ? $"-CertificateFingerprint {certificateFingerprintString};def" : string.Empty; // Act CommandRunnerResult verifyResult = CommandRunner.Run( _nugetExePath, pathContext.PackageSource, $"verify {signedPackagePath} -Signatures {fingerprint}", waitForExit: true); // Assert verifyResult.Success.Should().BeFalse(because: verifyResult.AllOutput); verifyResult.AllOutput.Should().Contain(_noMatchingCertErrorCode); verifyResult.AllOutput.Should().Contain(_noTimestamperWarningCode); verifyResult.AllOutput.Should().Contain("This package is signed but not by a trusted signer."); } }
public async Task Verify_AuthorSignedPackage_WithAuthorItemTrustedCertificate_Succeeds(string allowUntrustedRoot, bool verifyCertificateFingerprint) { // Arrange TrustedTestCert <TestCertificate> cert = _testFixture.TrustedTestCertificateChain.Leaf; using (var pathContext = new SimpleTestPathContext()) { var nupkg = new SimpleTestPackageContext("A", "1.0.0"); string testDirectory = pathContext.WorkingDirectory; await SimpleTestPackageUtility.CreatePackagesAsync(testDirectory, nupkg); //Act string certificateFingerprintString = SignatureTestUtility.GetFingerprint(cert.Source.Cert, HashAlgorithmName.SHA256); string signedPackagePath = await SignedArchiveTestUtility.AuthorSignPackageAsync(cert.Source.Cert, nupkg, testDirectory); // Arrange string trustedSignersSectionContent = $@" <trustedSigners> <author name=""signed""> <certificate fingerprint=""{certificateFingerprintString}"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""{allowUntrustedRoot}"" /> </author> </trustedSigners> "; SimpleTestSettingsContext.AddSectionIntoNuGetConfig(testDirectory, trustedSignersSectionContent, "configuration"); string fingerprint = verifyCertificateFingerprint ? $"-CertificateFingerprint {certificateFingerprintString};def" : string.Empty; // Act CommandRunnerResult verifyResult = CommandRunner.Run( _nugetExePath, testDirectory, $"verify {signedPackagePath} -Signatures {fingerprint}", waitForExit: true); // Assert // For certificate with trusted root setting allowUntrustedRoot to true/false doesn't matter verifyResult.Success.Should().BeTrue(because: verifyResult.AllOutput); verifyResult.AllOutput.Should().Contain(_noTimestamperWarningCode); } }
public void SetApiKey_WithSpecifiedSource_SetApiKeyBySourceKey(string serverUri) { using (var pathContext = new SimpleTestPathContext()) { // Add source into NuGet.Config file SimpleTestSettingsContext settings = pathContext.Settings; var packageSourcesSection = SimpleTestSettingsContext.GetOrAddSection(settings.XML, ConfigurationConstants.PackageSources); string sourceKey = serverUri.Contains("random") ? "random" : serverUri.Contains("contos") ? "contoso" : "nuget.org"; SimpleTestSettingsContext.AddEntry(packageSourcesSection, sourceKey, serverUri); settings.Save(); var testApiKey = Guid.NewGuid().ToString(); // Act var result = CommandRunner.Run( NuGetExePath, pathContext.WorkingDirectory, $"setApiKey {testApiKey} -Source {sourceKey} -ConfigFile {settings.ConfigPath}", waitForExit: true); var iSettings = Configuration.Settings.LoadDefaultSettings( Path.GetDirectoryName(settings.ConfigPath), Path.GetFileName(settings.ConfigPath), null); // Assert Assert.True(0 == result.ExitCode, $"{result.Output} {result.Errors}"); Assert.Contains($"The API Key '{testApiKey}' was saved for '{serverUri}'", result.Output); Assert.DoesNotContain($"symbol", result.Output); var actualApiKey = SettingsUtility.GetDecryptedValueForAddItem(iSettings, ConfigurationConstants.ApiKeys, serverUri); Assert.Equal(testApiKey, actualApiKey); XElement apiKeySection = SimpleTestSettingsContext.GetOrAddSection(XmlUtility.Load(settings.ConfigPath), ConfigurationConstants.ApiKeys); Assert.Equal(1, apiKeySection.Elements().Count()); } }
public void ListCommand_WithAuthenticatedSource_AppliesCredentialsFromSettings() { var expectedAuthHeader = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes("user:password")); var listEndpoint = Guid.NewGuid().ToString() + "/api/v2"; bool serverReceiveProperAuthorizationHeader = false; using (var pathContext = new SimpleTestPathContext()) { // Arrange var repo = Path.Combine(pathContext.WorkingDirectory, "repo"); var packageFileName1 = Util.CreateTestPackage("testPackage1", "1.1.0", repo); var package1 = new ZipPackage(packageFileName1); // Server setup using (var serverV3 = new MockServer()) { var indexJson = Util.CreateIndexJson(); Util.AddFlatContainerResource(indexJson, serverV3); Util.AddLegacyGalleryResource(indexJson, serverV3, listEndpoint); serverV3.Get.Add("/", r => { var h = r.Headers["Authorization"]; if (h == null) { return(new Action <HttpListenerResponse>(response => { response.StatusCode = 401; response.AddHeader("WWW-Authenticate", @"Basic realm=""Test"""); MockServer.SetResponseContent(response, "401 Unauthenticated"); })); } if (expectedAuthHeader != h) { return(HttpStatusCode.Forbidden); } var path = serverV3.GetRequestUrlAbsolutePath(r); if (path == "/index.json") { return(new Action <HttpListenerResponse>(response => { response.StatusCode = 200; response.ContentType = "text/javascript"; MockServer.SetResponseContent(response, indexJson.ToString()); })); } if (path == $"/{listEndpoint}/$metadata") { return(Util.GetMockServerResource()); } if (path == $"/{listEndpoint}/Search()") { return(new Action <HttpListenerResponse>(response => { response.ContentType = "application/atom+xml;type=feed;charset=utf-8"; var feed = serverV3.ToODataFeed(new[] { package1 }, "Search"); MockServer.SetResponseContent(response, feed); })); } serverReceiveProperAuthorizationHeader = true; return("OK"); }); // Add source into NuGet.Config file var settings = pathContext.Settings; SimpleTestSettingsContext.RemoveSource(settings.XML, "source"); var source = serverV3.Uri + "index.json"; var packageSourcesSection = SimpleTestSettingsContext.GetOrAddSection(settings.XML, "packageSources"); SimpleTestSettingsContext.AddEntry(packageSourcesSection, "vsts", source, additionalAtrributeName: "protocolVersion", additionalAttributeValue: "3"); //var packageSourceCredentialsSection = SimpleTestSettingsContext.GetOrAddSection(settings.XML, "packageSourceCredentials"); SimpleTestSettingsContext.AddPackageSourceCredentialsSection(settings.XML, "vsts", "user", "password", clearTextPassword: true); settings.Save(); serverV3.Start(); // Act var result = CommandRunner.Run( Util.GetNuGetExePath(), pathContext.SolutionRoot, $"list test -source {serverV3.Uri}index.json -configfile {pathContext.NuGetConfig} -verbosity detailed -noninteractive", waitForExit: true); serverV3.Stop(); // Assert Assert.True(0 == result.Item1, $"{result.Item2} {result.Item3}"); Assert.True(serverReceiveProperAuthorizationHeader); Assert.Contains($"GET {serverV3.Uri}{listEndpoint}/Search()", result.Item2); // verify that only package id & version is displayed Assert.Matches(@"(?m)testPackage1\s+1\.1\.0", result.Item2); } } }
[InlineData("{0}push")] // delete package endpoint public void DeleteCommand_WithApiKeyFromConfig(string configKeyFormatString) { // Arrange var testApiKey = Guid.NewGuid().ToString(); using (var pathContext = new SimpleTestPathContext()) using (var server = new MockServer()) { // Server setup var indexJson = Util.CreateIndexJson(); Util.AddFlatContainerResource(indexJson, server); Util.AddPublishResource(indexJson, server); server.Get.Add("/index.json", r => { return(new Action <HttpListenerResponse>(response => { response.StatusCode = 200; response.ContentType = "text/javascript"; MockServer.SetResponseContent(response, indexJson.ToString()); })); }); server.Delete.Add("/push/testPackage1/1.1", r => { var h = r.Headers[ApiKeyHeader]; if (!string.Equals(h, testApiKey, StringComparison.OrdinalIgnoreCase)) { return(HttpStatusCode.Unauthorized); } return(HttpStatusCode.OK); }); server.Start(); // Add the source and apikeys into NuGet.Config file var settings = pathContext.Settings; SimpleTestSettingsContext.RemoveSource(settings.XML, "source"); var source = server.Uri + "index.json"; var packageSourcesSection = SimpleTestSettingsContext.GetOrAddSection(settings.XML, "packageSources"); SimpleTestSettingsContext.AddEntry(packageSourcesSection, $"MockServer", source); var configKey = string.Format(configKeyFormatString, server.Uri); var configValue = Configuration.EncryptionUtility.EncryptString(testApiKey); var apikeysSection = SimpleTestSettingsContext.GetOrAddSection(settings.XML, "apikeys"); SimpleTestSettingsContext.AddEntry(apikeysSection, configKey, configValue); settings.Save(); // Act var args = new[] { "delete", "testPackage1", "1.1.0", "-Source", "MockServer", "-ConfigFile", pathContext.NuGetConfig, "-NonInteractive" }; var result = CommandRunner.Run( NuGetExePath, Directory.GetCurrentDirectory(), string.Join(" ", args), waitForExit: true); server.Stop(); // Assert Assert.True(0 == result.Item1, $"{result.Item2} {result.Item3}"); Assert.Contains("testPackage1 1.1.0 was deleted successfully.", result.Item2); } }