1111
1212set -o pipefail
1313
14- _GITHUB_HOST=${GITHUB_HOST:= " github.com" }
14+ APP_ID=$( cat $1 ) # Path to appid.env
15+ PRIVATE_KEY_PATH=$2 # Path to key_private.pem
1516
16- # If URL is not github.com then use the enterprise api endpoint
17- if [[ ${GITHUB_HOST} = " github.com" ]]; then
18- URI=" https://api.${_GITHUB_HOST} "
19- else
20- URI=" https://${_GITHUB_HOST} /api/v3"
21- fi
17+ # Generate JWT
18+ header=' {"alg":"RS256","typ":"JWT"}'
19+ payload=" {\" iat\" :$( date +%s) ,\" exp\" :$(( $(date +% s) + 600 )) ,\" iss\" :${APP_ID} }"
2220
23- API_VERSION=v3
24- API_HEADER=" Accept: application/vnd.github.${API_VERSION} +json"
25- CONTENT_LENGTH_HEADER=" Content-Length: 0"
26- APP_INSTALLATIONS_URI=" ${URI} /app/installations"
21+ header_base64=$( echo -n " $header " | openssl base64 | tr -d ' =' | tr ' /+' ' _-' | tr -d ' \n' )
22+ payload_base64=$( echo -n " $payload " | openssl base64 | tr -d ' =' | tr ' /+' ' _-' | tr -d ' \n' )
2723
24+ signature=$( echo -n " ${header_base64} .${payload_base64} " | \
25+ openssl dgst -sha256 -sign " $PRIVATE_KEY_PATH " | \
26+ openssl base64 | tr -d ' =' | tr ' /+' ' _-' | tr -d ' \n' )
2827
29- # JWT parameters based off
30- # https://docs.github.com/en/developers/apps/building-github-apps/authenticating-with-github-apps#authenticating-as-a-github-app
31- #
32- # JWT token issuance and expiration parameters
33- JWT_IAT_DRIFT=60
34- JWT_EXP_DELTA=600
35-
36- JWT_JOSE_HEADER=' {
37- "alg": "RS256",
38- "typ": "JWT"
39- }'
40-
41-
42- build_jwt_payload () {
43- now=$( date +%s)
44- iat=$(( now - JWT_IAT_DRIFT))
45- jq -c \
46- --arg iat_str " ${iat} " \
47- --arg exp_delta_str " ${JWT_EXP_DELTA} " \
48- --arg app_id_str " ${APP_ID} " \
49- '
50- ($iat_str | tonumber) as $iat
51- | ($exp_delta_str | tonumber) as $exp_delta
52- | ($app_id_str | tonumber) as $app_id
53- | .iat = $iat
54- | .exp = ($iat + $exp_delta)
55- | .iss = $app_id
56- ' <<< " {}" | tr -d ' \n'
57- }
58-
59- base64url () {
60- base64 | tr ' +/' ' -_' | tr -d ' =\n'
61- }
62-
63- rs256_sign () {
64- openssl dgst -binary -sha256 -sign <( echo " $1 " )
65- }
66-
67- request_access_token () {
68- jwt_payload=$( build_jwt_payload)
69- encoded_jwt_parts=$( base64url <<< " ${JWT_JOSE_HEADER}" ) .$( base64url <<< " ${jwt_payload}" )
70- encoded_mac=$( echo -n " $encoded_jwt_parts " | rs256_sign " ${APP_PRIVATE_KEY} " | base64url)
71- generated_jwt=" ${encoded_jwt_parts} .${encoded_mac} "
72-
73- auth_header=" Authorization: Bearer ${generated_jwt} "
74-
75- app_installations_response=$( curl -sX POST \
76- -H " ${auth_header} " \
77- -H " ${API_HEADER} " \
78- --header " X-GitHub-Api-Version: 2022-11-28" \
79- --url " https://api.github.com/app/installations/${INSTALL_ID} /access_tokens" \
80- )
81- echo " $app_installations_response " | jq --raw-output ' .token'
82- }
83-
84- request_access_token
28+ jwt=" ${header_base64} .${payload_base64} .${signature} "
29+ echo " ACCESS_TOKEN=${jwt} " > " ${DST_FILE} "
0 commit comments