-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
102 lines (82 loc) · 2.25 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/dvsekhvalnov/jose2go"
Rsa "github.com/dvsekhvalnov/jose2go/keys/rsa"
)
type permissions struct {
Contents string `json:"contents"`
MetaData string `json:"metadata"`
}
type body struct {
Token string `json:"token"`
ExpiresAt string `json:"expires_at"`
Permissions permissions `json:"permissions"`
RepositorySelections string `json:"repository_selections"`
}
func fetchToken(installationId string, jwt string) string {
httpposturl := "https://api.github.com/app/installations/" + installationId + "/access_tokens"
request, err := http.NewRequest("POST", httpposturl, nil)
if err != nil {
panic(err)
}
request.Header.Set("Accept", "application/vnd.github+json")
request.Header.Set("Authorization", "Bearer "+jwt)
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
responseBody, err := io.ReadAll(response.Body)
if err != nil {
panic(err)
}
res := body{}
json.Unmarshal(responseBody, &res)
return res.Token
}
func toUnixString(time time.Time) string {
return strconv.FormatInt(time.Unix(), 10)
}
func createJwtJose(appId string, key string) string {
iat := toUnixString(time.Now().Add(time.Second * -30))
exp := toUnixString(time.Now().Add(time.Second * 30))
payload := "{\"iat\":" + iat + ",\"exp\":" + exp + ",\"iss\":\"" + appId + "\"}"
privateKey, err := Rsa.ReadPrivate([]byte(key))
if err != nil {
panic(err)
}
token, err := jose.Sign(payload, jose.RS256, privateKey)
if err != nil {
panic(err)
}
return token
}
func getEnvs() (string, string, string) {
installationId, ok := os.LookupEnv("GITHUB_INSTALLATION_ID")
if !ok {
panic("GITHUB_INSTALLATION_ID not set")
}
appId, ok := os.LookupEnv("GITHUB_APP_ID")
if !ok {
panic("GITHUB_APP_ID not set")
}
privateKey, ok := os.LookupEnv("GITHUB_APP_PRIVATE_KEY")
if !ok {
panic("GITHUB_APP_PRIVATE_KEY not set")
}
return installationId, appId, strings.Replace(privateKey, "\\n", "\n", -1)
}
func main() {
installationId, appId, privateKey := getEnvs()
token := createJwtJose(appId, privateKey)
fmt.Print(fetchToken(installationId, token))
}