-
Notifications
You must be signed in to change notification settings - Fork 135
/
headlamp.go
1475 lines (1201 loc) · 43 KB
/
headlamp.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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"compress/gzip"
"context"
"crypto/tls"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
oidc "github.com/coreos/go-oidc"
"github.com/gobwas/glob"
"github.com/google/uuid"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/headlamp-k8s/headlamp/backend/pkg/cache"
"github.com/headlamp-k8s/headlamp/backend/pkg/helm"
"github.com/headlamp-k8s/headlamp/backend/pkg/kubeconfig"
"github.com/headlamp-k8s/headlamp/backend/pkg/logger"
"github.com/headlamp-k8s/headlamp/backend/pkg/plugins"
"github.com/headlamp-k8s/headlamp/backend/pkg/portforward"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/clientcmd/api"
"golang.org/x/oauth2"
)
type HeadlampConfig struct {
useInCluster bool
devMode bool
insecure bool
enableHelm bool
enableDynamicClusters bool
port uint
kubeConfigPath string
staticDir string
pluginDir string
staticPluginDir string
oidcClientID string
oidcClientSecret string
oidcIdpIssuerURL string
baseURL string
oidcScopes []string
proxyURLs []string
cache cache.Cache[interface{}]
kubeConfigStore kubeconfig.ContextStore
}
const DrainNodeCacheTTL = 20 // seconds
const isWindows = runtime.GOOS == "windows"
const ContextCacheTTL = 5 * time.Minute // minutes
const ContextUpdateChacheTTL = 20 * time.Second // seconds
type clientConfig struct {
Clusters []Cluster `json:"clusters"`
IsDyanmicClusterEnabled bool `json:"isDynamicClusterEnabled"`
}
type spaHandler struct {
staticPath string
indexPath string
baseURL string
}
type OauthConfig struct {
Config *oauth2.Config
Verifier *oidc.IDTokenVerifier
Ctx context.Context
}
func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Clean the path to prevent directory traversal
path := filepath.Clean(r.URL.Path)
path = strings.TrimPrefix(path, h.baseURL)
// prepend the path with the path to the static directory
path = filepath.Join(h.staticPath, path)
// check whether a file exists at the given path
_, err := os.Stat(path)
if os.IsNotExist(err) {
// file does not exist, serve index.html
http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))
return
} else if err != nil {
// if we got an error (that wasn't that the file doesn't exist) stating the
// file, return a 500 internal server error and stop
logger.Log(logger.LevelError, nil, err, "stating file")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// The file does exist, so we serve that.
http.ServeFile(w, r, path)
}
// returns True if a file exists.
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
// copy a file, whilst doing some search/replace on the data.
func copyReplace(src string, dst string,
search []byte, replace []byte,
search2 []byte, replace2 []byte,
) {
data, err := os.ReadFile(src)
if err != nil {
// Error Reading the file
logger.Log(logger.LevelError, nil, err, "reading file")
os.Exit(1)
}
data1 := bytes.ReplaceAll(data, search, replace)
data2 := bytes.ReplaceAll(data1, search2, replace2)
fileMode := 0o600
err = os.WriteFile(dst, data2, fs.FileMode(fileMode))
if err != nil {
// Error writing the file
logger.Log(logger.LevelError, nil, err, "writing file")
os.Exit(1)
}
}
// make sure the base-url is updated in the index.html file.
func baseURLReplace(staticDir string, baseURL string) {
indexBaseURL := path.Join(staticDir, "index.baseUrl.html")
index := path.Join(staticDir, "index.html")
replaceURL := baseURL
if baseURL == "" {
// We have to do the replace when baseURL == "" because of the case when
// someone first does a different baseURL. If we didn't it would stay stuck
// on that previous baseURL.
replaceURL = "/"
}
if !fileExists(indexBaseURL) {
copyReplace(index, indexBaseURL, []byte(""), []byte(""), []byte(""), []byte(""))
}
copyReplace(indexBaseURL,
index,
[]byte("./"),
[]byte(baseURL+"/"),
[]byte("headlampBaseUrl=\".\""),
[]byte("headlampBaseUrl=\""+replaceURL+"\""))
}
func getOidcCallbackURL(r *http.Request, config *HeadlampConfig) string {
urlScheme := r.URL.Scheme
if urlScheme == "" {
// check proxy headers first
fwdProto := r.Header.Get("X-Forwarded-Proto")
switch {
case fwdProto != "":
urlScheme = fwdProto
case strings.HasPrefix(r.Host, "localhost:") || r.TLS == nil:
urlScheme = "http"
default:
urlScheme = "https"
}
}
// Clean up + add the base URL to the redirect URL
hostWithBaseURL := strings.Trim(r.Host, "/")
baseURL := strings.Trim(config.baseURL, "/")
if baseURL != "" {
hostWithBaseURL = hostWithBaseURL + "/" + baseURL
}
return fmt.Sprintf("%s://%s/oidc-callback", urlScheme, hostWithBaseURL)
}
func serveWithNoCacheHeader(fs http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Cache-Control", "no-cache")
fs.ServeHTTP(w, r)
}
}
// defaultKubeConfigPersistenceDir returns the default directory to store kubeconfig
// files of clusters that are loaded in Headlamp.
func defaultKubeConfigPersistenceDir() (string, error) {
userConfigDir, err := os.UserConfigDir()
if err == nil {
kubeConfigDir := filepath.Join(userConfigDir, "Headlamp", "kubeconfigs")
if isWindows {
// golang is wrong for config folder on windows.
// This matches env-paths and headlamp-plugin.
kubeConfigDir = filepath.Join(userConfigDir, "Headlamp", "Config", "kubeconfigs")
}
// Create the directory if it doesn't exist.
fileMode := 0o755
err = os.MkdirAll(kubeConfigDir, fs.FileMode(fileMode))
if err == nil {
return kubeConfigDir, nil
}
}
// if any error occurred, fallback to the current directory.
ex, err := os.Executable()
if err == nil {
return filepath.Dir(ex), nil
}
return "", fmt.Errorf("failed to get default kubeconfig persistence directory: %v", err)
}
func defaultKubeConfigPersistenceFile() (string, error) {
kubeConfigDir, err := defaultKubeConfigPersistenceDir()
if err != nil {
return "", err
}
return filepath.Join(kubeConfigDir, "config"), nil
}
// addPluginRoutes adds plugin routes to a router.
// It serves plugin list base paths as json at “/plugins”.
// It serves plugin static files at “/plugins/” and “/static-plugins/”.
// It disables caching and reloads plugin list base paths if not in-cluster.
func addPluginRoutes(config *HeadlampConfig, r *mux.Router) {
// Delete plugin route
// This is only available when running locally.
if !config.useInCluster {
r.HandleFunc("/plugins/{name}", func(w http.ResponseWriter, r *http.Request) {
if err := checkHeadlampBackendToken(w, r); err != nil {
return
}
pluginName := mux.Vars(r)["name"]
err := plugins.Delete(config.pluginDir, pluginName)
if err != nil {
http.Error(w, "Error deleting plugin", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}).Methods("DELETE")
}
r.HandleFunc("/plugins", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
pluginsList, err := config.cache.Get(context.Background(), plugins.PluginListKey)
if err != nil && err == cache.ErrNotFound {
pluginsList = []string{}
}
if err := json.NewEncoder(w).Encode(pluginsList); err != nil {
logger.Log(logger.LevelError, nil, err, "encoding plugins base paths list")
}
}).Methods("GET")
// Serve plugins
pluginHandler := http.StripPrefix(config.baseURL+"/plugins/", http.FileServer(http.Dir(config.pluginDir)))
// If we're running locally, then do not cache the plugins. This ensures that reloading them (development,
// update) will actually get the new content.
if !config.useInCluster {
pluginHandler = serveWithNoCacheHeader(pluginHandler)
}
r.PathPrefix("/plugins/").Handler(pluginHandler)
if config.staticPluginDir != "" {
staticPluginsHandler := http.StripPrefix(config.baseURL+"/static-plugins/",
http.FileServer(http.Dir(config.staticPluginDir)))
r.PathPrefix("/static-plugins/").Handler(staticPluginsHandler)
}
}
//nolint:gocognit,funlen,gocyclo
func createHeadlampHandler(config *HeadlampConfig) http.Handler {
kubeConfigPath := config.kubeConfigPath
config.staticPluginDir = os.Getenv("HEADLAMP_STATIC_PLUGINS_DIR")
logger.Log(logger.LevelInfo, nil, nil, "Creating Headlamp handler")
logger.Log(logger.LevelInfo, nil, nil, "Kubeconfig path: "+kubeConfigPath)
logger.Log(logger.LevelInfo, nil, nil, "Static plugin dir: "+config.staticPluginDir)
logger.Log(logger.LevelInfo, nil, nil, "Plugins dir: "+config.pluginDir)
logger.Log(logger.LevelInfo, nil, nil, "Dynamic clusters support: "+fmt.Sprint(config.enableDynamicClusters))
logger.Log(logger.LevelInfo, nil, nil, "Helm support: "+fmt.Sprint(config.enableHelm))
logger.Log(logger.LevelInfo, nil, nil, "Proxy URLs: "+fmt.Sprint(config.proxyURLs))
plugins.PopulatePluginsCache(config.staticPluginDir, config.pluginDir, config.cache)
if !config.useInCluster {
// in-cluster mode is unlikely to want reloading plugins.
pluginEventChan := make(chan string)
go plugins.Watch(config.pluginDir, pluginEventChan)
go plugins.HandlePluginEvents(config.staticPluginDir, config.pluginDir, pluginEventChan, config.cache)
// in-cluster mode is unlikely to want reloading kubeconfig.
go kubeconfig.LoadAndWatchFiles(config.kubeConfigStore, kubeConfigPath, kubeconfig.KubeConfig)
}
// In-cluster
if config.useInCluster {
context, err := kubeconfig.GetInClusterContext(config.oidcIdpIssuerURL,
config.oidcClientID, config.oidcClientSecret,
strings.Join(config.oidcScopes, ","))
if err != nil {
logger.Log(logger.LevelError, nil, err, "Failed to get in-cluster context")
}
context.Source = kubeconfig.InCluster
err = context.SetupProxy()
if err != nil {
logger.Log(logger.LevelError, nil, err, "Failed to setup proxy for in-cluster context")
}
err = config.kubeConfigStore.AddContext(context)
if err != nil {
logger.Log(logger.LevelError, nil, err, "Failed to add in-cluster context")
}
}
if config.staticDir != "" {
baseURLReplace(config.staticDir, config.baseURL)
}
// For when using a base-url, like "/headlamp" with a reverse proxy.
var r *mux.Router
if config.baseURL == "" {
r = mux.NewRouter()
} else {
baseRoute := mux.NewRouter()
r = baseRoute.PathPrefix(config.baseURL).Subrouter()
}
fmt.Println("*** Headlamp Server ***")
fmt.Println(" API Routers:")
// load kubeConfig clusters
err := kubeconfig.LoadAndStoreKubeConfigs(config.kubeConfigStore, kubeConfigPath, kubeconfig.KubeConfig)
if err != nil {
logger.Log(logger.LevelError, nil, err, "loading kubeconfig")
}
// load dynamic clusters
kubeConfigPersistenceFile, err := defaultKubeConfigPersistenceFile()
if err != nil {
logger.Log(logger.LevelError, nil, err, "getting default kubeconfig persistence file")
}
err = kubeconfig.LoadAndStoreKubeConfigs(config.kubeConfigStore, kubeConfigPersistenceFile, kubeconfig.DynamicCluster)
if err != nil {
logger.Log(logger.LevelError, nil, err, "loading dynamic kubeconfig")
}
addPluginRoutes(config, r)
config.handleClusterRequests(r)
r.HandleFunc("/externalproxy", func(w http.ResponseWriter, r *http.Request) {
proxyURL := r.Header.Get("proxy-to")
if proxyURL == "" && r.Header.Get("Forward-to") != "" {
proxyURL = r.Header.Get("Forward-to")
}
if proxyURL == "" {
logger.Log(logger.LevelError, map[string]string{"proxyURL": proxyURL},
errors.New("proxy URL is empty"), "proxy URL is empty")
http.Error(w, "proxy URL is empty", http.StatusBadRequest)
return
}
url, err := url.Parse(proxyURL)
if err != nil {
logger.Log(logger.LevelError, map[string]string{"proxyURL": proxyURL},
err, "The provided proxy URL is invalid")
http.Error(w, fmt.Sprintf("The provided proxy URL is invalid: %v", err), http.StatusBadRequest)
return
}
isURLContainedInProxyURLs := false
for _, proxyURL := range config.proxyURLs {
g := glob.MustCompile(proxyURL)
if g.Match(url.String()) {
isURLContainedInProxyURLs = true
break
}
}
if !isURLContainedInProxyURLs {
logger.Log(logger.LevelError, nil, err, "no allowed proxy url match, request denied")
http.Error(w, "no allowed proxy url match, request denied ", http.StatusBadRequest)
return
}
ctx := context.Background()
proxyReq, err := http.NewRequestWithContext(ctx, r.Method, proxyURL, r.Body)
if err != nil {
logger.Log(logger.LevelError, nil, err, "creating request")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// We may want to filter some headers, otherwise we could just use a shallow copy
proxyReq.Header = make(http.Header)
for h, val := range r.Header {
proxyReq.Header[h] = val
}
// Disable caching
w.Header().Set("Cache-Control", "no-cache, private, max-age=0")
w.Header().Set("Expires", time.Unix(0, 0).Format(http.TimeFormat))
w.Header().Set("Pragma", "no-cache")
w.Header().Set("X-Accel-Expires", "0")
client := http.Client{}
resp, err := client.Do(proxyReq)
if err != nil {
logger.Log(logger.LevelError, nil, err, "making request")
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
defer resp.Body.Close()
// Check that the server actually sent compressed data
var reader io.ReadCloser
switch resp.Header.Get("Content-Encoding") {
case "gzip":
reader, err = gzip.NewReader(resp.Body)
if err != nil {
logger.Log(logger.LevelError, nil, err, "reading gzip response")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer reader.Close()
default:
reader = resp.Body
}
respBody, err := io.ReadAll(reader)
if err != nil {
logger.Log(logger.LevelError, nil, err, "reading response")
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
_, err = w.Write(respBody)
if err != nil {
logger.Log(logger.LevelError, nil, err, "writing response")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
})
// Configuration
r.HandleFunc("/config", config.getConfig).Methods("GET")
config.addClusterSetupRoute(r)
oauthRequestMap := make(map[string]*OauthConfig)
r.HandleFunc("/oidc", func(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
cluster := r.URL.Query().Get("cluster")
if config.insecure {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //nolint:gosec
}
insecureClient := &http.Client{Transport: tr}
ctx = oidc.ClientContext(ctx, insecureClient)
}
kContext, err := config.kubeConfigStore.GetContext(cluster)
if err != nil {
logger.Log(logger.LevelError, map[string]string{"cluster": cluster},
err, "failed to get context")
http.NotFound(w, r)
return
}
oidcAuthConfig, err := kContext.OidcConfig()
if err != nil {
logger.Log(logger.LevelError, map[string]string{"cluster": cluster},
err, "failed to get oidc config")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
provider, err := oidc.NewProvider(ctx, oidcAuthConfig.IdpIssuerURL)
if err != nil {
logger.Log(logger.LevelError, map[string]string{"idpIssuerURL": oidcAuthConfig.IdpIssuerURL},
err, "failed to get provider")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
oidcConfig := &oidc.Config{
ClientID: oidcAuthConfig.ClientID,
}
verifier := provider.Verifier(oidcConfig)
oauthConfig := &oauth2.Config{
ClientID: oidcAuthConfig.ClientID,
ClientSecret: oidcAuthConfig.ClientSecret,
Endpoint: provider.Endpoint(),
RedirectURL: getOidcCallbackURL(r, config),
Scopes: append([]string{oidc.ScopeOpenID}, oidcAuthConfig.Scopes...),
}
/* we encode the cluster to base64 and set it as state so that when getting redirected
by oidc we can use this state value to get cluster name
*/
state := base64.StdEncoding.EncodeToString([]byte(cluster))
oauthRequestMap[state] = &OauthConfig{Config: oauthConfig, Verifier: verifier, Ctx: ctx}
http.Redirect(w, r, oauthConfig.AuthCodeURL(state), http.StatusFound)
}).Queries("cluster", "{cluster}")
r.HandleFunc("/portforward", func(w http.ResponseWriter, r *http.Request) {
portforward.StartPortForward(config.kubeConfigStore, config.cache, w, r)
}).Methods("POST")
r.HandleFunc("/portforward", func(w http.ResponseWriter, r *http.Request) {
portforward.StopOrDeletePortForward(config.cache, w, r)
}).Methods("DELETE")
r.HandleFunc("/portforward/list", func(w http.ResponseWriter, r *http.Request) {
portforward.GetPortForwards(config.cache, w, r)
})
r.HandleFunc("/drain-node", config.handleNodeDrain).Methods("POST")
r.HandleFunc("/drain-node-status",
config.handleNodeDrainStatus).Methods("GET").Queries("cluster", "{cluster}", "nodeName", "{node}")
r.HandleFunc("/portforward", func(w http.ResponseWriter, r *http.Request) {
portforward.GetPortForwardByID(config.cache, w, r)
}).Methods("GET")
r.HandleFunc("/oidc-callback", func(w http.ResponseWriter, r *http.Request) {
state := r.URL.Query().Get("state")
decodedState, err := base64.StdEncoding.DecodeString(state)
if err != nil {
logger.Log(logger.LevelError, nil, err, "failed to decode state")
http.Error(w, "wrong state set, invalid request "+err.Error(), http.StatusBadRequest)
return
}
if state == "" {
logger.Log(logger.LevelError, nil, err, "invalid request state is empty")
http.Error(w, "invalid request state is empty", http.StatusBadRequest)
return
}
//nolint:nestif
if oauthConfig, ok := oauthRequestMap[state]; ok {
oauth2Token, err := oauthConfig.Config.Exchange(oauthConfig.Ctx, r.URL.Query().Get("code"))
if err != nil {
logger.Log(logger.LevelError, nil, err, "failed to exchange token")
http.Error(w, "Failed to exchange token: "+err.Error(), http.StatusInternalServerError)
return
}
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
if !ok {
logger.Log(logger.LevelError, nil, err, "no id_token field in oauth2 token")
http.Error(w, "No id_token field in oauth2 token.", http.StatusInternalServerError)
return
}
if err := config.cache.Set(context.Background(),
fmt.Sprintf("oidc-token-%s", rawIDToken), oauth2Token.RefreshToken); err != nil {
logger.Log(logger.LevelError, nil, err, "failed to cache refresh token")
http.Error(w, "Failed to cache refresh token: "+err.Error(), http.StatusInternalServerError)
return
}
idToken, err := oauthConfig.Verifier.Verify(oauthConfig.Ctx, rawIDToken)
if err != nil {
logger.Log(logger.LevelError, nil, err, "failed to verify ID Token")
http.Error(w, "Failed to verify ID Token: "+err.Error(), http.StatusInternalServerError)
return
}
resp := struct {
OAuth2Token *oauth2.Token
IDTokenClaims *json.RawMessage // ID Token payload is just JSON.
}{oauth2Token, new(json.RawMessage)}
if err := idToken.Claims(&resp.IDTokenClaims); err != nil {
logger.Log(logger.LevelError, nil, err, "failed to get id token claims")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var redirectURL string
if config.devMode {
redirectURL = "http://localhost:3000/"
} else {
redirectURL = "/"
}
baseURL := strings.Trim(config.baseURL, "/")
if baseURL != "" {
redirectURL += baseURL + "/"
}
redirectURL += fmt.Sprintf("auth?cluster=%1s&token=%2s", decodedState, rawIDToken)
http.Redirect(w, r, redirectURL, http.StatusSeeOther)
} else {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
})
// Serve the frontend if needed
if config.staticDir != "" {
staticPath := config.staticDir
if isWindows {
// We support unix paths on windows. So "frontend/static" works.
if strings.Contains(config.staticDir, "/") {
staticPath = filepath.FromSlash(config.staticDir)
}
}
spa := spaHandler{staticPath: staticPath, indexPath: "index.html", baseURL: config.baseURL}
r.PathPrefix("/").Handler(spa)
http.Handle("/", r)
}
// On dev mode we're loose about where connections come from
if config.devMode {
headers := handlers.AllowedHeaders([]string{
"X-HEADLAMP_BACKEND-TOKEN", "X-Requested-With", "Content-Type",
"Authorization", "Forward-To",
"KUBECONFIG", "X-HEADLAMP-USER-ID",
})
methods := handlers.AllowedMethods([]string{"GET", "POST", "PUT", "HEAD", "DELETE", "PATCH", "OPTIONS"})
origins := handlers.AllowedOrigins([]string{"*"})
return handlers.CORS(headers, methods, origins)(r)
}
return r
}
func parseClusterAndToken(r *http.Request) (string, string) {
cluster := ""
re := regexp.MustCompile(`^/clusters/([^/]+)/.*`)
urlString := r.URL.RequestURI()
matches := re.FindStringSubmatch(urlString)
if len(matches) > 1 {
cluster = matches[1]
}
// get token
token := r.Header.Get("Authorization")
token = strings.TrimPrefix(token, "Bearer ")
return cluster, token
}
func isTokenAboutToExpire(token string) bool {
const TokenParts = 3
// parse expiry time from token
parts := strings.Split(token, ".")
if len(parts) != TokenParts {
return false
}
payloadPart := parts[1]
payloadBytes, err := base64.RawStdEncoding.DecodeString(payloadPart)
if err != nil {
logger.Log(logger.LevelError, nil, err, "failed to decode payload")
return false
}
var payload map[string]interface{}
if err := json.Unmarshal(payloadBytes, &payload); err != nil {
logger.Log(logger.LevelError, nil, err, "failed to unmarshal payload")
return false
}
// check if token is expired
exp, ok := payload["exp"].(float64)
if !ok {
return false
}
// if token is not about to expire, then skip
expTime := time.Unix(int64(exp), 0)
return time.Until(expTime) <= time.Second*10
}
//nolint:funlen
func refreshAndCacheNewToken(oidcAuthConfig *kubeconfig.OidcConfig,
cache cache.Cache[interface{}], token string,
) (string, error) {
const ExtendRefreshTokenTTL = 10 // seconds
// get provider
provider, err := oidc.NewProvider(context.Background(), oidcAuthConfig.IdpIssuerURL)
if err != nil {
logger.Log(logger.LevelError, nil, err, "failed to get provider")
return "", err
}
// get refresh token from cache
refreshToken, err := cache.Get(context.Background(), fmt.Sprintf("oidc-token-%s", token))
if err != nil || refreshToken == "" {
logger.Log(logger.LevelError, nil, err, "failed to get refresh token")
return "", err
}
rToken, ok := refreshToken.(string)
if !ok {
logger.Log(logger.LevelError, nil, err, "failed to cast refresh token")
return "", err
}
oauth2Config := oauth2.Config{
ClientID: oidcAuthConfig.ClientID,
ClientSecret: oidcAuthConfig.ClientSecret,
Endpoint: provider.Endpoint(),
Scopes: oidcAuthConfig.Scopes,
}
// get new token using refresh token
ts := oauth2Config.TokenSource(context.Background(), &oauth2.Token{
RefreshToken: rToken,
})
tk, err := ts.Token()
if err != nil {
logger.Log(logger.LevelError, nil, err, "failed to get new token")
return "", err
}
idToken, ok := tk.Extra("id_token").(string)
if ok {
// update cache
if err := cache.Set(context.Background(), fmt.Sprintf("oidc-token-%s", idToken), tk.RefreshToken); err != nil {
logger.Log(logger.LevelError, nil, err, "failed to cache refresh token")
return "", err
}
// set ttl to 10 seconds for old token to handle case when the new token is not accepted by the client.
if err := cache.SetWithTTL(context.Background(), fmt.Sprintf("oidc-token-%s", token),
refreshToken, time.Second*ExtendRefreshTokenTTL); err != nil {
logger.Log(logger.LevelError, nil, err, "failed to extend refresh token ttl")
return "", err
}
return idToken, nil
}
return "", errors.New("failed to get id token")
}
func (c *HeadlampConfig) OIDCTokenRefreshMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// skip if not cluster request
if !strings.HasPrefix(r.URL.String(), "/clusters/") {
next.ServeHTTP(w, r)
return
}
// parse cluster and token
cluster, token := parseClusterAndToken(r)
if cluster == "" || token == "" {
next.ServeHTTP(w, r)
return
}
// get oidc config
kContext, err := c.kubeConfigStore.GetContext(cluster)
if err != nil {
logger.Log(logger.LevelError, map[string]string{"cluster": cluster},
err, "failed to get context")
next.ServeHTTP(w, r)
return
}
// skip if cluster is not using OIDC auth
oidcAuthConfig, err := kContext.OidcConfig()
if err != nil {
logger.Log(logger.LevelError, map[string]string{"cluster": cluster},
err, "failed to get oidc config")
next.ServeHTTP(w, r)
return
}
// skip if token is not about to expire
if !isTokenAboutToExpire(token) {
next.ServeHTTP(w, r)
return
}
// refresh and cache new token
newToken, err := refreshAndCacheNewToken(oidcAuthConfig, c.cache, token)
if err != nil {
logger.Log(logger.LevelError, map[string]string{"cluster": cluster},
err, "failed to refresh token")
}
if newToken != "" {
w.Header().Set("X-Authorization", newToken)
}
next.ServeHTTP(w, r)
})
}
func StartHeadlampServer(config *HeadlampConfig) {
handler := createHeadlampHandler(config)
handler = config.OIDCTokenRefreshMiddleware(handler)
// Start server
err := http.ListenAndServe(fmt.Sprintf(":%d", config.port), handler) //nolint:gosec
if err != nil {
logger.Log(logger.LevelError, nil, nil, "Failed to start server")
os.Exit(1)
}
}
// Returns the helm.Handler given the config and request. Writes http.NotFound if clusterName is not there.
func getHelmHandler(c *HeadlampConfig, w http.ResponseWriter, r *http.Request) (*helm.Handler, error) {
clusterName := mux.Vars(r)["clusterName"]
context, err := c.kubeConfigStore.GetContext(clusterName)
if err != nil {
logger.Log(logger.LevelError, map[string]string{"clusterName": clusterName},
err, "failed to get context")
http.NotFound(w, r)
return nil, errors.New("not found")
}
namespace := r.URL.Query().Get("namespace")
helmHandler, err := helm.NewHandler(context.ClientConfig(), c.cache, namespace)
if err != nil {
logger.Log(logger.LevelError, nil, err, "failed to create helm handler")
http.Error(w, "failed to create helm handler", http.StatusInternalServerError)
return nil, err
}
return helmHandler, nil
}
// Check request for header "X-HEADLAMP_BACKEND-TOKEN" matches HEADLAMP_BACKEND_TOKEN env
// This check is to prevent access except for from the app.
// The app sets HEADLAMP_BACKEND_TOKEN, and gives the token to the frontend.
func checkHeadlampBackendToken(w http.ResponseWriter, r *http.Request) error {
backendToken := r.Header.Get("X-HEADLAMP_BACKEND-TOKEN")
backendTokenEnv := os.Getenv("HEADLAMP_BACKEND_TOKEN")
if backendToken != backendTokenEnv || backendTokenEnv == "" {
http.Error(w, "access denied", http.StatusForbidden)
return errors.New("X-HEADLAMP_BACKEND-TOKEN does not match HEADLAMP_BACKEND_TOKEN")
}
return nil
}
//nolint:gocognit,funlen
func handleClusterHelm(c *HeadlampConfig, router *mux.Router) {
router.PathPrefix("/clusters/{clusterName}/helm/{.*}").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := checkHeadlampBackendToken(w, r); err != nil {
logger.Log(logger.LevelError, nil, err, "failed to check headlamp backend token")
return
}
helmHandler, err := getHelmHandler(c, w, r)
if err != nil {
logger.Log(logger.LevelError, nil, err, "failed to get helm handler")
return
}
// we used nolint:gocognit in this function because...
// Perhaps there's a better way to dispatch these?
path := r.URL.Path
if strings.HasSuffix(path, "/releases/list") && r.Method == http.MethodGet {
helmHandler.ListRelease(w, r)
return
}
if strings.HasSuffix(path, "/release/install") && r.Method == http.MethodPost {
helmHandler.InstallRelease(w, r)
return
}
if strings.HasSuffix(path, "/release/history") && r.Method == http.MethodGet {
helmHandler.GetReleaseHistory(w, r)
return
}
if strings.HasSuffix(path, "/releases/uninstall") && r.Method == http.MethodDelete {
helmHandler.UninstallRelease(w, r)
return
}
if strings.HasSuffix(path, "/releases/rollback") && r.Method == http.MethodPut {
helmHandler.RollbackRelease(w, r)
return
}
if strings.HasSuffix(path, "/releases/upgrade") && r.Method == http.MethodPut {
helmHandler.UpgradeRelease(w, r)
return
}
if strings.HasSuffix(path, "/releases") && r.Method == http.MethodGet {
helmHandler.GetRelease(w, r)
return
}
if strings.HasSuffix(path, "/repositories") && r.Method == http.MethodGet {
helmHandler.ListRepo(w, r)
return
}
if strings.HasSuffix(path, "/repositories") && r.Method == http.MethodPost {
helmHandler.AddRepo(w, r)
return
}
if strings.HasSuffix(path, "/repositories/remove") && r.Method == http.MethodDelete {
helmHandler.RemoveRepo(w, r)
return
}
if strings.HasSuffix(path, "/repositories/update") && r.Method == http.MethodPut {
helmHandler.UpdateRepository(w, r)
return
}
if strings.HasSuffix(path, "/charts") && r.Method == http.MethodGet {
helmHandler.ListCharts(w, r)
return
}
if strings.HasSuffix(path, "/action/status") && r.Method == http.MethodGet {
helmHandler.GetActionStatus(w, r)
return
}
})
}
// handleClusterAPI handles cluster API requests. It is responsible for
// all the requests made to /clusters/{clusterName}/{api:.*} endpoint.
// It parses the request and creates a proxy request to the cluster.
// That proxy is saved in the cache with the context key.
func handleClusterAPI(c *HeadlampConfig, router *mux.Router) {
router.PathPrefix("/clusters/{clusterName}/{api:.*}").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
contextKey, err := c.getContextKeyForRequest(r)
if err != nil {
logger.Log(logger.LevelError, map[string]string{"key": contextKey},
err, "failed to get context key")
http.NotFound(w, r)
return
}
kContext, err := c.kubeConfigStore.GetContext(contextKey)
if err != nil {
logger.Log(logger.LevelError, map[string]string{"key": contextKey},
err, "failed to get context")
http.NotFound(w, r)
return
}
clusterURL, err := url.Parse(kContext.Cluster.Server)