forked from 1Panel-dev/KubePi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
v1.go
448 lines (412 loc) · 11.9 KB
/
v1.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
package v1
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"strings"
"github.com/godtool/kubeone/service/api/v1/mfa"
"github.com/godtool/kubeone/service/server"
"github.com/godtool/kubeone/service/api/v1/file"
"github.com/kataras/iris/v12/middleware/jwt"
"github.com/asdine/storm/v3"
pkgV1 "github.com/godtool/kubeone/pkg/api/v1"
"github.com/godtool/kubeone/pkg/collectons"
"github.com/godtool/kubeone/pkg/i18n"
"github.com/godtool/kubeone/service/api/v1/chart"
"github.com/godtool/kubeone/service/api/v1/cluster"
"github.com/godtool/kubeone/service/api/v1/imagerepo"
"github.com/godtool/kubeone/service/api/v1/ldap"
"github.com/godtool/kubeone/service/api/v1/proxy"
"github.com/godtool/kubeone/service/api/v1/role"
"github.com/godtool/kubeone/service/api/v1/session"
"github.com/godtool/kubeone/service/api/v1/system"
"github.com/godtool/kubeone/service/api/v1/user"
"github.com/godtool/kubeone/service/api/v1/webkubectl"
"github.com/godtool/kubeone/service/api/v1/ws"
v1 "github.com/godtool/kubeone/service/model/v1"
v1Role "github.com/godtool/kubeone/service/model/v1/role"
v1System "github.com/godtool/kubeone/service/model/v1/system"
"github.com/godtool/kubeone/service/service/v1/common"
v1RoleService "github.com/godtool/kubeone/service/service/v1/role"
v1RoleBindingService "github.com/godtool/kubeone/service/service/v1/rolebinding"
v1SystemService "github.com/godtool/kubeone/service/service/v1/system"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/context"
"github.com/kataras/iris/v12/core/router"
)
var resourceWhiteList = WhiteList{"sessions", "proxy", "ws", "charts", "webkubectl", "apps", "mfa", "pod"}
type WhiteList []string
func (w WhiteList) In(name string) bool {
for i := range w {
if w[i] == name {
return true
}
}
return false
}
func authHandler() iris.Handler {
return func(ctx *context.Context) {
var p session.UserProfile
if ctx.GetHeader("Authorization") != "" {
pr := jwt.Get(ctx).(*session.UserProfile)
p = *pr
} else {
p = server.SessionMgr.Start(ctx).Get("profile").(session.UserProfile)
}
if p.Name == "" {
ctx.Values().Set("message", "please login")
ctx.StopWithStatus(iris.StatusUnauthorized)
return
}
ctx.Values().Set("profile", p)
ctx.Next()
}
}
func langHandler() iris.Handler {
return func(ctx *context.Context) {
p := ctx.Values().Get("profile")
u, ok := p.(session.UserProfile)
lang := i18n.LanguageZhCN
if ok {
lang = u.Language
}
ctx.Values().Set("language", lang)
ctx.Next()
}
}
func pageHandler() iris.Handler {
return func(ctx *context.Context) {
if ctx.URLParamExists(pkgV1.PageSize) && ctx.URLParamExists(pkgV1.PageNum) {
pageNum, err := ctx.URLParamInt(pkgV1.PageNum)
if err != nil {
ctx.Values().Set("message", fmt.Sprintf("page num format err %s", err.Error()))
ctx.StopWithStatus(iris.StatusBadRequest)
return
}
pageSize, err := ctx.URLParamInt(pkgV1.PageSize)
if err != nil {
ctx.Values().Set("message", fmt.Sprintf("page size format err %s", err.Error()))
ctx.StopWithStatus(iris.StatusBadRequest)
return
}
ctx.Values().Set(pkgV1.PageNum, pageNum)
ctx.Values().Set(pkgV1.PageSize, pageSize)
}
ctx.Next()
}
}
type logHelper struct {
Name string `json:"name"`
Metadata v1.Metadata
}
func logHandler() iris.Handler {
return func(ctx *context.Context) {
method := strings.ToLower(ctx.Method())
if method != "post" && method != "delete" && method != "put" {
ctx.Next()
return
}
resourceName := ctx.Values().GetString("resource")
if resourceName == "" || resourceWhiteList.In(resourceName) {
ctx.Next()
return
}
currentPath := ctx.GetCurrentRoute().Path()
path := strings.Replace(ctx.Request().URL.Path, "/kubepi/api/v1/", "", 1)
currentPath = strings.Replace(currentPath, "/kubepi/api/v1/", "", 1)
if strings.HasSuffix(path, "search") {
ctx.Next()
return
}
u := ctx.Values().Get("profile")
profile := u.(session.UserProfile)
var log v1System.OperationLog
log.Operator = profile.Name
log.Operation = method
//handle ldap operate
if strings.Contains(path, "ldap") {
if strings.Contains(path, "import") {
log.Operation = "import"
}
if strings.Contains(path, "sync") {
log.Operation = "sync"
}
if strings.Contains(path, "connect") {
log.Operation = "testConnect"
}
if strings.Contains(path, "login") {
log.Operation = "testLogin"
}
}
pathResource := strings.Split(path, "/")
if strings.HasPrefix(currentPath, "clusters/:name") {
if len(pathResource) < 3 {
log.OperationDomain = pathResource[0]
if method != "post" {
log.SpecificInformation = pathResource[1]
}
} else {
log.OperationDomain = fmt.Sprintf("%s_%s", pathResource[0], pathResource[2])
if method != "post" {
if len(pathResource) > 3 {
log.SpecificInformation = fmt.Sprintf("[%s] %s", pathResource[1], pathResource[3])
} else {
log.SpecificInformation = fmt.Sprintf("[%s] %s", pathResource[1], "-")
}
}
}
} else {
log.OperationDomain = strings.Split(currentPath, "/")[0]
if method != "post" {
if len(pathResource) > 1 {
log.SpecificInformation = pathResource[1]
} else {
log.SpecificInformation = "-"
}
}
}
if !strings.Contains(currentPath, "upload") {
if method == "post" {
var req logHelper
data, _ := ctx.GetBody()
if err := json.Unmarshal(data, &req); err != nil {
ctx.Next()
}
if len(req.Name) == 0 {
req.Name = req.Metadata.Name
}
if strings.HasPrefix(currentPath, "clusters/:name") {
log.SpecificInformation = fmt.Sprintf("[%s] %s", pathResource[1], req.Name)
} else {
log.SpecificInformation = req.Name
}
ctx.Request().Body = ioutil.NopCloser(bytes.NewBuffer(data))
}
}
systemService := v1SystemService.NewService()
go systemService.CreateOperationLog(&log, common.DBOptions{})
ctx.Next()
}
}
func resourceExtractHandler() iris.Handler {
return func(ctx *context.Context) {
path := ctx.Request().URL.Path
ss := strings.Split(path, "/")
// "" "api" "v1" "resource"
if len(ss) >= 5 {
ctx.Values().Set("resource", ss[4])
}
ctx.Next()
}
}
func roleHandler() iris.Handler {
return func(ctx *context.Context) {
// 查询当前用户的角色
// 查询角色的 rolebinding 获取 roles
p := ctx.Values().Get("profile")
u := p.(session.UserProfile)
if u.IsAdministrator {
ctx.Next()
return
}
roleBindingService := v1RoleBindingService.NewService()
rbs, err := roleBindingService.GetRoleBindingBySubject(v1Role.Subject{
Kind: "User",
Name: u.Name,
}, common.DBOptions{})
if err != nil {
if !errors.As(err, &storm.ErrNotFound) {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.Values().Set("message", err.Error())
return
}
}
roleNameHash := map[string]struct{}{}
for i := range rbs {
roleName := rbs[i].RoleRef
roleNameHash[roleName] = struct{}{}
}
var roleNames []string
for key := range roleNameHash {
roleNames = append(roleNames, key)
}
roleService := v1RoleService.NewService()
rs, err := roleService.GetByNames(roleNames, common.DBOptions{})
if err != nil {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.Values().Set("message", err.Error())
return
}
ctx.Values().Set("roles", rs)
ctx.Next()
}
}
func getVerbByRoute(path, method string) string {
switch strings.ToLower(method) {
case "put":
return "update"
case "delete":
return "delete"
case "get":
if strings.Contains(path, "/:name") {
return "get"
} else {
return "list"
}
case "post":
if strings.HasSuffix(path, "search") {
return "list"
}
return "create"
}
return ""
}
func apiResourceHandler(party iris.Party) iris.Handler {
return func(ctx *context.Context) {
//1. 确定所有的api资源有哪些
apiBuilder := party.(*router.APIBuilder)
routes := apiBuilder.GetRoutes()
resourceMap := map[string]*collectons.StringSet{}
for i := range routes {
if strings.HasPrefix(routes[i].Path, "/kubepi/api/v1/") {
ss := strings.Split(routes[i].Path, "/")
if len(ss) >= 5 {
resourceName := ss[4]
//过滤session资源
if resourceWhiteList.In(resourceName) {
continue
}
if _, ok := resourceMap[resourceName]; !ok {
resourceMap[resourceName] = collectons.NewStringSet()
}
resourceMap[resourceName].Add(getVerbByRoute(routes[i].Path, routes[i].Method))
}
}
}
displayMap := map[string][]string{}
for k := range resourceMap {
verbs := resourceMap[k]
if len(verbs.ToSlice()) > 0 {
displayMap[k] = verbs.ToSlice()
}
}
if ops, ok := displayMap["clusters"]; ok {
ops = append(ops, "authorization")
displayMap["clusters"] = ops
}
ctx.Values().Set("data", displayMap)
}
}
func roleAccessHandler() iris.Handler {
return func(ctx *context.Context) {
//// 查询角色的 resources
//// 通过api resource 过滤出来资源主体,method 过滤操作
p := ctx.Values().Get("profile")
u := p.(session.UserProfile)
isInWhiteList := false
for _, path := range resourceWhiteList {
if strings.Contains(ctx.Request().URL.Path, fmt.Sprintf("/%s", path)) && path != "sessions" {
isInWhiteList = true
break
}
}
if !isInWhiteList {
// 放通admin权限
if u.IsAdministrator {
ctx.Next()
return
}
rs := ctx.Values().Get("roles")
roles := rs.([]v1Role.Role)
requestResource := ctx.Values().GetString("resource")
if requestResource != "" {
currentRoute := ctx.GetCurrentRoute()
requestVerb := getVerbByRoute(currentRoute.Path(), currentRoute.Method())
resourceMatched, methodMatch := matchRoles(requestResource, requestVerb, roles)
if !(resourceMatched && methodMatch) {
ctx.StopWithStatus(iris.StatusForbidden)
ctx.Values().Set("message", []string{"user %s can not access resource %s %s", u.Name, requestResource, requestVerb})
return
}
}
}
ctx.Next()
}
}
func matchRoles(requestResource, requestMethod string, rs []v1Role.Role) (bool, bool) {
resourceMatch := false
methodMatch := false
for i := range rs {
for j := range rs[i].Rules {
for k := range rs[i].Rules[j].Resource {
if rs[i].Rules[j].Resource[k] == requestResource || rs[i].Rules[j].Resource[k] == "*" {
resourceMatch = true
for x := range rs[i].Rules[j].Verbs {
if rs[i].Rules[j].Verbs[x] == requestMethod || rs[i].Rules[j].Verbs[x] == "*" {
methodMatch = true
}
}
}
}
}
}
return resourceMatch, methodMatch
}
func resourceNameInvalidHandler() iris.Handler {
return func(ctx *context.Context) {
r := ctx.GetCurrentRoute()
if strings.Contains(r.Path(), "/:name") {
resourceName := ctx.Params().GetString("name")
if resourceName == "" {
ctx.StatusCode(iris.StatusBadRequest)
ctx.Values().Set("message", fmt.Sprintf("invalid resource name %s", resourceName))
return
}
}
ctx.Next()
}
}
func WarpedJwtHandler() iris.Handler {
verifier := jwt.NewVerifier(jwt.HS256, server.Config().Spec.Jwt.Key)
verifier.WithDefaultBlocklist()
verifyMiddleware := verifier.Verify(func() interface{} {
return new(session.UserProfile)
})
return func(ctx *context.Context) {
sess := server.SessionMgr.Start(ctx)
if sess.Get("profile") != nil {
ctx.Next()
return
}
verifyMiddleware(ctx)
}
}
func AddV1Route(app iris.Party) {
v1Party := app.Party("/v1")
session.Install(v1Party)
mfa.Install(v1Party)
v1Party.Use(langHandler())
v1Party.Use(pageHandler())
authParty := v1Party.Party("")
authParty.Use(WarpedJwtHandler())
authParty.Use(authHandler())
authParty.Use(resourceExtractHandler())
authParty.Use(roleHandler())
authParty.Use(roleAccessHandler())
authParty.Use(resourceNameInvalidHandler())
authParty.Use(logHandler())
authParty.Get("/", apiResourceHandler(authParty))
user.Install(authParty)
cluster.Install(authParty)
role.Install(authParty)
system.Install(authParty)
proxy.Install(authParty)
ws.Install(authParty)
chart.Install(authParty)
webkubectl.Install(authParty, v1Party)
ldap.Install(authParty)
imagerepo.Install(authParty)
file.Install(authParty)
}