Using a .netrc to securely store remote server credentials

Oct 19, 2021 12:14 AM

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 machine
  • 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 me@example.com
  password c4cd94da15ea0544802c2cfd5ec4ead324327111
machine github.com
  login me@example.com
  password c2224da15ea0544802c2cfd5ec4ead324327430

Programmatically mutating the .netrc file

Most major languages have libraries supporting accessing and mutating a .netrc file. If you're using golang, I can recommend jdxcode/netrc, as the standard library implementation is only internal.

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.

How to Handle Secrets on the Command Line
How to Handle Secrets on the Command Line

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 chmod 600)

Other uses

  • A nice property of .netrc is that you can get curl support out of the box using --netrc flag.
  • Git servers using HTTP(S) protocol can also look up credentials this way.