Skip to content

Commit 48624c9

Browse files
added validation
1 parent 2347e92 commit 48624c9

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

api/cluster/EnvironmentRestHandler.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import (
2525
"github.com/devtron-labs/devtron/pkg/cluster/environment/read"
2626
"github.com/devtron-labs/devtron/util/commonEnforcementFunctionsUtil"
2727
"net/http"
28+
"regexp"
2829
"strconv"
2930
"strings"
3031
"sync"
@@ -106,6 +107,34 @@ func NewEnvironmentRestHandlerImpl(svc request.EnvironmentService, environmentRe
106107
}
107108
}
108109

110+
var (
111+
// Regex patterns for environment name validation
112+
envNameAlphanumericRegex = regexp.MustCompile(`^[a-z0-9-]+$`)
113+
envNameNoStartEndHyphen = regexp.MustCompile(`^(?![-]).*[^-]$`)
114+
envNameLengthRegex = regexp.MustCompile(`^.{1,16}$`)
115+
)
116+
117+
// validateEnvironmentName validates the environment name against multiple regex patterns
118+
// Note: Required validation is already handled by struct validation tag
119+
func (impl EnvironmentRestHandlerImpl) validateEnvironmentName(envName string) error {
120+
// Validation 1: Use only lowercase alphanumeric characters or '-'
121+
if !envNameAlphanumericRegex.MatchString(envName) {
122+
return errors.New("Use only lowercase alphanumeric characters or '-'")
123+
}
124+
125+
// Validation 2: Cannot start/end with '-'
126+
if !envNameNoStartEndHyphen.MatchString(envName) {
127+
return errors.New("Cannot start/end with '-'")
128+
}
129+
130+
// Validation 3: Minimum 1 and Maximum 16 characters required
131+
if !envNameLengthRegex.MatchString(envName) {
132+
return errors.New("Minimum 1 and Maximum 16 characters required")
133+
}
134+
135+
return nil
136+
}
137+
109138
func (impl EnvironmentRestHandlerImpl) Create(w http.ResponseWriter, r *http.Request) {
110139
decoder := json.NewDecoder(r.Body)
111140
userId, err := impl.userService.GetLoggedInUser(r)
@@ -128,6 +157,13 @@ func (impl EnvironmentRestHandlerImpl) Create(w http.ResponseWriter, r *http.Req
128157
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
129158
return
130159
}
160+
// Validate environment name
161+
err = impl.validateEnvironmentName(bean.Environment)
162+
if err != nil {
163+
impl.logger.Errorw("environment name validation err, Create", "err", err, "envName", bean.Environment)
164+
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
165+
return
166+
}
131167

132168
// RBAC enforcer applying
133169
token := r.Header.Get("token")

0 commit comments

Comments
 (0)