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