Skip to content

WIP: Acceptable use of GitHub authentication and authorisation mechanisms #309

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Large diffs are not rendered by default.

32 changes: 32 additions & 0 deletions decisions/assets/ADR-003/examples/bash/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Example: Get GitHub App access token in Bash

Dependencies are `openssl`, `curl`, `jq` and `gh`.

Prepare environment:

```bash
export GITHUB_APP_ID=...
export GITHUB_APP_PK_FILE=...
export GITHUB_ORG="nhs-england-tools"
```

Run script:

```bash
$ cd docs/adr/assets/ADR-003/examples/bash
$ ./script.sh
GITHUB_TOKEN=ghs_...
```

Check the token:

```bash
$ GITHUB_TOKEN=ghs_...; echo "$GITHUB_TOKEN" | gh auth login --with-token
$ gh auth status
github.com
✓ Logged in to github.com as nhs-england-update-from-template[bot] (keyring)
✓ Git operations for github.com configured to use https protocol.
✓ Token: ghs_************************************
```

See the [example (script.sh)](./script.sh) implementation. This script has been written to illustrate the concept in a clear and simple way. It is not a production ready code.
46 changes: 46 additions & 0 deletions decisions/assets/ADR-003/examples/bash/script.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#!/bin/bash

function main() {

if [[ -z "$GITHUB_APP_ID" || -z "$GITHUB_APP_PK_FILE" || -z "$GITHUB_ORG" ]]; then
echo "Environment variables GITHUB_APP_ID, GITHUB_APP_PK_FILE and GITHUB_ORG must be passed to this program."
exit 1
fi

jwt_token=$(get-jwt-token)
installation_id=$(get-installation-id)
access_token=$(get-access-token)

echo "GITHUB_TOKEN=$access_token"
}

function get-jwt-token() {

header=$(echo -n '{"alg":"RS256","typ":"JWT"}' | base64 | tr -d '=' | tr -d '\n=' | tr -- '+/' '-_')
payload=$(echo -n '{"iat":'"$(date +%s)"',"exp":'$(($(date +%s)+600))',"iss":"'"$GITHUB_APP_ID"'"}' | base64 | tr -d '\n=' | tr -- '+/' '-_')
signature=$(echo -n "$header.$payload" | openssl dgst -binary -sha256 -sign "$GITHUB_APP_PK_FILE" | openssl base64 | tr -d '\n=' | tr -- '+/' '-_')

echo "$header.$payload.$signature"
}

function get-installation-id() {

installations_response=$(curl -sX GET \
-H "Authorization: Bearer $jwt_token" \
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/app/installations)

echo "$installations_response" | jq '.[] | select(.account.login == "'"$GITHUB_ORG"'") .id'
}

function get-access-token() {

token_response=$(curl -sX POST \
-H "Authorization: Bearer $jwt_token" \
-H "Accept: application/vnd.github.v3+json" \
"https://api.github.com/app/installations/$installation_id/access_tokens")

echo "$token_response" | jq .token -r
}

main
32 changes: 32 additions & 0 deletions decisions/assets/ADR-003/examples/golang/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Example: Get GitHub App access token in Golang

Dependencies are listed in the `go.mod` file.

Prepare environment:

```bash
export GITHUB_APP_ID=...
export GITHUB_APP_PK_FILE=...
export GITHUB_ORG="nhs-england-tools"
```

Run script:

```bash
$ cd docs/adr/assets/ADR-003/examples/golang
$ go run main.go
GITHUB_TOKEN=ghs_...
```

Check the token:

```bash
$ GITHUB_TOKEN=ghs_...; echo "$GITHUB_TOKEN" | gh auth login --with-token
$ gh auth status
github.com
✓ Logged in to github.com as nhs-england-update-from-template[bot] (keyring)
✓ Git operations for github.com configured to use https protocol.
✓ Token: ghs_************************************
```

See the [example (main.go)](./main.go) implementation. This script has been written to illustrate the concept in a clear and simple way. It is not a production ready code.
10 changes: 10 additions & 0 deletions decisions/assets/ADR-003/examples/golang/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module github-app-get-tokent

go 1.21.0

require (
github.com/go-resty/resty/v2 v2.7.0
github.com/golang-jwt/jwt v3.2.2+incompatible
)

require golang.org/x/net v0.7.0 // indirect
12 changes: 12 additions & 0 deletions decisions/assets/ADR-003/examples/golang/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
github.com/go-resty/resty/v2 v2.7.0 h1:me+K9p3uhSmXtrBZ4k9jcEAfJmuC8IivWHwaLZwPrFY=
github.com/go-resty/resty/v2 v2.7.0/go.mod h1:9PWDzw47qPphMRFfhsyk0NnSgvluHcljSMVIq3w7q0I=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
golang.org/x/net v0.0.0-20211029224645-99673261e6eb/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g=
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
88 changes: 88 additions & 0 deletions decisions/assets/ADR-003/examples/golang/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package main

import (
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"log"
"os"
"time"

"github.com/go-resty/resty/v2"
"github.com/golang-jwt/jwt"
)

type Installation struct {
ID int `json:"id"`
Account struct {
Login string `json:"login"`
} `json:"account"`
}

func main() {

ghAppId := os.Getenv("GITHUB_APP_ID")
ghAppPkFile := os.Getenv("GITHUB_APP_PK_FILE")
ghOrg := os.Getenv("GITHUB_ORG")

if ghAppId == "" || ghAppPkFile == "" || ghOrg == "" {
log.Fatalf("Environment variables GITHUB_APP_ID, GITHUB_APP_PK_FILE and GITHUB_ORG must be passed to this program.")
}

jwtToken := getJwtToken(ghAppId, ghAppPkFile)
installationId := getInstallationId(jwtToken, ghOrg)
accessToken := getAccessToken(jwtToken, installationId)

fmt.Printf("GITHUB_TOKEN=%s\n", accessToken)
}

func getJwtToken(ghAppId string, ghAppPkFile string) string {

pemContent, _ := ioutil.ReadFile(ghAppPkFile)
block, _ := pem.Decode(pemContent)
privateKey, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
"iat": time.Now().Unix(),
"exp": time.Now().Add(10 * time.Minute).Unix(),
"iss": ghAppId,
})
jwtToken, _ := token.SignedString(privateKey)

return jwtToken
}

func getInstallationId(jwtToken string, ghOrg string) int {

client := resty.New()
resp, _ := client.R().
SetHeader("Authorization", "Bearer "+jwtToken).
SetHeader("Accept", "application/vnd.github.v3+json").
Get("https://api.github.com/app/installations")

var installations []Installation
json.Unmarshal(resp.Body(), &installations)
installationId := 0
for _, installation := range installations {
if installation.Account.Login == ghOrg {
installationId = installation.ID
}
}

return installationId
}

func getAccessToken(jwtToken string, installationId int) string {

client := resty.New()
resp, _ := client.R().
SetHeader("Authorization", "Bearer "+jwtToken).
SetHeader("Accept", "application/vnd.github.v3+json").
Post(fmt.Sprintf("https://api.github.com/app/installations/%d/access_tokens", installationId))

var result map[string]interface{}
json.Unmarshal(resp.Body(), &result)

return result["token"].(string)
}
134 changes: 134 additions & 0 deletions decisions/assets/ADR-003/examples/nodejs/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
yarn.lock

SEE: https://github.com/github/gitignore/blob/main/Node.gitignore

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp
.cache

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
29 changes: 29 additions & 0 deletions decisions/assets/ADR-003/examples/nodejs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Example: Get GitHub App access token in Node.js TypeScript (using Octokit)

Dependencies are listed in the `package.json` file.

Prepare environment:

```bash
export GITHUB_APP_ID=...
export GITHUB_APP_PK_FILE=...
export GITHUB_ORG="nhs-england-tools"
```

Run script:

```bash
$ cd docs/adr/assets/ADR-003/examples/nodejs
$ yarn install
$ yarn start
[
{
name: 'repository-template',
full_name: 'nhs-england-tools/repository-template',
private: false,
owner: {
login: 'nhs-england-tools',
...
```

See the [example (main.ts)](./main.ts) implementation. This script has been written to illustrate the concept in a clear and simple way. It is not a production ready code.
Loading