Skip to content

Commit 0b64f4e

Browse files
authored
fix: api responses (#6789)
* fix: API token generation api responses refactoring * fix: register custom validation against tag for api token name validations * fix: register custom validation against tag for api token name validations * Revert "fix: register custom validation against tag for api token name validations" This reverts commit 7593c27. * fix: remove `required` validation from Description and expiryAtInMs * fix: adding resource conflict api response in WriteJsonResp utility * fix: path params int validation updated to whole numbers only * fix: handled resource not found response for update and delete api, token * fix: validation for SSO config name field * fix: enhanced query param validation for commit metadata for pipeline material * fix: disable updating clsutername and api name in update clsuter api * fix: enhanced api response in query param validation failure reeors in ge default deployment template * fix: disable modifying cluster nae and env name in update env api * fix: resolving review comments * fix: resolving review comments
1 parent 3ca0e87 commit 0b64f4e

File tree

8 files changed

+81
-14
lines changed

8 files changed

+81
-14
lines changed

api/auth/sso/SsoLoginHandler.go

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,12 @@ func (handler SsoLoginRestHandlerImpl) CreateSSOLoginConfig(w http.ResponseWrite
7070
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
7171
return
7272
}
73-
73+
err = handler.validator.Struct(dto)
74+
if err != nil {
75+
handler.logger.Errorw("validation err in CreateSSOLoginConfig", "err", err, "payload", dto)
76+
common.HandleValidationErrors(w, r, err)
77+
return
78+
}
7479
token := r.Header.Get("token")
7580
if ok := handler.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionCreate, "*"); !ok {
7681
common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)
@@ -103,7 +108,12 @@ func (handler SsoLoginRestHandlerImpl) UpdateSSOLoginConfig(w http.ResponseWrite
103108
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
104109
return
105110
}
106-
111+
err = handler.validator.Struct(dto)
112+
if err != nil {
113+
handler.logger.Errorw("validation err in CreateSSOLoginConfig", "err", err, "payload", dto)
114+
common.HandleValidationErrors(w, r, err)
115+
return
116+
}
107117
token := r.Header.Get("token")
108118
if ok := handler.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionUpdate, "*"); !ok {
109119
common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)

api/cluster/ClusterRestHandler.go

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -462,6 +462,20 @@ func (impl ClusterRestHandlerImpl) Update(w http.ResponseWriter, r *http.Request
462462
if util2.IsBaseStack() {
463463
ctx = context.WithValue(ctx, "token", token)
464464
}
465+
466+
// checkImmutable fields - cluster name
467+
modifiedCluster, err := impl.clusterService.FindByIdWithoutConfig(bean.Id)
468+
if err != nil {
469+
impl.logger.Errorw("err finding cluster name", "error", err, "clusterId", bean.Id)
470+
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
471+
return
472+
}
473+
474+
if bean.ClusterName != modifiedCluster.ClusterName {
475+
common.WriteJsonResp(w, errors.New("cluster name cannot be changed"), nil, http.StatusConflict)
476+
return
477+
}
478+
465479
_, err = impl.clusterService.Update(ctx, &bean, userId)
466480
if err != nil {
467481
impl.logger.Errorw("service err, Update", "error", err, "payload", bean)
@@ -703,12 +717,11 @@ func (impl ClusterRestHandlerImpl) HandleRbacForClusterNamespace(userId int32, t
703717

704718
func (impl ClusterRestHandlerImpl) GetClusterNamespaces(w http.ResponseWriter, r *http.Request) {
705719
//token := r.Header.Get("token")
706-
vars := mux.Vars(r)
707-
clusterIdString := vars["clusterId"]
720+
//vars := mux.Vars(r)
708721

709722
userId, err := impl.userService.GetLoggedInUser(r)
710723
if userId == 0 || err != nil {
711-
impl.logger.Errorw("user not authorized", "error", err, "userId", userId)
724+
impl.logger.Errorw("user not authorized", "userId", userId, "error", err)
712725
common.HandleUnauthorized(w, r)
713726
return
714727
}
@@ -717,10 +730,10 @@ func (impl ClusterRestHandlerImpl) GetClusterNamespaces(w http.ResponseWriter, r
717730
if ok := impl.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionGet, "*"); ok {
718731
isActionUserSuperAdmin = true
719732
}
720-
clusterId, err := strconv.Atoi(clusterIdString)
733+
// extract cluster and handle response on error
734+
clusterId, err := common.ExtractIntPathParamWithContext(w, r, "clusterId", "cluster")
721735
if err != nil {
722-
impl.logger.Errorw("failed to extract clusterId from param", "error", err, "clusterId", clusterIdString)
723-
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
736+
impl.logger.Error("error in parsing clusterId", "clusterId", clusterId, "err", err)
724737
return
725738
}
726739

api/cluster/EnvironmentRestHandler.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,16 @@ func (impl EnvironmentRestHandlerImpl) Update(w http.ResponseWriter, r *http.Req
293293
}
294294
//RBAC enforcer Ends
295295

296+
// checkImmutable fields
297+
if modifiedEnvironment.Environment != bean.Environment {
298+
common.WriteJsonResp(w, errors.New("environment name cannot be changed"), nil, http.StatusConflict)
299+
return
300+
}
301+
if modifiedEnvironment.Namespace != bean.Namespace {
302+
common.WriteJsonResp(w, errors.New("namespace cannot be changed"), nil, http.StatusConflict)
303+
return
304+
}
305+
296306
res, err := impl.environmentClusterMappingsService.Update(&bean, userId)
297307
if err != nil {
298308
impl.logger.Errorw("service err, Update", "err", err, "payload", bean)

api/restHandler/app/pipeline/configure/BuildPipelineRestHandler.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1664,9 +1664,11 @@ func (handler *PipelineConfigRestHandlerImpl) GetCommitMetadataForPipelineMateri
16641664
return
16651665
}
16661666
vars := mux.Vars(r)
1667-
ciPipelineMaterialId, err := strconv.Atoi(vars["ciPipelineMaterialId"])
1667+
ciPipelineMaterialIdString := vars["ciPipelineMaterialId"]
1668+
ciPipelineMaterialId, err := strconv.Atoi(ciPipelineMaterialIdString)
16681669
if err != nil {
1669-
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
1670+
handler.Logger.Errorw("failed to extract ciPipelineMaterialId from param must be integer", "error", err, "ciPipelineMaterialId", ciPipelineMaterialIdString)
1671+
common.HandleParameterError(w, r, "ciPipelineMaterialId", ciPipelineMaterialIdString)
16701672
return
16711673
}
16721674

api/restHandler/app/pipeline/configure/DeploymentPipelineRestHandler.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -987,13 +987,13 @@ func (handler *PipelineConfigRestHandlerImpl) GetDefaultDeploymentTemplate(w htt
987987
appId, err := strconv.Atoi(vars["appId"])
988988
if err != nil {
989989
handler.Logger.Error("error in getting appId path param, GetDefaultDeploymentTemplate", "err", err)
990-
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
990+
common.HandleParameterError(w, r, "appId", vars["appId"])
991991
return
992992
}
993993
chartRefId, err := strconv.Atoi(vars["chartRefId"])
994994
if err != nil {
995995
handler.Logger.Error("error in getting chartRefId path param, GetDefaultDeploymentTemplate", "err", err)
996-
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
996+
common.HandleParameterError(w, r, "chartRefId", vars["chartRefId"])
997997
return
998998
}
999999
token := r.Header.Get("token")

api/restHandler/common/EnhancedErrorResponse.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,12 @@ func validationMessage(fe validator.FieldError) string {
253253
"%s must start and end with a lowercase letter or digit; may only contain lowercase letters, digits, '_' or '-' (no spaces or commas)",
254254
fe.Field(),
255255
)
256-
256+
// validation tag for sso config name
257+
case "validate-sso-config-name":
258+
return fmt.Sprintf(
259+
"%s must be one of [google, github, gitlab, microsoft, ldap, oidc, openshift]",
260+
fe.Field(),
261+
)
257262
// if a certain validator tag is not included in switch case then,
258263
// we will parse the error as generic validator error,
259264
// and further divide them on basis of parametric and non-parametric validation tags

internal/util/ValidateUtil.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,13 @@ func IntValidator() (*validator.Validate, error) {
108108
return v, err
109109
}
110110
err = v.RegisterValidation("validate-api-token-name", validateApiTokenName)
111+
if err != nil {
112+
return v, err
113+
}
114+
err = v.RegisterValidation("validate-sso-config-name", validateSSOConfigName)
115+
if err != nil {
116+
return v, err
117+
}
111118
return v, err
112119
}
113120

@@ -147,3 +154,23 @@ func validateApiTokenName(fl validator.FieldLevel) bool {
147154
hostnameRegexRFC952 := regexp.MustCompile(hostnameRegexString)
148155
return hostnameRegexRFC952.MatchString(fl.Field().String())
149156
}
157+
158+
func validateSSOConfigName(fl validator.FieldLevel) bool {
159+
allowedSSOConfigNames := []string{
160+
"google",
161+
"github",
162+
"gitlab",
163+
"microsoft",
164+
"ldap",
165+
"oidc",
166+
"openshift",
167+
}
168+
value := fl.Field().String()
169+
for _, v := range allowedSSOConfigNames {
170+
if value == v {
171+
return true
172+
}
173+
}
174+
return false
175+
}
176+

pkg/auth/user/bean/UserRequest.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ type RoleData struct {
112112

113113
type SSOLoginDto struct {
114114
Id int32 `json:"id"`
115-
Name string `json:"name,omitempty"`
115+
Name string `json:"name,omitempty," validate:"validate-sso-config-name"`
116116
Label string `json:"label,omitempty"`
117117
Url string `json:"url,omitempty"`
118118
Config json.RawMessage `json:"config,omitempty"`

0 commit comments

Comments
 (0)