This repository was archived by the owner on May 1, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
355 lines (310 loc) · 10.3 KB
/
main.go
File metadata and controls
355 lines (310 loc) · 10.3 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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
// Copyright 2021 the GitHub Runner Token Proxy authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"crypto/rsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"os/signal"
"regexp"
"strings"
"syscall"
"time"
"github.com/sethvargo/github-runner-token-proxy/internal/logging"
)
var (
// bind is the interface address on which to bind (default: all). port is the
// port on which the container should listen.
bind = envOrDefault("BIND", "")
port = envOrDefault("PORT", "8080")
// githubToken is the GitHub personal access token, injected via the Cloud Run
// Secret Sanager integration.
githubToken = envOrDefault("GITHUB_TOKEN", "")
// githubAppID is the ID of your GitHub App. githubAppPrivateKey is the RSA
// private key for your app; it should be loaded from Secret Manager.
// githubInstallationID is the specific installation to target for getting
// permissions to register the runners.
githubAppID = envOrDefault("GITHUB_APP_ID", "")
githubAppPrivateKey = envRSAPrivateKey("GITHUB_APP_PRIVATE_KEY", nil)
githubInstallationID = envOrDefault("GITHUB_INSTALLATION_ID", "")
// githubAPIURL is the endpoint where the GitHub API can be found. It defaults
// to the public github.com installation. This can be set to the enterprise
// API endpoint (which is usually) "(url)/api/v3" on GitHub Enterprise
// installations.
githubAPIURL = envOrDefault("GITHUB_API_URL", "https://api.github.com")
// allowedScopes is the list of allowed repos or owner names. By default, no
// scopes are allowed. Set this value to "match:*" to allow all, but it is
// better to specify a set or repositories for security.
//
// Values are treated as literal string matches unless prefixed with "match:",
// in which case the value is treated as a regular expression.
allowedScopes = envOrDefaultRegexSlice("ALLOWED_SCOPES", nil)
// deniedScopes is an optional list of denied repos or owner names. This takes
// priority over the allowlist.
//
// Values are treated as literal string matches unless prefixed with "match:",
// in which case the value is treated as a regular expression.
deniedScopes = envOrDefaultRegexSlice("DENIED_SCOPES", nil)
// httpClient is the default HTTP client.
httpClient = &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
ForceAttemptHTTP2: true,
DisableKeepAlives: true,
MaxIdleConnsPerHost: -1,
},
}
// logger is the structured logger.
logger = logging.NewLogger(os.Stdout, os.Stderr)
)
func main() {
ctx, done := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer done()
if err := realMain(ctx); err != nil {
done()
logger.Fatal("error from main process", "error", err)
}
logger.Info("shutting down")
}
func realMain(ctx context.Context) error {
var ts TokenSource
switch {
case githubAppID != "" && githubInstallationID != "" && githubAppPrivateKey != nil:
ts = &githubAppTokenSource{
appID: githubAppID,
installationID: githubInstallationID,
privateKey: githubAppPrivateKey,
}
case githubToken != "":
ts = &staticTokenSource{
token: githubToken,
}
default:
return fmt.Errorf("missing [GITHUB_TOKEN] or [GITHUB_APP_ID, GITHUB_APP_PRIVATE_KEY, GITHUB_INSTALLATION_ID]")
}
mux := http.NewServeMux()
mux.Handle("/register", handleToken(ts, "registration-token"))
mux.Handle("/remove", handleToken(ts, "remove-token"))
server := &http.Server{
Addr: bind + ":" + port,
Handler: mux,
}
serverErrCh := make(chan error, 1)
go func() {
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
select {
case serverErrCh <- err:
default:
}
}
}()
// Wait for shutdown signal or error from the listener.
select {
case err := <-serverErrCh:
return fmt.Errorf("error from server listener: %w", err)
case <-ctx.Done():
}
// Gracefully shut down the server.
shutdownCtx, done := context.WithTimeout(context.Background(), 5*time.Second)
defer done()
if err := server.Shutdown(shutdownCtx); err != nil {
return fmt.Errorf("failed to shutdown server: %w", err)
}
return nil
}
// TokenRequest is a generic token request.
type TokenRequest struct {
Scope string `json:"scope"`
}
func handleToken(ts TokenSource, typ string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method != "POST" {
logger.Warn("expected http method to be POST, got %q", r.Method)
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
var tr TokenRequest
lr := io.LimitReader(r.Body, 64*1024) // 64kb
dec := json.NewDecoder(lr)
dec.DisallowUnknownFields()
if err := dec.Decode(&tr); err != nil {
logger.Warn("failed to decode request", "error", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
scope := strings.Trim(tr.Scope, "/")
if scope == "" {
logger.Warn("missing scope in request body")
http.Error(w, "missing scope in request body", http.StatusBadRequest)
return
}
// Parse the deny list first, since it takes priority.
for _, entry := range deniedScopes {
if entry.MatchString(scope) {
logger.Warn("scope is in denied list", "scope", scope)
http.Error(w, "scope is not allowed", http.StatusUnauthorized)
return
}
}
// Ensure the scope is allowed.
foundMatch := false
for _, entry := range allowedScopes {
if entry.MatchString(scope) {
foundMatch = true
break
}
}
if !foundMatch {
logger.Warn("scope is not allowed", "scope", scope)
http.Error(w, "scope is not allowed", http.StatusUnauthorized)
return
}
rtr, err := githubTokenRequest(ctx, ts, scope, typ)
if err != nil {
logger.Warn("failed to make token request", "error", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
b, err := json.Marshal(rtr)
if err != nil {
logger.Error("failed to marshal json response", "error", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(200)
_, _ = w.Write(b)
})
}
// TokenResponse is a generic token response.
type TokenResponse struct {
Token string `json:"token"`
}
// githubTokenRequest is a generic request for GitHub runner tokens.
func githubTokenRequest(ctx context.Context, ts TokenSource, scope, subpath string) (*TokenResponse, error) {
var parent string
switch strings.Count(scope, "/") {
case 0:
parent = "orgs"
case 1:
parent = "repos"
default:
return nil, fmt.Errorf("invalid scope %q", scope)
}
// Fetch the token from the token source.
token, err := ts.Token(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get auth token: %w", err)
}
// e.g. https://api.github.com/repos/[owner]/[name]/actions/runners/registration-token
// e.g. https://api.github.com/orgs/[name]/actions/runners/registration-token
pth := strings.TrimSuffix(githubAPIURL, "/") + "/" + parent + "/" + scope + "/actions/runners/" + subpath
req, err := http.NewRequestWithContext(ctx, "POST", pth, nil)
if err != nil {
return nil, fmt.Errorf("failed to create token request: %w", err)
}
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to make token request: %w", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(io.LimitReader(resp.Body, 64*1024)) // 64kb
if err != nil {
return nil, fmt.Errorf("failed to read token response: %w", err)
}
// Ensure successful response.
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("bad response from token request (%d): %s", resp.StatusCode, body)
}
var tr TokenResponse
if err := json.Unmarshal(body, &tr); err != nil {
return nil, fmt.Errorf("failed to unmarshal token: %w", err)
}
return &tr, nil
}
// envOrDefault returns the value in the environment variable. If the value is
// empty, it returns the default value.
func envOrDefault(key, def string) string {
v := os.Getenv(key)
if v == "" {
return def
}
return v
}
// envOrDefaultRegexSlice returns the value in the environment variable, parsed
// as a semi-colon separated of values into a slice of regular expressions. If
// no value is present, it returns the default. It panics if any of the regular
// expressions cannot compile.
//
// Why not commas? Well gcloud already uses commas and its pattern for escaping
// is quite bonkers, so we just picked a different character.
func envOrDefaultRegexSlice(key string, def []*regexp.Regexp) []*regexp.Regexp {
v := os.Getenv(key)
if v == "" {
return def
}
// Trim all whitespace and remove blank entries.
split := strings.Split(v, ";")
parts := make([]*regexp.Regexp, 0, len(split))
for _, p := range split {
tr := strings.TrimSpace(p)
if tr != "" {
if strings.HasPrefix(tr, "match:") {
tr = tr[6:]
} else {
tr = `\A` + regexp.QuoteMeta(tr) + `\z`
}
re := regexp.MustCompile(tr)
parts = append(parts, re)
}
}
return parts
}
// envRSAPrivateKey parses the given env as a PEM-encoded RSA private key.
func envRSAPrivateKey(key string, def *rsa.PrivateKey) *rsa.PrivateKey {
val := os.Getenv(key)
if val == "" {
return def
}
block, _ := pem.Decode([]byte(val))
if block == nil {
panic(fmt.Errorf("failed to parse pem block"))
}
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
panic(fmt.Errorf("failed to parse private key: %w", err))
}
return privateKey
}