Example #1
0
        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());
            }
        }
Example #2
0
        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());
            }
        }
Example #3
0
        [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);
                }
        }
        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);
                }
            }
        }