forked from github/github-mcp-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithubapp.go
More file actions
221 lines (194 loc) · 6.27 KB
/
Copy pathgithubapp.go
File metadata and controls
221 lines (194 loc) · 6.27 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// Package githubapp provides GitHub App installation access tokens.
package githubapp
import (
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"strings"
"sync"
"time"
"golang.org/x/oauth2"
)
const (
jwtLifetime = 9 * time.Minute
clockSkew = time.Minute
refreshBuffer = 5 * time.Minute
httpTimeout = 30 * time.Second
)
// Config describes a GitHub App installation used for server-to-server auth.
type Config struct {
// AppID is used as the JWT issuer. GitHub accepts an app ID or client ID.
AppID string
// InstallationID identifies the installation whose access token is minted.
InstallationID string
// PrivateKeyPEM is the RSA key used to sign app JWTs.
PrivateKeyPEM []byte
// BaseRESTURL is the REST API base, e.g. https://api.github.com/ for
// github.com or https://HOST/api/v3/ for GitHub Enterprise Server.
BaseRESTURL string
}
func (c Config) validate() error {
switch {
case c.AppID == "":
return errors.New("GitHub App ID or client ID is required (GITHUB_APP_ID)")
case c.InstallationID == "":
return errors.New("GitHub App installation ID is required (GITHUB_APP_INSTALLATION_ID)")
case len(c.PrivateKeyPEM) == 0:
return errors.New("GitHub App private key is required (GITHUB_APP_PRIVATE_KEY_PATH or GITHUB_APP_PRIVATE_KEY)")
case c.BaseRESTURL == "":
return errors.New("GitHub App REST base URL is required")
}
return nil
}
func parsePrivateKey(pemBytes []byte) (*rsa.PrivateKey, error) {
block, _ := pem.Decode(pemBytes)
if block == nil {
return nil, errors.New("no PEM block found in private key")
}
if key, err := x509.ParsePKCS1PrivateKey(block.Bytes); err == nil {
return key, nil
}
parsed, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("parsing private key (want PKCS#1 or PKCS#8 RSA): %w", err)
}
key, ok := parsed.(*rsa.PrivateKey)
if !ok {
return nil, fmt.Errorf("private key is %T, want an RSA key", parsed)
}
return key, nil
}
func mintJWT(appID string, privateKey *rsa.PrivateKey, now time.Time) (string, error) {
header := map[string]string{"alg": "RS256", "typ": "JWT"}
claims := map[string]any{
"iat": now.Add(-clockSkew).Unix(),
"exp": now.Add(jwtLifetime).Unix(),
"iss": appID,
}
headerJSON, err := json.Marshal(header)
if err != nil {
return "", fmt.Errorf("encoding JWT header: %w", err)
}
claimsJSON, err := json.Marshal(claims)
if err != nil {
return "", fmt.Errorf("encoding JWT claims: %w", err)
}
signingInput := base64.RawURLEncoding.EncodeToString(headerJSON) + "." +
base64.RawURLEncoding.EncodeToString(claimsJSON)
digest := sha256.Sum256([]byte(signingInput))
signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, digest[:])
if err != nil {
return "", fmt.Errorf("signing JWT: %w", err)
}
return signingInput + "." + base64.RawURLEncoding.EncodeToString(signature), nil
}
type installationTokenSource struct {
cfg Config
privateKey *rsa.PrivateKey
httpClient *http.Client
}
func newInstallationTokenSource(cfg Config, privateKey *rsa.PrivateKey, httpClient *http.Client) *installationTokenSource {
if httpClient == nil {
httpClient = &http.Client{Timeout: httpTimeout}
}
return &installationTokenSource{cfg: cfg, privateKey: privateKey, httpClient: httpClient}
}
func (s *installationTokenSource) Token() (*oauth2.Token, error) {
jwt, err := mintJWT(s.cfg.AppID, s.privateKey, time.Now())
if err != nil {
return nil, err
}
endpoint, err := url.JoinPath(s.cfg.BaseRESTURL, "app", "installations", s.cfg.InstallationID, "access_tokens")
if err != nil {
return nil, fmt.Errorf("building installation token URL: %w", err)
}
ctx, cancel := context.WithTimeout(context.Background(), httpTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, nil)
if err != nil {
return nil, fmt.Errorf("creating installation token request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+jwt)
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
resp, err := s.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("requesting installation token: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusCreated {
snippet, readErr := io.ReadAll(io.LimitReader(resp.Body, 512))
if readErr != nil {
return nil, fmt.Errorf("installation token request failed: %s (reading response: %w)", resp.Status, readErr)
}
return nil, fmt.Errorf("installation token request failed: %s: %s", resp.Status, strings.TrimSpace(string(snippet)))
}
var body struct {
Token string `json:"token"`
ExpiresAt time.Time `json:"expires_at"`
}
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
return nil, fmt.Errorf("decoding installation token response: %w", err)
}
if body.Token == "" {
return nil, errors.New("installation token response did not contain a token")
}
if body.ExpiresAt.IsZero() {
return nil, errors.New("installation token response did not contain an expiry")
}
return &oauth2.Token{
AccessToken: body.Token,
TokenType: "token",
Expiry: body.ExpiresAt.Add(-refreshBuffer),
}, nil
}
// Provider caches and refreshes GitHub App installation access tokens.
type Provider struct {
source oauth2.TokenSource
logger *slog.Logger
mu sync.Mutex
errLogged bool
}
func NewProvider(cfg Config, logger *slog.Logger) (*Provider, error) {
if err := cfg.validate(); err != nil {
return nil, err
}
privateKey, err := parsePrivateKey(cfg.PrivateKeyPEM)
if err != nil {
return nil, fmt.Errorf("invalid GitHub App private key: %w", err)
}
if logger == nil {
logger = slog.Default()
}
source := oauth2.ReuseTokenSource(nil, newInstallationTokenSource(cfg, privateKey, nil))
return &Provider{source: source, logger: logger}, nil
}
// AccessToken returns a cached token or refreshes it before expiry.
func (p *Provider) AccessToken() string {
tok, err := p.source.Token()
if err != nil {
p.mu.Lock()
if !p.errLogged {
p.errLogged = true
p.logger.Error("failed to obtain GitHub App installation token", "error", err)
}
p.mu.Unlock()
return ""
}
p.mu.Lock()
p.errLogged = false
p.mu.Unlock()
return tok.AccessToken
}