|
| 1 | +package github |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "net/http" |
| 8 | + "path" |
| 9 | + "strconv" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/golang-jwt/jwt/v4" |
| 13 | +) |
| 14 | + |
| 15 | +type GitHubApp struct { |
| 16 | + ClientId string `json:"client_id"` |
| 17 | + InstallationId int64 `json:"installation_id"` |
| 18 | + PrivateKey string `json:"private_key"` // SENSITIVE |
| 19 | +} |
| 20 | + |
| 21 | +// generateJWTtoken returns a signed JWT token used to authenticate as GitHub App |
| 22 | +func generateJWTtoken(clientId, privateKey string) (string, error) { |
| 23 | + key, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(privateKey)) |
| 24 | + if err != nil { |
| 25 | + return "", fmt.Errorf("could not parse private key: %w", err) |
| 26 | + } |
| 27 | + // GitHub rejects expiry and issue timestamps that are not an integer, |
| 28 | + // while the jwt-go library serializes to fractional timestamps. |
| 29 | + // Truncate them before passing to jwt-go. |
| 30 | + // Additionally, GitHub recommends setting this value 60 seconds in the past. |
| 31 | + iat := time.Now().Add(-60 * time.Second).Truncate(time.Second) |
| 32 | + // maximum validity 10 minutes. Here, we reduce it to 2 minutes. |
| 33 | + exp := iat.Add(2 * time.Minute) |
| 34 | + // Docs: https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-a-json-web-token-jwt-for-a-github-app#about-json-web-tokens-jwts |
| 35 | + claims := &jwt.RegisteredClaims{ |
| 36 | + IssuedAt: jwt.NewNumericDate(iat), |
| 37 | + ExpiresAt: jwt.NewNumericDate(exp), |
| 38 | + // The client ID or application ID of your GitHub App. |
| 39 | + // Use of the client ID is recommended. |
| 40 | + Issuer: clientId, |
| 41 | + } |
| 42 | + |
| 43 | + // GitHub JWT must be signed using the RS256 algorithm. |
| 44 | + token, err := jwt.NewWithClaims(jwt.SigningMethodRS256, claims).SignedString(key) |
| 45 | + if err != nil { |
| 46 | + return "", fmt.Errorf("could not sign the JWT token: %w", err) |
| 47 | + } |
| 48 | + return token, nil |
| 49 | +} |
| 50 | + |
| 51 | +// GenerateInstallationToken returns an installation token used to authenticate as GitHub App installation |
| 52 | +func GenerateInstallationToken(server string, app GitHubApp) (string, error) { |
| 53 | + // API: POST /app/installations/{installationId}/access_tokens |
| 54 | + installationId := strconv.FormatInt(app.InstallationId, 10) |
| 55 | + url := server + path.Join("/app/installations", installationId, "/access_tokens") |
| 56 | + |
| 57 | + req, err := http.NewRequest(http.MethodPost, url, nil) |
| 58 | + if err != nil { |
| 59 | + return "", fmt.Errorf("github post: new request: %s", err) |
| 60 | + } |
| 61 | + req.Header.Add("Accept", "application/vnd.github.v3+json") |
| 62 | + |
| 63 | + jtwToken, err := generateJWTtoken(app.ClientId, app.PrivateKey) |
| 64 | + if err != nil { |
| 65 | + return "", err |
| 66 | + } |
| 67 | + req.Header.Set("Authorization", "Bearer "+jtwToken) |
| 68 | + |
| 69 | + client := &http.Client{Timeout: time.Second * 5} |
| 70 | + |
| 71 | + // FIXME: add retry here... |
| 72 | + resp, err := client.Do(req) |
| 73 | + if err != nil { |
| 74 | + return "", fmt.Errorf("http client Do: %s", err) |
| 75 | + } |
| 76 | + defer resp.Body.Close() |
| 77 | + |
| 78 | + body, errBody := io.ReadAll(resp.Body) |
| 79 | + if resp.StatusCode != http.StatusCreated { |
| 80 | + if errBody != nil { |
| 81 | + return "", fmt.Errorf("generate github app installation token: status code: %d (%s)", resp.StatusCode, errBody) |
| 82 | + } |
| 83 | + return "", fmt.Errorf("generate github app installation token: status code: %d (%s)", resp.StatusCode, string(body)) |
| 84 | + } |
| 85 | + if errBody != nil { |
| 86 | + return string(body), fmt.Errorf("generate github app installation token: read body: %s", errBody) |
| 87 | + } |
| 88 | + |
| 89 | + var token struct { |
| 90 | + Value string `json:"token"` |
| 91 | + } |
| 92 | + if err := json.Unmarshal(body, &token); err != nil { |
| 93 | + return "", fmt.Errorf("error: json unmarshal: %s", err) |
| 94 | + } |
| 95 | + return token.Value, nil |
| 96 | +} |
0 commit comments