Keeping secrets in blogdown

Keeping API keys and passwords secret in a blogdown blog using the static/ folder and the secret package.
R
Published

January 2, 2019

Sometimes we need to keep secrets. For instance, if you want to use ggmap after July 2018 you need an API key and to provide billing details to Google. You definitely don’t want to accidentally include your personal API key in a blog post.

This blog is generated using the awesome blogdown package, which means all this wonderful stuff is generated from RMarkdown documents that are available in a public Github repository. It’s therefore extremely important I don’t accidentally include the key anywhere in my repository. But I want to consistently use API keys anywhere in the website.

If you want to do something similar, I recommend following these instructions:

  1. Add the following lines to your .gitignore file
static/data/secret-keys.R
static/data/secret-vault.vault
  1. Add these changes to a commit and push to Github.

  2. Don’t proceed until you’ve done step 2. You need to protect these two files.

  3. Create an SSH key in the terminal:

ssh-keygen -t rsa
# Enter file in which to save the key: blog_vault

Now create the static/data/secret-keys.R file and add your tokens using Gabor Csardi’s secret package:

library("secret")
library("here")

## ==== Create a vault — run ONCE ONLY
my_vault <- here("static", "data", "secret-vault.vault")
create_vault(my_vault)

## ==== Create a user — run ONCE ONLY
key_dir <- "/Users/charliejhadley/.ssh"
charliejhadley_public_key  <- file.path(key_dir, "blog_vault.pub")
charliejhadley_private_key <- file.path(key_dir, "blog_vault")
add_user("charliejhadley", charliejhadley_public_key, vault = my_vault)

Once you’ve run this code, comment out everything except the first two lines. Then add a secret:

add_secret("ggmaps_key", "YOUR-REAL-KEY", user = "charliejhadley", vault = my_vault)

Delete the add_secret() line after running it. Remember that if you have not disabled your .RHistory then your keys will be available in a plain text file.

Now you can use your keys safely in blogposts:

library("here")
library("secret")
library("ggmap")

my_vault <- here("static", "data", "secret-vault.vault")
charliejhadley_private_key <- file.path("~/.ssh", "blog_vault")

ggmaps_key <- get_secret("ggmaps_key", key = charliejhadley_private_key, vault = my_vault)
register_google(key = ggmaps_key)

base_map <- get_googlemap(center = c(2.2945, 48.858222), maptype = "roadmap")
ggmap(base_map)

I highly recommend Hadley Wickham’s httr vignette on managing secrets if you want to learn more.