Skip to content

Instantly share code, notes, and snippets.

@bangpound
Created March 23, 2019 13:57
Show Gist options
  • Save bangpound/2ce916ec7fe13c62d28dea5c92441524 to your computer and use it in GitHub Desktop.
Save bangpound/2ce916ec7fe13c62d28dea5c92441524 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# Vault Token helper for the Mac OS X Keychain.
#
# Vault allows an external programs to be configured as a token helper
# that can get, store, and erase tokens on behalf of the Vault client.
#
# see https://www.vaultproject.io/docs/commands/token-helper.html
#
# To use this script, make it executable and set your ~/.vault file to
# contain:
#
# token_helper = "/path/to/vault-token-helper.sh"
# Exit on error.
set -o errexit
# Exit on error inside any functions or subshells.
set -o errtrace
# Do not allow use of undefined vars.
set -o nounset
# Catch the error if any piped command fails.
set -o pipefail
case $1 in
get)
# If the key is not set, keyctl returns "request_key: Required key not available"
# on stderr and exits with a non-zero status.
token=$(security find-generic-password -a "${USER}" -s "${VAULT_ADDR}" -w || echo '')
[ -z "${token}" ] && exit 0
printf "%s" "${token}"
;;
store)
# Vault sends the token on stdin but there is no linebreak, so EOF is reached
# which causes read to return a non-zero status.
read -r token || true
options="-a ${USER} -s ${VAULT_ADDR} -w ${token}"
security find-generic-password -a "${USER}" -s "${VAULT_ADDR}" > /dev/null 2>&1 && has_token=1 || has_token=0
if [ ${has_token} -eq 1 ]; then
options="${options} -U"
fi
security add-generic-password ${options}
;;
erase)
security delete-generic-password -a "${USER}" -s "${VAULT_ADDR}" > /dev/null 2>&1 || true
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment