forked from devtron-labs/devtron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInstalledAppRestHandler.go
372 lines (346 loc) · 14 KB
/
InstalledAppRestHandler.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
/*
* Copyright (c) 2020 Devtron Labs
*
* 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
*
* http://www.apache.org/licenses/LICENSE-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 OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package appStore
import (
"encoding/json"
"errors"
"fmt"
bean2 "github.com/devtron-labs/devtron/api/bean"
client "github.com/devtron-labs/devtron/api/helm-app"
openapi "github.com/devtron-labs/devtron/api/helm-app/openapiClient"
"github.com/devtron-labs/devtron/api/restHandler/common"
"github.com/devtron-labs/devtron/client/argocdServer/application"
appStoreBean "github.com/devtron-labs/devtron/pkg/appStore/bean"
"github.com/devtron-labs/devtron/pkg/appStore/deployment/service"
"github.com/devtron-labs/devtron/pkg/cluster"
"github.com/devtron-labs/devtron/pkg/user"
"github.com/devtron-labs/devtron/pkg/user/casbin"
"github.com/devtron-labs/devtron/util/argo"
"github.com/devtron-labs/devtron/util/rbac"
"github.com/devtron-labs/devtron/util/response"
"github.com/gorilla/mux"
"go.uber.org/zap"
"gopkg.in/go-playground/validator.v9"
"net/http"
"strconv"
"strings"
)
type InstalledAppRestHandler interface {
GetAllInstalledApp(w http.ResponseWriter, r *http.Request)
DeployBulk(w http.ResponseWriter, r *http.Request)
CheckAppExists(w http.ResponseWriter, r *http.Request)
DefaultComponentInstallation(w http.ResponseWriter, r *http.Request)
FetchAppDetailsForInstalledApp(w http.ResponseWriter, r *http.Request)
}
type InstalledAppRestHandlerImpl struct {
Logger *zap.SugaredLogger
userAuthService user.UserService
enforcer casbin.Enforcer
enforcerUtil rbac.EnforcerUtil
installedAppService service.InstalledAppService
validator *validator.Validate
clusterService cluster.ClusterService
acdServiceClient application.ServiceClient
appStoreDeploymentService service.AppStoreDeploymentService
helmAppClient client.HelmAppClient
helmAppService client.HelmAppService
argoUserService argo.ArgoUserService
}
func NewInstalledAppRestHandlerImpl(Logger *zap.SugaredLogger, userAuthService user.UserService,
enforcer casbin.Enforcer, enforcerUtil rbac.EnforcerUtil, installedAppService service.InstalledAppService,
validator *validator.Validate, clusterService cluster.ClusterService, acdServiceClient application.ServiceClient,
appStoreDeploymentService service.AppStoreDeploymentService, helmAppClient client.HelmAppClient, helmAppService client.HelmAppService,
argoUserService argo.ArgoUserService,
) *InstalledAppRestHandlerImpl {
return &InstalledAppRestHandlerImpl{
Logger: Logger,
userAuthService: userAuthService,
enforcer: enforcer,
enforcerUtil: enforcerUtil,
installedAppService: installedAppService,
validator: validator,
clusterService: clusterService,
acdServiceClient: acdServiceClient,
appStoreDeploymentService: appStoreDeploymentService,
helmAppService: helmAppService,
helmAppClient: helmAppClient,
argoUserService: argoUserService,
}
}
func (handler InstalledAppRestHandlerImpl) GetAllInstalledApp(w http.ResponseWriter, r *http.Request) {
userId, err := handler.userAuthService.GetLoggedInUser(r)
if userId == 0 || err != nil {
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
return
}
v := r.URL.Query()
token := r.Header.Get("token")
var envIds []int
envsQueryParam := v.Get("envIds")
if envsQueryParam != "" {
envsStr := strings.Split(envsQueryParam, ",")
for _, t := range envsStr {
envId, err := strconv.Atoi(t)
if err != nil {
handler.Logger.Errorw("request err, GetAllInstalledApp", "err", err, "envsQueryParam", envsQueryParam)
response.WriteResponse(http.StatusBadRequest, "please send valid envs", w, errors.New("env id invalid"))
return
}
envIds = append(envIds, envId)
}
}
clusterIdString := v.Get("clusterIds")
var clusterIds []int
if clusterIdString != "" {
clusterIdSlices := strings.Split(clusterIdString, ",")
for _, clusterId := range clusterIdSlices {
id, err := strconv.Atoi(clusterId)
if err != nil {
handler.Logger.Errorw("request err, GetAllInstalledApp", "err", err, "clusterIdString", clusterIdString)
common.WriteJsonResp(w, err, "please send valid cluster Ids", http.StatusBadRequest)
return
}
clusterIds = append(clusterIds, id)
}
}
onlyDeprecated := false
deprecatedStr := v.Get("onlyDeprecated")
if len(deprecatedStr) > 0 {
onlyDeprecated, err = strconv.ParseBool(deprecatedStr)
if err != nil {
onlyDeprecated = false
}
}
var chartRepoIds []int
chartRepoIdsStr := v.Get("chartRepoIds")
if len(chartRepoIdsStr) > 0 {
chartRepoIdStrArr := strings.Split(chartRepoIdsStr, ",")
for _, chartRepoIdStr := range chartRepoIdStrArr {
chartRepoId, err := strconv.Atoi(chartRepoIdStr)
if err == nil {
chartRepoIds = append(chartRepoIds, chartRepoId)
}
}
}
appStoreName := v.Get("appStoreName")
appName := v.Get("appName")
offset := 0
offsetStr := v.Get("offset")
if len(offsetStr) > 0 {
offset, _ = strconv.Atoi(offsetStr)
}
size := 0
sizeStr := v.Get("size")
if len(sizeStr) > 0 {
size, _ = strconv.Atoi(sizeStr)
}
filter := &appStoreBean.AppStoreFilter{OnlyDeprecated: onlyDeprecated, ChartRepoId: chartRepoIds, AppStoreName: appStoreName, EnvIds: envIds, AppName: appName, ClusterIds: clusterIds}
if size > 0 {
filter.Size = size
filter.Offset = offset
}
handler.Logger.Infow("request payload, GetAllInstalledApp", "envsQueryParam", envsQueryParam)
res, err := handler.installedAppService.GetAll(filter)
if err != nil {
handler.Logger.Errorw("service err, GetAllInstalledApp", "err", err, "envsQueryParam", envsQueryParam)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
authorizedApp := make([]openapi.HelmApp, 0)
for _, app := range *res.HelmApps {
appName := *app.AppName
envId := (*app.EnvironmentDetail).EnvironmentId
//rbac block starts from here
object, object2 := handler.enforcerUtil.GetHelmObjectByAppNameAndEnvId(appName, int(*envId))
var ok bool
if object2 == "" {
ok = handler.enforcer.Enforce(token, casbin.ResourceHelmApp, casbin.ActionGet, object)
} else {
// futuristic case
ok = handler.enforcer.Enforce(token, casbin.ResourceHelmApp, casbin.ActionGet, object) || handler.enforcer.Enforce(token, casbin.ResourceHelmApp, casbin.ActionGet, object2)
}
if !ok {
continue
}
authorizedApp = append(authorizedApp, app)
//rback block ends here
}
res.HelmApps = &authorizedApp
common.WriteJsonResp(w, err, res, http.StatusOK)
}
func (handler *InstalledAppRestHandlerImpl) DeployBulk(w http.ResponseWriter, r *http.Request) {
userId, err := handler.userAuthService.GetLoggedInUser(r)
if userId == 0 || err != nil {
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
return
}
decoder := json.NewDecoder(r.Body)
var request appStoreBean.ChartGroupInstallRequest
err = decoder.Decode(&request)
if err != nil {
handler.Logger.Errorw("request err, DeployBulk", "err", err, "payload", request)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
err = handler.validator.Struct(request)
if err != nil {
handler.Logger.Errorw("validation err, DeployBulk", "err", err, "payload", request)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
request.UserId = userId
handler.Logger.Infow("request payload, DeployBulk", "payload", request)
//RBAC block starts from here
token := r.Header.Get("token")
rbacObject := ""
if ok := handler.enforcer.Enforce(token, casbin.ResourceChartGroup, casbin.ActionUpdate, rbacObject); !ok {
common.WriteJsonResp(w, fmt.Errorf("unauthorized user"), nil, http.StatusForbidden)
return
}
//RBAC block ends here
for _, item := range request.ChartGroupInstallChartRequest {
isChartRepoActive, err := handler.appStoreDeploymentService.IsChartRepoActive(item.AppStoreVersion)
if err != nil {
handler.Logger.Errorw("service err, CreateInstalledApp", "err", err, "payload", request)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
if !isChartRepoActive {
common.WriteJsonResp(w, fmt.Errorf("chart repo is disabled"), nil, http.StatusNotAcceptable)
return
}
}
res, err := handler.installedAppService.DeployBulk(&request)
if err != nil {
handler.Logger.Errorw("service err, DeployBulk", "err", err, "payload", request)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
common.WriteJsonResp(w, err, res, http.StatusOK)
}
func (handler *InstalledAppRestHandlerImpl) CheckAppExists(w http.ResponseWriter, r *http.Request) {
userId, err := handler.userAuthService.GetLoggedInUser(r)
if userId == 0 || err != nil {
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
return
}
decoder := json.NewDecoder(r.Body)
var request []*appStoreBean.AppNames
err = decoder.Decode(&request)
if err != nil {
handler.Logger.Errorw("request err, CheckAppExists", "err", err, "payload", request)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
handler.Logger.Infow("request payload, CheckAppExists", "payload", request)
res, err := handler.installedAppService.CheckAppExists(request)
if err != nil {
handler.Logger.Errorw("service err, CheckAppExists", "err", err, "payload", request)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
common.WriteJsonResp(w, err, res, http.StatusOK)
}
func (impl *InstalledAppRestHandlerImpl) DefaultComponentInstallation(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("token")
userId, err := impl.userAuthService.GetLoggedInUser(r)
if userId == 0 || err != nil {
impl.Logger.Errorw("service err, DefaultComponentInstallation", "error", err, "userId", userId)
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
return
}
vars := mux.Vars(r)
clusterId, err := strconv.Atoi(vars["clusterId"])
if err != nil {
impl.Logger.Errorw("request err, DefaultComponentInstallation", "error", err, "clusterId", clusterId)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
impl.Logger.Errorw("request payload, DefaultComponentInstallation", "clusterId", clusterId)
cluster, err := impl.clusterService.FindById(clusterId)
if err != nil {
impl.Logger.Errorw("service err, DefaultComponentInstallation", "error", err, "clusterId", clusterId)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
// RBAC enforcer applying
if ok := impl.enforcer.Enforce(token, casbin.ResourceCluster, casbin.ActionUpdate, strings.ToLower(cluster.ClusterName)); !ok {
common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)
return
}
// RBAC enforcer ends
isTriggered, err := impl.installedAppService.DeployDefaultChartOnCluster(cluster, userId)
if err != nil {
impl.Logger.Errorw("service err, DefaultComponentInstallation", "error", err, "cluster", cluster)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
common.WriteJsonResp(w, err, isTriggered, http.StatusOK)
}
func (handler *InstalledAppRestHandlerImpl) FetchAppDetailsForInstalledApp(w http.ResponseWriter, r *http.Request) {
userId, err := handler.userAuthService.GetLoggedInUser(r)
if userId == 0 || err != nil {
common.WriteJsonResp(w, err, nil, http.StatusUnauthorized)
return
}
vars := mux.Vars(r)
installedAppId, err := strconv.Atoi(vars["installed-app-id"])
if err != nil {
handler.Logger.Errorw("request err, FetchAppDetailsForInstalledApp", "err", err, "installedAppId", installedAppId)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
token := r.Header.Get("token")
envId, err := strconv.Atoi(vars["env-id"])
if err != nil {
handler.Logger.Errorw("request err, FetchAppDetailsForInstalledApp", "err", err, "installedAppId", installedAppId, "envId", envId)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
handler.Logger.Infow("request payload, FetchAppDetailsForInstalledApp, app store", "installedAppId", installedAppId, "envId", envId)
appDetail, err := handler.installedAppService.FindAppDetailsForAppstoreApplication(installedAppId, envId)
if err != nil {
handler.Logger.Errorw("service err, FetchAppDetailsForInstalledApp, app store", "err", err, "installedAppId", installedAppId, "envId", envId)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
//rbac block starts from here
object, object2 := handler.enforcerUtil.GetHelmObjectByAppNameAndEnvId(appDetail.AppName, appDetail.EnvironmentId)
var ok bool
if object2 == "" {
ok = handler.enforcer.Enforce(token, casbin.ResourceHelmApp, casbin.ActionGet, object)
} else {
ok = handler.enforcer.Enforce(token, casbin.ResourceHelmApp, casbin.ActionGet, object) || handler.enforcer.Enforce(token, casbin.ResourceHelmApp, casbin.ActionGet, object2)
}
if !ok {
common.WriteJsonResp(w, fmt.Errorf("unauthorized user"), nil, http.StatusForbidden)
return
}
//rback block ends here
if len(appDetail.AppName) > 0 && len(appDetail.EnvironmentName) > 0 {
handler.fetchResourceTree(w, r, &appDetail)
} else {
appDetail.ResourceTree = map[string]interface{}{}
handler.Logger.Warnw("appName and envName not found - avoiding resource tree call", "app", appDetail.AppName, "env", appDetail.EnvironmentName)
}
common.WriteJsonResp(w, err, appDetail, http.StatusOK)
}
func (handler *InstalledAppRestHandlerImpl) fetchResourceTree(w http.ResponseWriter, r *http.Request, appDetail *bean2.AppDetailContainer) {
ctx := r.Context()
cn, _ := w.(http.CloseNotifier)
handler.installedAppService.FetchResourceTree(ctx, cn, appDetail)
}