Esempio n. 1
0
        public async Task BasicAuthSetCredentialsTest()
        {
            TargetUri           targetUri = new TargetUri("http://localhost");
            BasicAuthentication basicAuth = GetBasicAuthentication(RuntimeContext.Default, "basic-set");

            Credential credentials = null;

            Assert.Null(credentials = await basicAuth.GetCredentials(targetUri));
            Assert.Throws <System.ArgumentNullException>(() =>
            {
                try
                {
                    Task.Run(async() => { await basicAuth.SetCredentials(targetUri, credentials); }).Wait();
                }
                catch (System.AggregateException exception)
                {
                    exception = exception.Flatten();
                    throw exception.InnerException;
                }
            });

            credentials = new Credential("username", "password");

            await basicAuth.SetCredentials(targetUri, credentials);

            Assert.NotNull(credentials = await basicAuth.GetCredentials(targetUri));
        }
        public void BasicAuthGetCredentialsTest()
        {
            Uri targetUri = new Uri("http://localhost");
            BasicAuthentication basicAuth = GetBasicAuthentication("basic-get");

            Credential credentials = null;

            Assert.IsFalse(basicAuth.GetCredentials(targetUri, out credentials), "User credentials were unexpectedly retrieved.");

            credentials = new Credential("username", "password");

            basicAuth.CredentialStore.WriteCredentials(targetUri, credentials);

            Assert.IsTrue(basicAuth.GetCredentials(targetUri, out credentials), "User credentials were unexpectedly not retrieved.");
        }
        public void BasicAuthGetCredentialsTest()
        {
            TargetUri           targetUri = new TargetUri("http://localhost");
            BasicAuthentication basicAuth = GetBasicAuthentication("basic-get");

            Credential credentials = null;

            Assert.Null(credentials = basicAuth.GetCredentials(targetUri));

            credentials = new Credential("username", "password");

            basicAuth.CredentialStore.WriteCredentials(targetUri, credentials);

            Assert.NotNull(credentials = basicAuth.GetCredentials(targetUri));
        }
Esempio n. 4
0
        public async Task BasicAuthGetCredentialsTest()
        {
            TargetUri           targetUri = new TargetUri("http://localhost");
            BasicAuthentication basicAuth = GetBasicAuthentication(RuntimeContext.Default, "basic-get");

            Credential credentials = null;

            Assert.Null(credentials = await basicAuth.GetCredentials(targetUri));

            credentials = new Credential("username", "password");

            await basicAuth.CredentialStore.WriteCredentials(targetUri, credentials);

            Assert.NotNull(credentials = await basicAuth.GetCredentials(targetUri));
        }
Esempio n. 5
0
        static CredentialsHandler CreateCredentialsHandler(IRepository repo, string remoteName)
        {
            var remote    = repo.Network.Remotes[remoteName];
            var remoteUri = new Uri(remote.Url);

            var secrets = new SecretStore("git");
            var auth    = new BasicAuthentication(secrets);

            var targetUrl = remoteUri.GetLeftPart(UriPartial.Authority);
            var creds     = auth.GetCredentials(new TargetUri(targetUrl));

            if (creds == null)
            {
                return(null);
            }

            CredentialsHandler credentialsHandler =
                (url, user, cred) => new UsernamePasswordCredentials
            {
                Username = creds.Username,
                Password = creds.Password
            };

            return(credentialsHandler);
        }
Esempio n. 6
0
        public void BasicAuthentication_GetCredentials_NullResource_ThrowsException()
        {
            var context   = new TestCommandContext();
            var basicAuth = new BasicAuthentication(context);

            Assert.Throws <ArgumentNullException>(() => basicAuth.GetCredentials(null));
        }
Esempio n. 7
0
        protected string GetToken(string url)
        {
            var targetUrl = new Uri(url).GetLeftPart(UriPartial.Authority);

            switch (SecretStore)
            {
            case SecretStores.Credential:
                // Use the built in credential store
                var userPass = CredentialManager.Fill(new Uri(targetUrl));
                if (userPass.Username != null)
                {
                    return(userPass.Password);
                }
                break;

            default:
                // Use a specific secret store
                var secretStore = CreateSecretStore();
                var auth        = new BasicAuthentication(secretStore);
                var creds       = auth.GetCredentials(new TargetUri(targetUrl));
                if (creds != null)
                {
                    return(creds.Password);
                }
                break;
            }

            throw new ApplicationException($"Couldn't find credentials for {url}");
        }
        public void BasicAuthentication_GetCredentials_DesktopSession_ResourceAndUser_PassPromptDiffUserReturnsCredentials()
        {
            const string testResource = "https://example.com";
            const string testUserName = "******";
            const string newUserName  = "******";
            const string testPassword = "******"; // [SuppressMessage("Microsoft.Security", "CS001:SecretInline", Justification="Fake credential")]

            var context = new TestCommandContext
            {
                SessionManager = { IsDesktopSession = true },
                SystemPrompts  =
                {
                    CredentialPrompt = (resource, userName) =>
                    {
                        Assert.Equal(testResource, resource);
                        Assert.Equal(testUserName, userName);

                        return(new GitCredential(newUserName, testPassword));
                    }
                }
            };

            var basicAuth = new BasicAuthentication(context);

            ICredential credential = basicAuth.GetCredentials(testResource, testUserName);

            Assert.NotNull(credential);
            Assert.Equal(newUserName, credential.Account);
            Assert.Equal(testPassword, credential.Password);
        }
Esempio n. 9
0
        public void BasicAuthentication_GetCredentials_DesktopSession_Resource_UserPassPromptReturnsCredentials()
        {
            const string testResource = "https://example.com";
            const string testUserName = "******";
            const string testPassword = "******";

            var context = new TestCommandContext
            {
                SessionManager = { IsDesktopSession = true },
                SystemPrompts  =
                {
                    CredentialPrompt = (resource, userName) =>
                    {
                        Assert.Equal(testResource, resource);
                        Assert.Null(userName);

                        return(new GitCredential(testUserName, testPassword));
                    }
                }
            };

            var basicAuth = new BasicAuthentication(context);

            ICredential credential = basicAuth.GetCredentials(testResource);

            Assert.NotNull(credential);
            Assert.Equal(testUserName, credential.Account);
            Assert.Equal(testPassword, credential.Password);
        }
        public string FindGitHubToken()
        {
            var secrets = new SecretStore("git");
            var auth    = new BasicAuthentication(secrets);
            var creds   = auth.GetCredentials(new TargetUri("https://github.com"));

            return(creds?.Password);
        }
        public void BasicAuthSetCredentialsTest()
        {
            TargetUri           targetUri = new TargetUri("http://localhost");
            BasicAuthentication basicAuth = GetBasicAuthentication("basic-set");

            Credential credentials = null;

            Assert.Null(credentials = basicAuth.GetCredentials(targetUri));
            Assert.Throws <System.ArgumentNullException>(() =>
            {
                basicAuth.SetCredentials(targetUri, credentials);
            });

            credentials = new Credential("username", "password");

            basicAuth.SetCredentials(targetUri, credentials);

            Assert.NotNull(credentials = basicAuth.GetCredentials(targetUri));
        }
        public void BasicAuthSetCredentialsTest()
        {
            Uri targetUri = new Uri("http://localhost");
            BasicAuthentication basicAuth = GetBasicAuthentication("basic-set");

            Credential credentials = null;

            Assert.IsFalse(basicAuth.GetCredentials(targetUri, out credentials), "User credentials were unexpectedly retrieved.");
            try
            {
                basicAuth.SetCredentials(targetUri, credentials);
                Assert.Fail("User credentials were unexpectedly set.");
            }
            catch { }

            credentials = new Credential("username", "password");

            Assert.IsTrue(basicAuth.SetCredentials(targetUri, credentials), "User credentials were unexpectedly not set.");
            Assert.IsTrue(basicAuth.GetCredentials(targetUri, out credentials), "User credentials were unexpectedly not retrieved.");
        }
Esempio n. 13
0
        public static Credentials MicrosoftAlm(string url, string usernameFromUrl, SupportedCredentialTypes types)
        {
            var cleanUrl = new Uri(url).GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped);
            var auth     = new BasicAuthentication(new SecretStore("git"));
            var newCreds = auth.GetCredentials(new TargetUri(cleanUrl));

            return(newCreds == null ? null
                : new UsernamePasswordCredentials
            {
                Username = newCreds.Username,
                Password = newCreds.Password
            });
        }
        public void BasicAuthentication_GetCredentials_NoTerminalPrompts_ThrowsException()
        {
            const string testResource = "https://example.com";

            var context = new TestCommandContext
            {
                Settings = { IsTerminalPromptsEnabled = false },
            };

            var basicAuth = new BasicAuthentication(context);

            Assert.Throws <InvalidOperationException>(() => basicAuth.GetCredentials(testResource));
        }
Esempio n. 15
0
        public Credential GetGitCredentials(string gitUrl)
        {
            var secrets = new SecretStore("git");

            var auth  = new BasicAuthentication(secrets);
            var uri   = new Uri(gitUrl);
            var url   = uri.Scheme + "://" + uri.Authority;
            var creds = auth.GetCredentials(new TargetUri(url));

            //if (creds == null)
            // TODO: Prompt for

            return(creds);
        }
        public Credentials GetCredentials(string url, string usernameFromUrl, SupportedCredentialTypes types)
        {
            var uri     = new Uri(url);
            var host    = uri.Scheme + Uri.SchemeDelimiter + uri.Host;
            var secrets = new SecretStore("git");
            var auth    = new BasicAuthentication(secrets);
            var creds   = auth.GetCredentials(new TargetUri(host));

            return(new UsernamePasswordCredentials()
            {
                Username = creds.Username,
                Password = creds.Password
            });
        }
Esempio n. 17
0
        static Credentials OnHandleCredentials(string url, string usernameFromUrl, SupportedCredentialTypes types)
        {
            var secrets = new SecretStore("git");
            var auth    = new BasicAuthentication(secrets);
            // See https://github.com/microsoft/Git-Credential-Manager-for-Windows/issues/859
            var uri   = new Uri(url);
            var creds = auth.GetCredentials(new TargetUri(uri.GetComponents(UriComponents.Scheme | UriComponents.Host, UriFormat.Unescaped)));

            return(new UsernamePasswordCredentials
            {
                Username = creds.Username,
                Password = creds.Password,
            });
        }
        public void BasicAuthentication_GetCredentials_ResourceAndUserName_PasswordPromptReturnsCredentials()
        {
            const string testResource = "https://example.com";
            const string testUserName = "******";
            const string testPassword = "******";

            var context = new TestCommandContext();

            context.Terminal.SecretPrompts["Password"] = testPassword;

            var basicAuth = new BasicAuthentication(context);

            GitCredential credential = basicAuth.GetCredentials(testResource, testUserName);

            Assert.Equal(testUserName, credential.UserName);
            Assert.Equal(testPassword, credential.Password);
        }
Esempio n. 19
0
        public void FetchLatestGITFiles()
        {
            var secrets = new SecretStore("git");
            var auth    = new BasicAuthentication(secrets);
            var creds   = auth.GetCredentials(new TargetUri("https://github.com"));

            var options = new CloneOptions
            {
                CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials
                {
                    Username = "******",
                    Password = "******"
                },
            };

            // Clone everything from https://github.com/alexdaniel1967/TestHarness to C:\Test folder
            Repository.Clone("https://github.com/alexdaniel1967/TestHarness", @"C:\Test", options);
        }
        public void BasicAuthentication_GetCredentials_NonDesktopSession_ResourceAndUserName_PasswordPromptReturnsCredentials()
        {
            const string testResource = "https://example.com";
            const string testUserName = "******";
            const string testPassword = "******"; // [SuppressMessage("Microsoft.Security", "CS001:SecretInline", Justification="Fake credential")]

            var context = new TestCommandContext {
                SessionManager = { IsDesktopSession = false }
            };

            context.Terminal.SecretPrompts["Password"] = testPassword; // [SuppressMessage("Microsoft.Security", "CS001:SecretInline", Justification="Fake credential")]

            var basicAuth = new BasicAuthentication(context);

            ICredential credential = basicAuth.GetCredentials(testResource, testUserName);

            Assert.Equal(testUserName, credential.Account);
            Assert.Equal(testPassword, credential.Password);
        }
Esempio n. 21
0
        public void BasicAuthentication_GetCredentials_NonDesktopSession_Resource_UserPassPromptReturnsCredentials()
        {
            const string testResource = "https://example.com";
            const string testUserName = "******";
            const string testPassword = "******";

            var context = new TestCommandContext {
                SessionManager = { IsDesktopSession = false }
            };

            context.Terminal.Prompts["Username"]       = testUserName;
            context.Terminal.SecretPrompts["Password"] = testPassword;

            var basicAuth = new BasicAuthentication(context);

            ICredential credential = basicAuth.GetCredentials(testResource);

            Assert.Equal(testUserName, credential.Account);
            Assert.Equal(testPassword, credential.Password);
        }
Esempio n. 22
0
        //this option helps to clone a git project to a specific folder
        private void pictureBox5_Click(object sender, EventArgs e)
        {
            //opens git repo in browser
            Process.Start("https://github.com/sajagxD/sajagbugfinder.git");

            var secrets = new SecretStore("git");
            var auth    = new BasicAuthentication(secrets);
            var creds   = auth.GetCredentials(new TargetUri("https://github.com"));

            var options = new CloneOptions
            {
                CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials
                {
                    Username = creds.Username,
                    Password = creds.Password
                },
            };

            Repository.Clone("https://github.com/sajagxD/sajagbugfinder.git", @"c:\projects", options);
        }
        static CredentialsHandler CreateCredentialsHandler(IRepository repo, string remoteName)
        {
            CredentialsHandler retval = null;

            var remote    = repo.Network.Remotes[remoteName];
            var remoteUri = new Uri(remote.Url);

            var secrets = new SecretStore("git");
            var auth    = new BasicAuthentication(secrets);

            var targetUrl = remoteUri.GetLeftPart(UriPartial.Authority);

            //HACK ALERT!! to make this thing play nice with Windows Credentials and how it stores my PATs. YMMV
            if (targetUrl.Contains("dev.azure.com", StringComparison.OrdinalIgnoreCase))
            {
                var url = new Uri(targetUrl);
                if (!string.IsNullOrWhiteSpace(url.UserInfo))
                {
                    targetUrl = url + url.UserInfo;
                }
            }
            //End HACK ALERT!!

            var creds = auth.GetCredentials(new TargetUri(targetUrl));

            if (creds != null)
            {
                retval = (url, user, cred) => new UsernamePasswordCredentials
                {
                    Username = creds.Username,
                    Password = creds.Password
                };
            }

            return(retval);
        }
        static IDictionary <string, string> GetReferences(IRepository repo, string remoteName)
        {
            var secrets = new SecretStore("git");
            var auth    = new BasicAuthentication(secrets);
            var creds   = auth.GetCredentials(new TargetUri("https://github.com"));

            CredentialsHandler credentialsHandler =
                (url, user, cred) => new UsernamePasswordCredentials
            {
                Username = creds.Username,
                Password = creds.Password
            };

            var dictionary = new Dictionary <string, string>();
            var remote     = repo.Network.Remotes[remoteName];
            var refs       = repo.Network.ListReferences(remote, credentialsHandler);

            foreach (var reference in refs)
            {
                dictionary[reference.CanonicalName] = reference.TargetIdentifier;
            }

            return(dictionary);
        }
Esempio n. 25
0
        private void LogInButton_Click(object sender, EventArgs e)
        {
            gitHubCredentials = new UsernamePasswordCredentials()
            {
                Username = gitHubUsernameTextBox.Text,
                Password = gitHubPasswordTextBox.Text
            };


            // Setup GitHub authentication
            SecretStore         gitSecretStore   = new SecretStore("git");
            BasicAuthentication authType         = new BasicAuthentication(gitSecretStore);
            Credential          userCredentials  = authType.GetCredentials(new TargetUri("https://github.com"));
            CloneOptions        credCloneOptions = new CloneOptions
            {
                OnTransferProgress = cloneProgress =>
                {
                    var clonePercentage = (100 * cloneProgress.ReceivedObjects) / cloneProgress.TotalObjects;
                    cloneProgressBar.Invoke(new Action(() => cloneProgressBar.Value = clonePercentage));
                    return(true);
                },
                CredentialsProvider = (_url, _user, _cred) => gitHubCredentials,
            };

            // Try to authenticate, notify the user if there's an error
            try
            {
                // Clone the repo and close the form
                // We also want to nullify all credential objects to respect the user's privacy
                // This should make the memory "out of scope" in the eyes of the garbage collector

                // Extract the repo name from the URL, then combine it with the path to make the full path
                string[] repoSplit    = projectURL.Trim().Split('/');
                string   repoName     = repoSplit[repoSplit.Length - 1].Split('.')[0];
                string   combinedPath = Path.Combine(pathToClone, repoName);


                Repository.Clone(projectURL, combinedPath, credCloneOptions);

                userCredentials  = null;
                credCloneOptions = null;

                new Thread(new ThreadStart(delegate
                {
                    MessageBox.Show("Repository cloned successfully! Closing login form.", "Cloned Successfully", MessageBoxButtons.OK, MessageBoxIcon.Information);
                })).Start();

                this.Close();
            }
            catch (LibGit2Sharp.NameConflictException)
            {
                new Thread(new ThreadStart(delegate
                {
                    MessageBox.Show("Failed to clone the repo. Directory already exists with that name.", "Cloning Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                })).Start();
            }
            catch (LibGit2Sharp.LibGit2SharpException)
            {
                new Thread(new ThreadStart(delegate
                {
                    MessageBox.Show("Failed to clone the repo. Please check your internet connection or credentials.", "Cloning Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                })).Start();
            }
        }