...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package utils
17
18 import (
19 "net/http"
20
21 "github.com/gin-gonic/gin"
22 authorizationv1 "k8s.io/api/authorization/v1"
23 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
24
25 "github.com/chaos-mesh/chaos-mesh/pkg/clientpool"
26 config "github.com/chaos-mesh/chaos-mesh/pkg/config"
27 "github.com/chaos-mesh/chaos-mesh/pkg/log"
28 "github.com/chaos-mesh/chaos-mesh/pkg/mock"
29 )
30
31 func AuthMiddleware(c *gin.Context, config *config.ChaosDashboardConfig) {
32 if mockResult := mock.On("AuthMiddleware"); mockResult != nil {
33 c.Next()
34
35 return
36 }
37
38 kubeCli, err := clientpool.ExtractTokenAndGetAuthClient(c.Request.Header)
39 if err != nil {
40 SetAPIError(c, ErrBadRequest.WrapWithNoMessage(err))
41
42 return
43 }
44
45 ns := c.Query("namespace")
46
47 if ns == "" && !config.ClusterScoped && config.TargetNamespace != "" {
48 ns = config.TargetNamespace
49
50 log.L().WithName("auth middleware").V(1).Info("Replace query namespace", "ns", ns)
51 }
52
53 verb := "list"
54 if c.Request.Method != http.MethodGet {
55
56 verb = "patch"
57 }
58
59 sar := &authorizationv1.SelfSubjectAccessReview{
60 Spec: authorizationv1.SelfSubjectAccessReviewSpec{
61 ResourceAttributes: &authorizationv1.ResourceAttributes{
62 Namespace: ns,
63 Verb: verb,
64 Group: "chaos-mesh.org",
65 Resource: "*",
66 },
67 },
68 }
69
70 result, err := kubeCli.SelfSubjectAccessReviews().Create(c.Request.Context(), sar, metav1.CreateOptions{})
71 if err != nil {
72 SetAPImachineryError(c, ErrInternalServer.WrapWithNoMessage(err))
73
74 return
75 }
76
77 if !result.Status.Allowed {
78 if len(ns) == 0 {
79 SetAPIError(c, ErrNoClusterPrivilege.New("can't %s resource in the cluster", verb))
80 } else {
81 SetAPIError(c, ErrNoNamespacePrivilege.New("can't %s resource in namespace %s", verb, ns))
82 }
83
84 return
85 }
86
87 c.Next()
88 }
89