Skip to content

Instantly share code, notes, and snippets.

@pragmatist-nz
Last active December 10, 2024 04:58
Show Gist options
  • Select an option

  • Save pragmatist-nz/da818858984dd1ebc831ef24fe92a1d0 to your computer and use it in GitHub Desktop.

Select an option

Save pragmatist-nz/da818858984dd1ebc831ef24fe92a1d0 to your computer and use it in GitHub Desktop.
gh token from github app creds
#!/bin/bash
# kudos to https://github.com/exp0nge
# https://github.com/cli/cli/discussions/5095#discussioncomment-10898590
set -euo pipefail
jwt_encode() {
# https://stackoverflow.com/questions/58313106/create-rs256-jwt-in-bash
PEM=$( cat "$GITHUB_APP_SECRET_PATH" )
NOW=$( date +%s )
IAT="${NOW}"
# expire 5 minutes in the future. 10 minutes is the max for github
EXP=$((${NOW} + 300))
HEADER_RAW='{"alg":"RS256"}'
HEADER=$( echo -n "${HEADER_RAW}" | openssl base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n' )
PAYLOAD_RAW='{"iat":'"${IAT}"',"exp":'"${EXP}"',"iss":'"${GITHUB_APP_ID}"'}'
PAYLOAD=$( echo -n "${PAYLOAD_RAW}" | openssl base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n' )
HEADER_PAYLOAD="${HEADER}"."${PAYLOAD}"
SIGNATURE=$( openssl dgst -sha256 -sign <(echo -n "${PEM}") <(echo -n "${HEADER_PAYLOAD}") | openssl base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n' )
GITHUB_JWT="${HEADER_PAYLOAD}"."${SIGNATURE}"
}
if [[ "${GITHUB_APP_ID}" != "" ]] && [[ -e "${GITHUB_APP_SECRET_PATH}" ]] ; then
# Create a temporary JWT for API access
jwt_encode
# Request installation information; note that this assumes there's just one installation (this is a private GitHub app);
# if you have multiple installations you'll have to customize this to pick out the installation you are interested in
APP_TOKEN_URL="https://api.github.com/app/installations/${GITHUB_APP_INSTALLATION_ID}/access_tokens"
# Now POST to the installation token URL to generate a new access token we can use to with with the gh and hub command lines
export GITHUB_TOKEN=$( curl -s -X POST -H "Authorization: Bearer ${GITHUB_JWT}" -H "Accept: application/vnd.github.v3+json" ${APP_TOKEN_URL} | jq -r .token )
else
echo "GITHUB_APP_ID and GITHUB_APP_SECRET_PATH must be set"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment