-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
87 lines (72 loc) · 2.2 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
package main
import (
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"io"
"os"
)
func main() {
b, ok := os.LookupEnv("APP_PRIVATE_KEY")
if !ok {
setFailed("Private key env not set", "Environment variable APP_PRIVATE_KEY is not set")
}
appID, ok := os.LookupEnv("APP_ID")
if !ok {
setFailed("App ID not set", "Environment variable APP_ID is not set")
}
appInstId, ok := os.LookupEnv("APP_INSTALLATION_ID")
if !ok {
setFailed("App installation ID not set", "Environment variable APP_INSTALLATION_ID is not set")
}
pemBytes, err := base64.StdEncoding.DecodeString(b)
if err != nil {
setFailed("Base64 decode failed", "PEM secret should be base64 encoded")
return
}
key, err := loadPEMFromBytes(pemBytes)
if err != nil {
setFailed("Invalid PEM key", fmt.Sprintf("Unable to load PEM. err: %s", err))
}
jwt := issueJWTFromPEM(appID, key)
token, err := getInstallationToken(appInstId, jwt)
if err != nil {
setFailed("Failed to get installation key", fmt.Sprintf("Unable to get intallation token. err: %s", err))
}
githubOutputFile, err := openGitHubOutput(os.Getenv("GITHUB_OUTPUT"))
if err != nil {
setFailed("Failed to set the output 'token'", fmt.Sprintf("Unable to open GITHUB_OUTPUT. err: %s", err))
return
}
defer githubOutputFile.Close()
if err := setOutput(githubOutputFile, "token", token); err != nil {
setFailed("Failed to set the output 'token'", fmt.Sprintf("Unable to write the token to GITHUB_OUTPUT. err: %s", err))
}
}
func loadPEMFromBytes(key []byte) (*rsa.PrivateKey, error) {
b, _ := pem.Decode(key)
if b != nil {
key = b.Bytes
}
parsedKey, err := x509.ParsePKCS1PrivateKey(key)
if err != nil {
return nil, fmt.Errorf("private key should be a PKCS1 key; parse error: %v", err)
}
return parsedKey, nil
}
func openGitHubOutput(p string) (io.WriteCloser, error) {
return os.OpenFile(p, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
}
func setOutput(file io.Writer, name, value string) error {
if _, err := file.Write([]byte(fmt.Sprintf("%s=%s\n", name, value))); err != nil {
return err
}
return nil
}
func setFailed(title, msg string) {
// output error to stdout and exit 1
fmt.Printf("::error title=%s::%s", title, msg)
os.Exit(1)
}