-
Notifications
You must be signed in to change notification settings - Fork 55
/
engine.go
386 lines (326 loc) · 8.7 KB
/
engine.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
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package engine
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"sync"
"time"
"github.com/gorilla/handlers"
"github.com/goware/urlx"
"github.com/infrahq/infra/internal/logging"
"github.com/infrahq/infra/internal/timer"
v1 "github.com/infrahq/infra/internal/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
grpcMetadata "google.golang.org/grpc/metadata"
"gopkg.in/square/go-jose.v2"
"gopkg.in/square/go-jose.v2/jwt"
)
type Options struct {
Registry string
Name string
Endpoint string
ForceTLSVerify bool
APIKey string
}
type RoleBinding struct {
Role string
Users []string
}
type RegistrationInfo struct {
CA string
ClusterEndpoint string
}
type jwkCache struct {
mu sync.Mutex
key *jose.JSONWebKey
lastChecked time.Time
client *http.Client
baseURL string
}
func withClientAuthUnaryInterceptor(token string) grpc.DialOption {
return grpc.WithUnaryInterceptor(func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
return invoker(grpcMetadata.AppendToOutgoingContext(context.Background(), "authorization", "Bearer "+token), method, req, reply, cc, opts...)
})
}
func (j *jwkCache) getjwk() (*jose.JSONWebKey, error) {
j.mu.Lock()
defer j.mu.Unlock()
if j.lastChecked != (time.Time{}) && time.Now().Before(j.lastChecked.Add(JWKCacheRefresh)) {
return j.key, nil
}
res, err := j.client.Get(j.baseURL + "/.well-known/jwks.json")
if err != nil {
return nil, err
}
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var response struct {
Keys []jose.JSONWebKey `json:"keys"`
}
err = json.Unmarshal(data, &response)
if err != nil {
return nil, err
}
if len(response.Keys) < 1 {
return nil, errors.New("no jwks provided by registry")
}
j.lastChecked = time.Now()
j.key = &response.Keys[0]
return &response.Keys[0], nil
}
var JWKCacheRefresh = 5 * time.Minute
type GetJWKFunc func() (*jose.JSONWebKey, error)
type HttpContextKeyEmail struct{}
func jwtMiddleware(getjwk GetJWKFunc, next http.HandlerFunc) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authorization := r.Header.Get("X-Infra-Authorization")
raw := strings.Replace(authorization, "Bearer ", "", -1)
if raw == "" {
logging.L.Debug("No bearer token found")
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
tok, err := jwt.ParseSigned(raw)
if err != nil {
logging.L.Debug("Invalid jwt signature")
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
key, err := getjwk()
if err != nil {
logging.L.Debug("Could not get jwk")
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
out := make(map[string]interface{})
cl := jwt.Claims{}
if err := tok.Claims(key, &cl, &out); err != nil {
logging.L.Debug("Invalid token claims")
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
err = cl.Validate(jwt.Expected{
Issuer: "infra",
Time: time.Now(),
})
switch {
case errors.Is(err, jwt.ErrExpired):
http.Error(w, "expired", http.StatusUnauthorized)
return
case err != nil:
logging.L.Debug("Invalid JWT")
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
email, ok := out["email"].(string)
if !ok {
logging.L.Debug("Email not found in claims")
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
ctx := r.Context()
ctx = context.WithValue(ctx, HttpContextKeyEmail{}, email)
next(w, r.WithContext(ctx))
})
}
func proxyHandler(ca []byte, bearerToken string, remote *url.URL) (http.HandlerFunc, error) {
caCertPool := x509.NewCertPool()
ok := caCertPool.AppendCertsFromPEM(ca)
if !ok {
return nil, errors.New("could not append ca to client cert bundle")
}
proxy := httputil.NewSingleHostReverseProxy(remote)
proxy.Transport = &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: caCertPool,
},
}
return func(w http.ResponseWriter, r *http.Request) {
// Sometimes the kubernetes proxy strips query string for Upgrade requests
// so we need to put that in the request body
if r.Header.Get("X-Infra-Query") != "" {
r.URL.RawQuery = r.Header.Get("X-Infra-Query")
}
email, ok := r.Context().Value(HttpContextKeyEmail{}).(string)
if !ok {
logging.L.Debug("Proxy handler unable to retrieve email from context")
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
r.Header.Del("X-Infra-Authorization")
r.Header.Set("Impersonate-User", email)
r.Header.Add("Authorization", "Bearer "+bearerToken)
http.StripPrefix("/proxy", proxy).ServeHTTP(w, r)
}, nil
}
type BearerTransport struct {
Token string
Transport http.RoundTripper
}
func (b *BearerTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if b.Token != "" {
req.Header.Set("Authorization", "Bearer "+b.Token)
}
return b.Transport.RoundTrip(req)
}
func Run(options Options) error {
u, err := urlx.Parse(options.Registry)
if err != nil {
return err
}
registry := u.Host
if u.Port() == "" {
registry += ":443"
}
tlsConfig := &tls.Config{}
if !options.ForceTLSVerify {
// TODO (https://github.com/infrahq/infra/issues/174)
// Find a way to re-use the built-in TLS verification code vs
// this custom code based on the official go TLS example code
// which states this is approximately the same.
tlsConfig.InsecureSkipVerify = true
tlsConfig.VerifyConnection = func(cs tls.ConnectionState) error {
opts := x509.VerifyOptions{
DNSName: cs.ServerName,
Intermediates: x509.NewCertPool(),
}
for _, cert := range cs.PeerCertificates[1:] {
opts.Intermediates.AddCert(cert)
}
_, err := cs.PeerCertificates[0].Verify(opts)
if err != nil {
fmt.Println("Warning: could not verify registry TLS certificates: " + err.Error())
}
return nil
}
}
creds := credentials.NewTLS(tlsConfig)
conn, err := grpc.Dial(registry, grpc.WithTransportCredentials(creds), withClientAuthUnaryInterceptor(options.APIKey))
if err != nil {
return err
}
defer conn.Close()
client := v1.NewV1Client(conn)
kubernetes, err := NewKubernetes()
if err != nil {
return err
}
uri, err := urlx.Parse(options.Registry)
if err != nil {
return err
}
uri.Scheme = "https"
timer := timer.Timer{}
timer.Start(5, func() {
ca, err := kubernetes.CA()
if err != nil {
fmt.Println(err)
return
}
endpoint := options.Endpoint
if endpoint == "" {
endpoint, err = kubernetes.Endpoint()
if err != nil {
fmt.Println(err)
return
}
}
namespace, err := kubernetes.Namespace()
if err != nil {
fmt.Println(err)
return
}
name := options.Name
if name == "" {
name, err = kubernetes.Name()
if err != nil {
fmt.Println(err)
return
}
}
saToken, err := kubernetes.SaToken()
if err != nil {
fmt.Println(err)
return
}
res, err := client.CreateDestination(context.Background(), &v1.CreateDestinationRequest{
Name: name,
Type: v1.DestinationType_KUBERNETES,
Kubernetes: &v1.CreateDestinationRequest_Kubernetes{
Ca: string(ca),
Endpoint: endpoint,
Namespace: namespace,
SaToken: saToken,
},
})
if err != nil {
fmt.Println(err)
return
}
rolesRes, err := client.ListRoles(context.Background(), &v1.ListRolesRequest{
DestinationId: res.Id,
})
if err != nil {
fmt.Println(err)
}
// convert the response into an easy to use role-user form
var rbs []RoleBinding
for _, r := range rolesRes.Roles {
var users []string
for _, u := range r.Users {
users = append(users, u.Email)
}
rbs = append(rbs, RoleBinding{Role: r.Name, Users: users})
}
err = kubernetes.UpdateRoles(rbs)
if err != nil {
fmt.Println(err)
return
}
})
defer timer.Stop()
mux := http.NewServeMux()
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
})
remote, err := url.Parse(kubernetes.config.Host)
if err != nil {
return err
}
ca, err := ioutil.ReadFile(kubernetes.config.TLSClientConfig.CAFile)
if err != nil {
return err
}
ph, err := proxyHandler(ca, kubernetes.config.BearerToken, remote)
if err != nil {
return err
}
u.Scheme = "https"
cache := jwkCache{
client: &http.Client{
Transport: &BearerTransport{
Token: options.APIKey,
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
},
},
},
baseURL: u.String(),
}
mux.Handle("/proxy/", jwtMiddleware(cache.getjwk, ph))
fmt.Println("serving on port 80")
return http.ListenAndServe(":80", handlers.LoggingHandler(os.Stdout, mux))
}