Avoid committing secrets by ignoring tracked files in Git

Avoid committing secrets by ignoring tracked files in Git

The Problem

Secrets are things like API keys, user credentials, and certificates that will implicitly allow someone access to another platform or service. My team has a local.settings.json file in our repository that contains some secrets that allow us to call dependent services. In order to successfully run the code locally, you need those secrets.

If, in the midst of a slurry of commits, you commit that file with the secrets inside of it; you will likely have to delete your entire branch, or do some git magic to remove it. Deleting the secrets and committing isn't enough because git still keeps track of those secrets in the history.

The Solution

Very simply, you could just use .gitignore to prevent git from keeping track of this file and store it somewhere secure for developers to use (or just constantly pass it around). I don't like that approach, because it makes it hard to keep track of what should be in the file. I do recommend committing the secret-free version of your settings files, and then just inserting them manually when you need them.

The trick with this, is not committing those secrets into your codebase. The solution to that problem is to tell git to stop tracking file changes for this file. You can signal git to stop tracking those changes, and then add your secrets in and continue on!

Here's How

First, with your clean file already tracked in git you can signal git to stop tracking changes to your file using this line:

git update-index --assume-unchanged [<file> ...]
Prevent git from tracking changes made to a path

This will allow you to save changes to the file (ie. adding secrets to it) without accidentally committing them. As you're making changes, make sure you're still being diligent with git status and ensure git isn't tracking changes to that file.

To make changes that your teammates can see, you'll need to start by removing hte secrets from your file. Then, run this command:

git update-index --no-assume-unchanged [<file> ...]
Allow git to track changes made to a path

This will signal to git to start tracking that file again, and you'll be able to commit the contents of the file.

Once you're ready to use the file with secrets just start from the top just rinse and repeat!

I am not exactly sure which mechanics will override this --assume-unchanged  flag; but in my experience it seems like merges or switching branches might undo that work. If you know, drop me a line: twalkerweb+blog@gmail.com