This repository has been archived by the owner on Jan 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
router.go
77 lines (64 loc) · 2.15 KB
/
router.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
package k8s
import (
"fmt"
"net/http"
"github.com/Sirupsen/logrus"
"github.com/dgrijalva/jwt-go"
"github.com/gorilla/mux"
)
type BackendAccess interface {
AuthAndLookup(req *http.Request) (*jwt.Token, string, error)
ServeRemoteHTTP(token *jwt.Token, hostKey string, rw http.ResponseWriter, req *http.Request) error
}
type handler struct {
lookup *Lookup
accessKey string
secretKey string
frontendHTTPHandler BackendAccess
netesProxy *netesProxy
}
func Handler(frontendHTTPHandler BackendAccess, cattleAddr, accessKey, secretKey string) (http.Handler, error) {
np, err := newNetesProxy()
if err != nil {
return nil, err
}
return &handler{
lookup: NewLookup(fmt.Sprintf("http://%s/v3/clusters", cattleAddr), accessKey, secretKey),
accessKey: accessKey,
secretKey: secretKey,
frontendHTTPHandler: frontendHTTPHandler,
netesProxy: np,
}, nil
}
func (h *handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
cluster, _, err := h.lookup.Lookup(req)
if err != nil {
logrus.Errorf("Failed to find cluster: %v", err)
http.Error(rw, fmt.Sprintf("Failed to find cluster: %v", err), http.StatusInternalServerError)
return
}
if cluster == nil {
http.Error(rw, "Failed to find cluster", http.StatusNotFound)
return
}
if cluster.Embedded {
h.netesProxy.Handle(rw, req)
return
}
vars := mux.Vars(req)
vars["service"] = fmt.Sprintf("k8s-api.%s", cluster.Id)
//oldAuth := req.Header.Get("Authorization")
req.SetBasicAuth(h.accessKey, h.secretKey)
token, hostKey, err := h.frontendHTTPHandler.AuthAndLookup(req)
if err != nil {
http.Error(rw, fmt.Sprintf("Failed to authorize cluster: %v", err), http.StatusInternalServerError)
return
}
//req.Header.Set("Authorization", oldAuth)
req.Header.Set("Authorization", "Bearer "+cluster.K8sClientConfig.BearerToken)
req.Header.Set("X-API-Cluster-Id", cluster.Id)
if err := h.frontendHTTPHandler.ServeRemoteHTTP(token, hostKey, rw, req); err != nil {
logrus.Errorf("Failed to forward request: %v", err)
http.Error(rw, fmt.Sprintf("Failed to forward request: %v", err), http.StatusInternalServerError)
}
}