forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 1
/
k8s_proxy.go
85 lines (70 loc) · 2.07 KB
/
k8s_proxy.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
package k8sproxy
import (
"net/http"
"github.com/rancher/rancher/pkg/clusterrouter"
"github.com/rancher/rancher/pkg/clusterrouter/proxy"
rdialer "github.com/rancher/rancher/pkg/dialer"
"github.com/rancher/rancher/pkg/k8slookup"
"github.com/rancher/rancher/pkg/tunnelserver"
"github.com/rancher/types/config"
"github.com/rancher/types/config/dialer"
)
func New(scaledContext *config.ScaledContext, dialer dialer.Factory) http.Handler {
return clusterrouter.New(scaledContext.LocalConfig, k8slookup.New(scaledContext, true), dialer)
}
func NewLocalProxy(scaledContext *config.ScaledContext, dialer dialer.Factory, next http.Handler) (http.Handler, error) {
passThrough, err := proxy.NewSimpleProxy(scaledContext.LocalConfig.Host, scaledContext.LocalConfig.CAData)
if err != nil {
return nil, err
}
lp := &localProxy{
passThrough: passThrough,
next: next,
router: clusterrouter.New(scaledContext.LocalConfig, k8slookup.New(scaledContext, false), dialer),
}
if rd, ok := dialer.(*rdialer.Factory); ok {
lp.auth = rd.TunnelAuthorizer
}
return lp, nil
}
type localProxy struct {
passThrough http.Handler
next http.Handler
auth *tunnelserver.Authorizer
router http.Handler
}
func (l *localProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if l.pass(rw, req) {
return
}
if !l.proxy(rw, req) {
l.next.ServeHTTP(rw, req)
}
}
func (l *localProxy) pass(rw http.ResponseWriter, req *http.Request) bool {
if req.Header.Get("X-API-K8s-Node-Client") == "true" {
l.passThrough.ServeHTTP(rw, req)
return true
}
return false
}
func (l *localProxy) proxy(rw http.ResponseWriter, req *http.Request) bool {
if l.auth == nil {
return false
}
username, password, ok := req.BasicAuth()
if !ok {
return false
}
user, groups, cluster, ok := l.auth.AuthorizeLocalNode(username, password)
if !ok {
return false
}
req.Header.Set("X-API-Cluster-Id", cluster.Name)
req.Header.Set("Impersonate-User", user)
for _, group := range groups {
req.Header.Set("Impersonate-Group", group)
}
l.router.ServeHTTP(rw, req)
return true
}