-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
192 lines (158 loc) · 4.41 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
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
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strconv"
"time"
"github.com/golang-jwt/jwt"
"golang.org/x/time/rate"
)
const (
githubAPIURL = "https://api.github.com"
)
var (
limiter = rate.NewLimiter(rate.Every(time.Hour/5000), 1) // 5000 requests per hour
githubAppID string
githubAppKey []byte
installationID int64
certFile string
keyFile string
port int
)
type RateLimitResponse struct {
Resources struct {
Core struct {
Limit int `json:"limit"`
Remaining int `json:"remaining"`
Reset int `json:"reset"`
} `json:"core"`
} `json:"resources"`
}
func init() {
githubAppID = os.Getenv("GITHUB_APP_ID")
githubAppKey = []byte(os.Getenv("GITHUB_APP_PRIVATE_KEY"))
installationID, _ = strconv.ParseInt(os.Getenv("GITHUB_INSTALLATION_ID"), 10, 64)
flag.StringVar(&certFile, "cert", "", "Path to TLS certificate file")
flag.StringVar(&keyFile, "key", "", "Path to TLS key file")
flag.IntVar(&port, "port", 8443, "Port to run the server on")
}
func main() {
flag.Parse()
if certFile == "" || keyFile == "" {
log.Fatal("TLS certificate and key files are required")
}
target, err := url.Parse(githubAPIURL)
if err != nil {
log.Fatal(err)
}
proxy := httputil.NewSingleHostReverseProxy(target)
proxy.ModifyResponse = modifyResponse
server := &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: http.HandlerFunc(handler(proxy)),
TLSConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
},
}
log.Printf("Starting kado-proxy HTTPS server on :%d\n", port)
log.Fatal(server.ListenAndServeTLS(certFile, keyFile))
}
func generateJWT() (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
"iat": time.Now().Unix(),
"exp": time.Now().Add(10 * time.Minute).Unix(),
"iss": githubAppID,
})
privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(githubAppKey)
if err != nil {
return "", err
}
return token.SignedString(privateKey)
}
func getInstallationToken(jwt string) (string, error) {
url := fmt.Sprintf("https://api.github.com/app/installations/%d/access_tokens", installationID)
req, err := http.NewRequest("POST", url, nil)
if err != nil {
return "", err
}
req.Header.Set("Authorization", "Bearer "+jwt)
req.Header.Set("Accept", "application/vnd.github.v3+json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
var result map[string]interface{}
if err := json.Unmarshal(body, &result); err != nil {
return "", err
}
token, ok := result["token"].(string)
if !ok {
return "", fmt.Errorf("unable to get installation token")
}
return token, nil
}
func handler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if err := limiter.Wait(r.Context()); err != nil {
http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests)
return
}
// Check if we're using a GitHub App
if githubAppID != "" && len(githubAppKey) > 0 {
jwt, err := generateJWT()
if err != nil {
http.Error(w, "Failed to generate JWT", http.StatusInternalServerError)
return
}
token, err := getInstallationToken(jwt)
if err != nil {
http.Error(w, "Failed to get installation token", http.StatusInternalServerError)
return
}
r.Header.Set("Authorization", "token "+token)
} else if auth := r.Header.Get("Authorization"); auth != "" {
// If not using a GitHub App, forward the existing Authorization header
r.Header.Set("Authorization", auth)
}
r.Host = "api.github.com"
p.ServeHTTP(w, r)
}
}
func modifyResponse(r *http.Response) error {
if r.StatusCode == http.StatusForbidden {
body, err := io.ReadAll(r.Body)
if err != nil {
return err
}
r.Body.Close()
var rateLimitResp RateLimitResponse
if err := json.Unmarshal(body, &rateLimitResp); err != nil {
return err
}
remaining := rateLimitResp.Resources.Core.Remaining
reset := time.Unix(int64(rateLimitResp.Resources.Core.Reset), 0)
waitTime := time.Until(reset)
log.Printf("Rate limit reached. Remaining: %d, Reset: %s, Waiting: %s\n", remaining, reset, waitTime)
if remaining == 0 {
time.Sleep(waitTime)
}
r.Body = io.NopCloser(io.MultiReader(bytes.NewReader(body), r.Body))
}
return nil
}