Using a .netrc to securely store remote server credentials
I've been building a CLI for useCloudState.io, and I was wondering what the best way would be for the CLI to store an auth token in the users machine.
Following the lead from the excellent Heroku CLI, a .netrc file seemed to be the best choice.
Anatomy of a .netrc file
A .netrc file typically resides in your home (
~/.netrc) and is a widely used mechanism to store auth related information for remote servers.
Put simply, it's a key-value store where the:
- key: is an external server host, denoted by the prefix
- value: the username (denoted by
login) and the password (denoted by
password) are the credentials to connect to the machine.
$cat ~/.netrc machine api.usecloudstate.io login firstname.lastname@example.org password c4cd94da15ea0544802c2cfd5ec4ead324327111 machine github.com login email@example.com password c2224da15ea0544802c2cfd5ec4ead324327430
Programmatically mutating the .netrc file
However, since this is just a file, you can easily
echo and append (
>>) as well.
The obvious disclaimer here is that storing sensitive data in clear-text anywhere in your computer is inherently unsafe than some other means.
And anyone accessing your computer being able to
cat ~/.netrc is going to get access to your credentials.
In any case, it's a good practice to maintain the file with the minimum required permissions, as you'd with your SSH keys. (Typically
- A nice property of .netrc is that you can get curl support out of the box using
- Git servers using HTTP(S) protocol can also look up credentials this way.