/
proxy.go
288 lines (250 loc) · 8.81 KB
/
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
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
package terminal
import (
"bytes"
"context"
"crypto/tls"
"errors"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/coreos/pkg/capnslog"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"github.com/devops-simba/console/pkg/auth"
)
const (
// ProxyEndpoint path that that Proxy is supposed to handle
ProxyEndpoint = "/api/terminal/proxy/"
// AvailableEndpoint path used to check if functionality is enabled
AvailableEndpoint = "/api/terminal/available/"
// WorkspaceInitEndpoint is used to initialize a kubeconfig in the workspace
WorkspaceInitEndpoint = "exec/init"
// WorkspaceActivityEndpoint is used to prevent idle timeout in a workspace
WorkspaceActivityEndpoint = "activity/tick"
// WorkspaceCreatorLabel stores the UID of the user that created the workspace. Only this user should be able to
// access the workspace
WorkspaceCreatorLabel = "controller.devfile.io/creator"
// WorkspaceRestrictedAcccessAnnotation signifies that a workspace expects webhooks to be enabled. If they are not,
// startup is blocked.
WorkspaceRestrictedAcccessAnnotation = "controller.devfile.io/restricted-access"
)
var log = capnslog.NewPackageLogger("github.com/devops-simba/console", "terminal")
// Proxy provides handlers to handle terminal related requests
type Proxy struct {
// A client with the correct TLS setup for communicating with servers withing cluster.
workspaceHttpClient *http.Client
TLSClientConfig *tls.Config
ClusterEndpoint *url.URL
}
func NewProxy(serviceTLS *tls.Config, TLSClientConfig *tls.Config, clusterEndpoint *url.URL) *Proxy {
return &Proxy{
workspaceHttpClient: &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{TLSClientConfig: serviceTLS},
},
TLSClientConfig: TLSClientConfig,
ClusterEndpoint: clusterEndpoint,
}
}
var (
WorkspaceGroupVersionResource = schema.GroupVersionResource{
Group: "workspace.devfile.io",
Version: "v1alpha1",
Resource: "devworkspaces",
}
UserGroupVersionResource = schema.GroupVersionResource{
Group: "user.openshift.io",
Version: "v1",
Resource: "users",
}
)
// HandleProxy evaluates the namespace and workspace names from URL and after check that
// it's created by the current user - proxies the request there
func (p *Proxy) HandleProxy(user *auth.User, w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.Header().Add("Allow", "POST")
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
operatorRunning, err := workspaceOperatorIsRunning()
if err != nil {
http.Error(w, "Failed to check workspace operator state. Cause: "+err.Error(), http.StatusInternalServerError)
return
}
if !operatorRunning {
http.Error(w, "Terminal endpoint is disabled: workspace operator is not deployed.", http.StatusForbidden)
return
}
enabledForUser, err := p.checkUserPermissions(user.Token)
if err != nil {
http.Error(w, "Failed to check workspace operator state. Cause: "+err.Error(), http.StatusInternalServerError)
return
}
if !enabledForUser {
http.Error(w, "Terminal is disabled for cluster-admin users.", http.StatusForbidden)
return
}
ok, namespace, workspaceName, path := stripTerminalAPIPrefix(r.URL.Path)
if !ok {
http.NotFound(w, r)
return
}
if path != WorkspaceInitEndpoint && path != WorkspaceActivityEndpoint {
http.Error(w, "Unsupported path", http.StatusForbidden)
return
}
client, err := p.createDynamicClient(user.Token)
if err != nil {
http.Error(w, "Failed to create k8s client for the authenticated user. Cause: "+err.Error(), http.StatusInternalServerError)
return
}
userId := user.ID
if userId == "" {
// user id is missing, auth is used that does not support user info propagated, like OpenShift OAuth
userInfo, err := client.Resource(UserGroupVersionResource).Get(context.TODO(), "~", metav1.GetOptions{})
if err != nil {
http.Error(w, "Failed to retrieve the current user info. Cause: "+err.Error(), http.StatusInternalServerError)
return
}
userId = string(userInfo.GetUID())
if userId == "" {
// uid is missing. it must be kube:admin
if "kube:admin" != userInfo.GetName() {
http.Error(w, "User must have UID to proceed authorization", http.StatusInternalServerError)
return
}
}
}
ws, err := client.Resource(WorkspaceGroupVersionResource).Namespace(namespace).Get(context.TODO(), workspaceName, metav1.GetOptions{})
if err != nil {
http.Error(w, "Failed to get the requested workspace. Cause: "+err.Error(), http.StatusForbidden)
return
}
creator := ws.GetLabels()[WorkspaceCreatorLabel]
if creator != userId {
http.Error(w, "User is not a owner of the requested workspace", http.StatusForbidden)
return
}
restrictAccess := ws.GetAnnotations()[WorkspaceRestrictedAcccessAnnotation]
if restrictAccess != "true" {
http.Error(w, "Workspace must have restricted access annotation", http.StatusForbidden)
return
}
terminalHost, err := p.getBaseTerminalHost(ws)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if terminalHost.Scheme != "https" {
http.Error(w, "Workspace is not served over https", http.StatusForbidden)
return
}
terminalHost.Path = path
if path == WorkspaceInitEndpoint {
p.handleExecInit(terminalHost, user.Token, r, w)
} else if path == WorkspaceActivityEndpoint {
p.handleActivity(terminalHost, user.Token, w)
} else {
http.Error(w, "Unknown path", http.StatusForbidden)
}
}
func (p *Proxy) HandleProxyEnabled(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
w.Header().Set("Allow", "GET")
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
enabled, err := workspaceOperatorIsRunning()
if err != nil {
log.Errorf("Failed to check if workspace operator is running: %s", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if !enabled {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (p *Proxy) handleExecInit(host *url.URL, token string, r *http.Request, w http.ResponseWriter) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read body of request: "+err.Error(), http.StatusInternalServerError)
return
}
wkspReq, err := http.NewRequest(http.MethodPost, host.String(), ioutil.NopCloser(bytes.NewReader(body)))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
wkspReq.Header.Set("Content-type", "application/json")
wkspReq.Header.Set("X-Forwarded-Access-Token", token)
p.proxyToWorkspace(wkspReq, w)
}
func (p *Proxy) handleActivity(host *url.URL, token string, w http.ResponseWriter) {
wkspReq, err := http.NewRequest(http.MethodPost, host.String(), nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
wkspReq.Header.Set("X-Forwarded-Access-Token", token)
p.proxyToWorkspace(wkspReq, w)
}
// stripTerminalAPIPrefix strips path prefix that is expected for Terminal API request
func stripTerminalAPIPrefix(requestPath string) (ok bool, namespace string, workspaceName string, path string) {
// URL is supposed to have the following format
// -> /api/terminal/proxy/{namespace}/{workspace-name}/{path} < optional
// -> 0 / 1 / 2 / 3 / 4 / 5 / 6
segments := strings.SplitN(requestPath, "/", 7)
if len(segments) < 6 {
return false, "", "", ""
} else {
namespace = segments[4]
workspaceName = segments[5]
if len(segments) == 7 {
path = segments[6]
}
return true, namespace, workspaceName, path
}
}
// getBaseTerminalHost evaluates ideUrl from the specified workspace and extract host from it
func (p *Proxy) getBaseTerminalHost(ws *unstructured.Unstructured) (*url.URL, error) {
ideUrl, success, err := unstructured.NestedString(ws.UnstructuredContent(), "status", "ideUrl")
if !success {
return nil, errors.New("the specified workspace does not have ideUrl in its status")
}
if err != nil {
return nil, errors.New("failed to evaluate ide URL for the specified workspace. Cause: " + err.Error())
}
terminalUrl, err := url.Parse(ideUrl)
if err != nil {
return nil, errors.New("failed to parse workspace ideUrl " + ideUrl)
}
terminalHost, err := url.Parse(terminalUrl.Scheme + "://" + terminalUrl.Host)
if err != nil {
return nil, errors.New("failed to parse workspace ideUrl host " + ideUrl)
}
return terminalHost, nil
}
func (p *Proxy) proxyToWorkspace(wkspReq *http.Request, w http.ResponseWriter) {
wkspResp, err := p.workspaceHttpClient.Do(wkspReq)
if err != nil {
http.Error(w, "Failed to proxy request. Cause: "+err.Error(), http.StatusInternalServerError)
return
}
for k, vv := range wkspResp.Header {
for _, v := range vv {
w.Header().Add(k, v)
}
}
w.WriteHeader(wkspResp.StatusCode)
_, err = io.Copy(w, wkspResp.Body)
if err != nil {
panic(http.ErrAbortHandler)
}
_ = wkspResp.Body.Close()
}