-
Notifications
You must be signed in to change notification settings - Fork 328
/
handler.go
154 lines (136 loc) · 4.39 KB
/
handler.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
/*
* Tencent is pleased to support the open source community by making TKEStack
* available.
*
* Copyright (C) 2012-2022 Tencent. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at
*
* https://opensource.org/licenses/Apache-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package websocket
import (
"encoding/base64"
"fmt"
"net"
"net/http"
"net/url"
"time"
utilnet "k8s.io/apimachinery/pkg/util/net"
"k8s.io/apimachinery/pkg/util/proxy"
"k8s.io/client-go/rest"
"k8s.io/client-go/transport"
"k8s.io/klog"
"tkestack.io/tke/pkg/gateway/token"
"tkestack.io/tke/pkg/platform/apiserver/filter"
"tkestack.io/tke/pkg/util/log"
)
type handler struct {
config rest.Config
}
// NewHandler to create a reverse proxy handler and returns it.
// The reverse proxy will parse the requested cookie content, get the token in
// it, and append it as the http request header to the backend service component.
func NewHandler(address string) (http.Handler, error) {
u, err := url.Parse(address)
if err != nil {
log.Error("Failed to parse backend service address", log.String("address", address), log.Err(err))
return nil, err
}
cfg := rest.Config{
Host: u.Host,
TLSClientConfig: rest.TLSClientConfig{
Insecure: true,
},
}
return &handler{
config: cfg,
}, nil
}
func (h *handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
fmt.Println("in websocket")
clusterName := req.URL.Query().Get("clusterName")
if clusterName == "" {
log.Error("Failed to get cluster name from request")
http.Error(w, "Invalid cluster name", http.StatusBadRequest)
return
}
encodePath := req.URL.Query().Get("encodePath")
decodePathBytes, err := base64.StdEncoding.DecodeString(encodePath)
if err != nil {
log.Error("Failed to get/decode encode path from request")
http.Error(w, fmt.Sprintf("Invalid decode path: %v", err), http.StatusBadRequest)
return
}
decodePath := string(decodePathBytes)
t, err := token.RetrieveToken(req)
if err != nil {
log.Error("Failed to retrieve token from webtty", log.Err(err))
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
cfg := h.config
cfg.BearerToken = t.ID
target, err := url.Parse(decodePath)
if err != nil {
log.Error("Failed to generate decode path url", log.Err(err))
http.Error(w, "Internal Error", http.StatusInternalServerError)
return
}
target.Scheme = "https"
target.Host = cfg.Host
transport, err := rest.TransportFor(&cfg)
if err != nil {
log.Error("Failed initialize transport", log.Err(err))
http.Error(w, "Internal Error", http.StatusInternalServerError)
return
}
upgradeTransport, err := makeUpgradeTransport(&cfg, 30*time.Second)
if err != nil {
log.Error("Failed initialize upgrade transport", log.Err(err))
http.Error(w, "Internal Error", http.StatusInternalServerError)
return
}
responder := &responder{}
proxy := proxy.NewUpgradeAwareHandler(target, transport, false, false, responder)
proxy.UpgradeTransport = upgradeTransport
proxy.Location = target
reqClone := utilnet.CloneRequest(req)
reqClone.URL = target
reqClone.Header.Add(filter.ClusterNameHeaderKey, clusterName)
proxy.ServeHTTP(w, reqClone)
}
type responder struct{}
func (r *responder) Error(w http.ResponseWriter, req *http.Request, err error) {
klog.Errorf("Error while proxying request: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
func makeUpgradeTransport(config *rest.Config, keepalive time.Duration) (proxy.UpgradeRequestRoundTripper, error) {
transportConfig, err := config.TransportConfig()
if err != nil {
return nil, err
}
tlsConfig, err := transport.TLSConfigFor(transportConfig)
if err != nil {
return nil, err
}
rt := utilnet.SetOldTransportDefaults(&http.Transport{
TLSClientConfig: tlsConfig,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: keepalive,
}).DialContext,
})
upgrader, err := transport.HTTPWrappersForConfig(transportConfig, proxy.MirrorRequest)
if err != nil {
return nil, err
}
return proxy.NewUpgradeRequestRoundTripper(rt, upgrader), nil
}