Configuring mercurial keyring

If you don’t want to type your username and password everytime you do a pull or push to mercurial, you have to store your credentials somewhere. On windows, the commandline hg does not store credentials (you have to enter them every time). If you configure credentials in TortoiseHG, the username and password will be stored in plain-text, in mercurial.ini file. This is not the most secure way to do it, and mercurial will even warn you about that.

Keyring

Keyring is a Python module that uses native OS credentials database to store passwords. On Windows, it uses Windows Credentials Manager cmdkey.exe. For mercurial, there is mercurial_keyring extension that uses keyring as credentials store.

Installing keyring on Windows

The guide for mercurial_keyring says that installation “in some cases (Windows…) requires more care”. I will focus here on Windows installation, specifically the case when you use TortoiseHG distribution of mercurial. What we will do is install python2 from chocolatey, use pip to install all required python modules, then configure path to these modules in mercurial.ini.

  1. If you don’t have it already, install python2:

     > choco install -y python2
     > refreshenv
    

    chocolatey package python2 installs to c:/Python27 by default

  2. install mercurial_keyring

     > pip install --user mercurial_keyring
    

    pip will handle installation of all dependencies, including keyring, mercurial_extension_utils, etc.

  3. Configure exension in mercurial.ini:

     [extensions]
     mercurial_keyring = C:/Python27/Lib/site-packages/mercurial_keyring.py
    

Verify it

Let’s try it out:

> hg clone https://bitbucket.org/heavymetaldev/top-secret tmp
keyring: username not specified in hgrc (or in url). Password will not be saved.
http authorization required
realm: Bitbucket.org HTTP
url: https://bitbucket.org/heavymetaldev/top-secret
user:

Note that keyring apparently is working, but it says it will not save password. To configure username, either add it to repo url (like: https://[email protected]/heavymetaldev/top-secret) or configure in mercurial.ini:

[auth]
bitbucket.org.prefix = bitbucket.org
bitbucket.org.username = qbik

TortoiseHG does exactly that when you configure credentials there (with mercurial_keyring enabled).

Now, you can safely store your credentials, not worrying about it leaking somewhere.

Use SSH

If you use a hostin service that provides SSH access (like bitbucket), you may also want to configure SSH private key instead of storing usernamee and password.