/
server.go
454 lines (387 loc) · 15.2 KB
/
server.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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
package server
import (
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"time"
"github.com/cenk/backoff"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
"k8s.io/client-go/tools/cache"
saassigner "github.com/imduffy15/k8s-gke-service-account-assigner"
"github.com/imduffy15/k8s-gke-service-account-assigner/iam"
"github.com/imduffy15/k8s-gke-service-account-assigner/k8s"
"github.com/imduffy15/k8s-gke-service-account-assigner/mappings"
"cloud.google.com/go/compute/metadata"
)
const (
defaultAppPort = "8181"
defaultCacheSyncAttempts = 10
defaultIAMServiceAccountKey = "accounts.google.com/service-account"
defaultIAMScopeKey = "accounts.google.com/scopes"
defaultLogLevel = "info"
defaultLogFormat = "text"
defaultMaxElapsedTime = 2 * time.Second
defaultMaxInterval = 1 * time.Second
defaultMetadataAddress = "169.254.169.254"
defaultMetadataProxyAddress = "127.0.0.1:988"
defaultEnableMetadataProxy = false
defaultNamespaceKey = "accounts.google.com/allowed-service-accounts"
)
// Server encapsulates all of the parameters necessary for starting up
// the server. These can either be set via command line or directly.
type Server struct {
APIServer string
APIToken string
AppPort string
IAMServiceAccountKey string
IAMScopeKey string
DefaultServiceAccount string
DefaultScopes string
MetadataAddress string
MetadataProxyAddress string
HostInterface string
HostIP string
NodeName string
NamespaceKey string
LogLevel string
LogFormat string
AddIPTablesRule bool
Debug bool
EnableMetadataProxy bool
Insecure bool
NamespaceRestriction bool
Verbose bool
Version bool
iam *iam.Client
k8s *k8s.Client
serviceAccountMapper *mappings.ServiceAccountMapper
BackoffMaxElapsedTime time.Duration
BackoffMaxInterval time.Duration
}
type appHandler func(*log.Entry, http.ResponseWriter, *http.Request)
type responseWriter struct {
http.ResponseWriter
statusCode int
}
func (rw *responseWriter) WriteHeader(code int) {
rw.statusCode = code
rw.ResponseWriter.WriteHeader(code)
}
func newResponseWriter(w http.ResponseWriter) *responseWriter {
return &responseWriter{w, http.StatusOK}
}
// ServeHTTP implements the net/http server Handler interface
// and recovers from panics.
func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
logger := log.WithFields(log.Fields{
"req.method": r.Method,
"req.path": r.URL.Path,
"req.remote": parseRemoteAddr(r.RemoteAddr),
})
start := time.Now()
defer func() {
var err error
if rec := recover(); rec != nil {
switch t := rec.(type) {
case string:
err = errors.New(t)
case error:
err = t
default:
err = errors.New("unknown error")
}
logger.WithField("res.status", http.StatusInternalServerError).
Errorf("PANIC error processing request: %+v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}()
rw := newResponseWriter(w)
fn(logger, rw, r)
if r.URL.Path != "/healthz" {
latency := time.Since(start)
logger.WithFields(log.Fields{"res.duration": latency.Nanoseconds(), "res.status": rw.statusCode}).
Infof("%s %s (%d) took %d ns", r.Method, r.URL.Path, rw.statusCode, latency.Nanoseconds())
}
}
func parseRemoteAddr(addr string) string {
n := strings.IndexByte(addr, ':')
if n <= 1 {
return ""
}
hostname := addr[0:n]
if net.ParseIP(hostname) == nil {
return ""
}
return hostname
}
// xForwardedForStripper is identical to http.DefaultTransport except that it
// strips X-Forwarded-For headers. It fulfills the http.RoundTripper
// interface.
type xForwardedForStripper struct{}
// RoundTrip wraps the http.DefaultTransport.RoundTrip method, and strips
// X-Forwarded-For headers, since httputil.ReverseProxy.ServeHTTP adds it but
// the GCE metadata server rejects requests with that header.
func (x xForwardedForStripper) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Del("X-Forwarded-For")
return http.DefaultTransport.RoundTrip(req)
}
func (s *Server) getServiceAccountMapping(IP string) (*mappings.ServiceAccountMappingResult, error) {
var serviceAccountMapping *mappings.ServiceAccountMappingResult
var err error
operation := func() error {
serviceAccountMapping, err = s.serviceAccountMapper.GetServiceAccountMapping(IP)
return err
}
expBackoff := backoff.NewExponentialBackOff()
expBackoff.MaxInterval = s.BackoffMaxInterval
expBackoff.MaxElapsedTime = s.BackoffMaxElapsedTime
err = backoff.Retry(operation, expBackoff)
if err != nil {
return nil, err
}
return serviceAccountMapping, nil
}
// HealthResponse represents a response for the health check.
type HealthResponse struct {
HostIP string `json:"hostIP"`
ProjectID string `json:"projectId"`
}
// ErrorResponse represents a response for errors.
type ErrorResponse struct {
Error string `json:"error"`
Description string `json:"error_description"`
}
// ServiceAccount represents a response for a service account.
type ServiceAccount struct {
Aliases []string `json:"aliases"`
Email string `json:"email"`
Scopes []string `json:"scopes"`
}
func (s *Server) healthHandler(logger *log.Entry, w http.ResponseWriter, r *http.Request) {
projectID, err := metadata.ProjectID()
if err != nil {
log.Errorf("Error getting project id %+v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
health := &HealthResponse{ProjectID: projectID, HostIP: s.HostIP}
w.Header().Add("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(health); err != nil {
log.Errorf("Error sending json %+v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func (s *Server) debugStoreHandler(logger *log.Entry, w http.ResponseWriter, r *http.Request) {
log.Info("Dumping debug")
o, err := json.Marshal(s.serviceAccountMapper.DumpDebugInfo())
if err != nil {
log.Errorf("Error converting debug map to json: %+v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
write(logger, w, string(o))
}
func (s *Server) serviceAccountsHandler(logger *log.Entry, w http.ResponseWriter, r *http.Request) {
remoteIP := parseRemoteAddr(r.RemoteAddr)
serviceAccountMapping, err := s.getServiceAccountMapping(remoteIP)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
write(logger, w, fmt.Sprintf("%s/\n%s/", serviceAccountMapping.ServiceAccount, "default"))
}
func (s *Server) redirect(logger *log.Entry, w http.ResponseWriter, r *http.Request) {
correctedPath := fmt.Sprintf("%s/", r.URL.Path)
w.Header().Set("Location", correctedPath)
w.WriteHeader(http.StatusMovedPermanently)
write(logger, w, correctedPath)
}
func (s *Server) serviceAccountTokenHandler(logger *log.Entry, w http.ResponseWriter, r *http.Request) {
serviceAccountMappingResult, err := s.validateServiceAccountRequest(logger, w, r)
if err != nil {
return
}
credentials, err := s.iam.ImpersonateServiceAccount(serviceAccountMappingResult)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(credentials); err != nil {
logger.Errorf("Error sending json %+v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func (s *Server) serviceAccountIdentityHandler(logger *log.Entry, w http.ResponseWriter, r *http.Request) {
serviceAccountMappingResult, err := s.validateServiceAccountRequest(logger, w, r)
if err != nil {
return
}
audience := r.URL.Query().Get("audience")
if audience == "" {
http.Error(w, "audience parameter required", http.StatusBadRequest)
return
}
credentials, err := s.iam.GenerateIDToken(serviceAccountMappingResult, audience)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
write(logger, w, credentials)
}
func (s *Server) serviceAccountScopesHandler(logger *log.Entry, w http.ResponseWriter, r *http.Request) {
if serviceAccountMappingResult, err := s.validateServiceAccountRequest(logger, w, r); err == nil {
for _, scope := range serviceAccountMappingResult.Scopes {
write(logger, w, scope)
}
}
}
func (s *Server) serviceAccountAliasesHandler(logger *log.Entry, w http.ResponseWriter, r *http.Request) {
if _, err := s.validateServiceAccountRequest(logger, w, r); err == nil {
write(logger, w, mux.Vars(r)["serviceAccount"])
}
}
func (s *Server) serviceAccountEmailHandler(logger *log.Entry, w http.ResponseWriter, r *http.Request) {
if serviceAccountMappingResult, err := s.validateServiceAccountRequest(logger, w, r); err == nil {
write(logger, w, serviceAccountMappingResult.ServiceAccount)
}
}
func (s *Server) serviceAccountHandler(logger *log.Entry, w http.ResponseWriter, r *http.Request) {
if serviceAccountMappingResult, err := s.validateServiceAccountRequest(logger, w, r); err == nil {
recursive := r.URL.Query().Get("recursive")
if recursive != "True" {
for _, path := range []string{"aliases", "email", "identity", "scopes", "token"} {
write(logger, w, fmt.Sprintf("%s\n", path))
}
} else {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(&ServiceAccount{
Aliases: []string{mux.Vars(r)["serviceAccount"]},
Email: serviceAccountMappingResult.ServiceAccount,
Scopes: serviceAccountMappingResult.Scopes,
}); err != nil {
logger.Errorf("Error sending json %+v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
}
func (s *Server) validateServiceAccountRequest(logger *log.Entry, w http.ResponseWriter, r *http.Request) (*mappings.ServiceAccountMappingResult, error) {
remoteIP := parseRemoteAddr(r.RemoteAddr)
serviceAccountMapping, err := s.getServiceAccountMapping(remoteIP)
if err != nil {
log.Errorf("Failed to look up service account mapping for %s: %+v", remoteIP, err)
w.WriteHeader(http.StatusForbidden)
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(&ErrorResponse{
Error: "invalid_request",
Description: "Service account not enabled on this instance",
}); err != nil {
logger.Errorf("Error sending json %+v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return nil, err
}
serviceAccountLogger := logger.WithFields(log.Fields{
"pod.iam.serviceAccount": serviceAccountMapping.ServiceAccount,
"ns.name": serviceAccountMapping.Namespace,
})
wantedServiceAccount := mux.Vars(r)["serviceAccount"]
if wantedServiceAccount == "default" {
wantedServiceAccount = serviceAccountMapping.ServiceAccount
}
if wantedServiceAccount != serviceAccountMapping.ServiceAccount {
serviceAccountLogger.WithField("params.iam.serviceAccount", wantedServiceAccount).
Error("Invalid service account: does not match annotated service account")
w.WriteHeader(http.StatusForbidden)
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(&ErrorResponse{
Error: "invalid_request",
Description: "Service account not enabled on this instance",
}); err != nil {
logger.Errorf("Error sending json %+v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return nil, fmt.Errorf("invalid service account (%s): does not match annotated service account (%s)", wantedServiceAccount, serviceAccountMapping.ServiceAccount)
}
return serviceAccountMapping, nil
}
func (s *Server) reverseProxyHandler(logger *log.Entry, w http.ResponseWriter, r *http.Request) {
host := s.MetadataAddress
if s.EnableMetadataProxy {
host = s.MetadataProxyAddress
}
proxy := httputil.NewSingleHostReverseProxy(&url.URL{Scheme: "http", Host: host})
proxy.Transport = xForwardedForStripper{}
proxy.ServeHTTP(w, r)
logger.WithField("metadata.url", host).Debug("Proxy GCE metadata request")
}
func write(logger *log.Entry, w http.ResponseWriter, s string) {
if _, err := w.Write([]byte(fmt.Sprintf("%+v", s))); err != nil {
logger.Errorf("Error writing response: %+v", err)
}
}
// Run runs the specified Server.
func (s *Server) Run(host, token, nodeName string, insecure bool) error {
k, err := k8s.NewClient(host, token, nodeName, insecure)
if err != nil {
return err
}
s.k8s = k
s.iam = iam.NewClient()
s.serviceAccountMapper = mappings.NewServiceAccountMapper(s.IAMServiceAccountKey, s.IAMScopeKey, s.DefaultServiceAccount, s.DefaultScopes, s.NamespaceRestriction, s.NamespaceKey, s.k8s)
podSynched := s.k8s.WatchForPods(saassigner.NewPodHandler(s.IAMServiceAccountKey))
namespaceSynched := s.k8s.WatchForNamespaces(saassigner.NewNamespaceHandler(s.NamespaceKey))
synced := false
for i := 0; i < defaultCacheSyncAttempts && !synced; i++ {
synced = cache.WaitForCacheSync(nil, podSynched, namespaceSynched)
}
if !synced {
log.Fatalf("Attempted to wait for caches to be synced for %d however it is not done. Giving up.", defaultCacheSyncAttempts)
} else {
log.Debugln("Caches have been synced. Proceeding with server.")
}
r := mux.NewRouter()
if s.Debug {
// This is a potential security risk if enabled in some clusters, hence the flag
r.Handle("/debug/store", appHandler(s.debugStoreHandler))
}
r.Handle("/computeMetadata/v1/instance/service-accounts", appHandler(s.redirect))
r.Handle("/computeMetadata/v1/instance/service-accounts/", appHandler(s.serviceAccountsHandler))
r.Handle("/computeMetadata/v1/instance/service-accounts/{serviceAccount}", appHandler(s.redirect))
r.Handle("/computeMetadata/v1/instance/service-accounts/{serviceAccount}/", appHandler(s.serviceAccountHandler))
r.Handle("/computeMetadata/v1/instance/service-accounts/{serviceAccount}/aliases", appHandler(s.serviceAccountAliasesHandler))
r.Handle("/computeMetadata/v1/instance/service-accounts/{serviceAccount}/email", appHandler(s.serviceAccountEmailHandler))
r.Handle("/computeMetadata/v1/instance/service-accounts/{serviceAccount}/identity", appHandler(s.serviceAccountIdentityHandler))
r.Handle("/computeMetadata/v1/instance/service-accounts/{serviceAccount}/scopes", appHandler(s.serviceAccountScopesHandler))
r.Handle("/computeMetadata/v1/instance/service-accounts/{serviceAccount}/token", appHandler(s.serviceAccountTokenHandler))
r.Handle("/healthz", appHandler(s.healthHandler))
r.Handle("/{path:.*}", appHandler(s.reverseProxyHandler))
log.Infof("Listening on port %s", s.AppPort)
if err := http.ListenAndServe(":"+s.AppPort, r); err != nil {
log.Fatalf("Error creating http server: %+v", err)
}
return nil
}
// NewServer will create a new Server with default values.
func NewServer() *Server {
return &Server{
AppPort: defaultAppPort,
BackoffMaxElapsedTime: defaultMaxElapsedTime,
IAMServiceAccountKey: defaultIAMServiceAccountKey,
IAMScopeKey: defaultIAMScopeKey,
BackoffMaxInterval: defaultMaxInterval,
LogLevel: defaultLogLevel,
LogFormat: defaultLogFormat,
MetadataAddress: defaultMetadataAddress,
MetadataProxyAddress: defaultMetadataProxyAddress,
EnableMetadataProxy: defaultEnableMetadataProxy,
NamespaceKey: defaultNamespaceKey,
}
}