|
| 1 | +package auth |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/rsa" |
| 6 | + "crypto/x509" |
| 7 | + "encoding/pem" |
| 8 | + "errors" |
| 9 | + "fmt" |
| 10 | + "github.com/dgrijalva/jwt-go" |
| 11 | + "github.com/google/go-github/v40/github" |
| 12 | + "golang.org/x/oauth2" |
| 13 | + "k8s.io/klog/v2" |
| 14 | + "time" |
| 15 | +) |
| 16 | + |
| 17 | +var ErrInvalidKey = errors.New("invalid key") |
| 18 | + |
| 19 | +// signJWTFromPEM returns a signed JWT from a PEM-encoded private key. |
| 20 | +func signJWTFromPEM(key []byte, appId int64) (string, error) { |
| 21 | + // decode PEM |
| 22 | + block, _ := pem.Decode(key) |
| 23 | + if block == nil { |
| 24 | + return "", ErrInvalidKey |
| 25 | + } |
| 26 | + |
| 27 | + // parse key |
| 28 | + privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes) |
| 29 | + if err != nil { |
| 30 | + return "", err |
| 31 | + } |
| 32 | + |
| 33 | + // sign |
| 34 | + return signJWT(privateKey, appId) |
| 35 | +} |
| 36 | + |
| 37 | +func signJWT(privateKey *rsa.PrivateKey, appId int64) (string, error) { |
| 38 | + // sign |
| 39 | + token := jwt.NewWithClaims(jwt.SigningMethodRS256, |
| 40 | + jwt.MapClaims{ |
| 41 | + "exp": time.Now().Add(10 * time.Minute).Unix(), |
| 42 | + "iat": time.Now().Unix(), |
| 43 | + "iss": fmt.Sprintf("%d", appId), |
| 44 | + }) |
| 45 | + |
| 46 | + tokenString, err := token.SignedString(privateKey) |
| 47 | + if err != nil { |
| 48 | + return "", err |
| 49 | + } |
| 50 | + |
| 51 | + return tokenString, nil |
| 52 | +} |
| 53 | + |
| 54 | +func GetInstallationToken(privateKey []byte, appId int64) (string, error) { |
| 55 | + token, err := signJWTFromPEM(privateKey, appId) |
| 56 | + if err != nil { |
| 57 | + klog.Exitf("failed to sign JWT: %v", err) |
| 58 | + } |
| 59 | + |
| 60 | + // get installation access token for app |
| 61 | + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 62 | + defer cancel() |
| 63 | + ts := oauth2.StaticTokenSource( |
| 64 | + &oauth2.Token{AccessToken: token}, |
| 65 | + ) |
| 66 | + tc := oauth2.NewClient(ctx, ts) |
| 67 | + client := github.NewClient(tc) |
| 68 | + is, _, err := client.Apps.ListInstallations(ctx, nil) |
| 69 | + if err != nil { |
| 70 | + klog.Exitf("failed to list installations: %v", err) |
| 71 | + } |
| 72 | + |
| 73 | + for _, i := range is { |
| 74 | + if i.GetAppID() == appId { |
| 75 | + klog.Infof("installation id: %v", i.GetID()) |
| 76 | + klog.Infof("installed on %s: %s", i.GetTargetType(), i.GetAccount().GetLogin()) |
| 77 | + } |
| 78 | + |
| 79 | + // Get an installation token |
| 80 | + it, _, err := client.Apps.CreateInstallationToken(ctx, i.GetID(), nil) |
| 81 | + if err != nil { |
| 82 | + klog.Exitf("failed to create installation token: %v", err) |
| 83 | + } |
| 84 | + |
| 85 | + return it.GetToken(), nil |
| 86 | + } |
| 87 | + |
| 88 | + return "", errors.New("no installation found") |
| 89 | +} |
0 commit comments