@@ -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"
@@ -48,6 +49,12 @@ import (
4849
4950const ENV_DELETE_SUCCESS_RESP = "Environment deleted successfully."
5051
52+ var (
53+ // Regex patterns for environment name validation
54+ envNameAlphanumericRegex = regexp .MustCompile (`^[a-z0-9-]+$` )
55+ envNameLengthRegex = regexp .MustCompile (`^.{1,16}$` )
56+ )
57+
5158type EnvironmentRestHandler interface {
5259 Create (w http.ResponseWriter , r * http.Request )
5360 Get (w http.ResponseWriter , r * http.Request )
@@ -106,6 +113,27 @@ func NewEnvironmentRestHandlerImpl(svc request.EnvironmentService, environmentRe
106113 }
107114}
108115
116+ // validateEnvironmentName validates the environment name against multiple regex patterns
117+ // Note: Required validation is already handled by struct validation tag
118+ func (impl EnvironmentRestHandlerImpl ) validateEnvironmentName (envName string ) error {
119+ // Validation 1: Use only lowercase alphanumeric characters or '-'
120+ if ! envNameAlphanumericRegex .MatchString (envName ) {
121+ return errors .New ("Use only lowercase alphanumeric characters or '-'" )
122+ }
123+
124+ // Validation 2: Cannot start/end with '-'
125+ if strings .HasPrefix (envName , "-" ) || strings .HasSuffix (envName , "-" ) {
126+ return errors .New ("Cannot start/end with '-'" )
127+ }
128+
129+ // Validation 3: Minimum 1 and Maximum 16 characters required
130+ if ! envNameLengthRegex .MatchString (envName ) {
131+ return errors .New ("Minimum 1 and Maximum 16 characters required" )
132+ }
133+
134+ return nil
135+ }
136+
109137func (impl EnvironmentRestHandlerImpl ) Create (w http.ResponseWriter , r * http.Request ) {
110138 decoder := json .NewDecoder (r .Body )
111139 userId , err := impl .userService .GetLoggedInUser (r )
@@ -128,6 +156,13 @@ func (impl EnvironmentRestHandlerImpl) Create(w http.ResponseWriter, r *http.Req
128156 common .WriteJsonResp (w , err , nil , http .StatusBadRequest )
129157 return
130158 }
159+ // Validate environment name
160+ err = impl .validateEnvironmentName (bean .Environment )
161+ if err != nil {
162+ impl .logger .Errorw ("environment name validation err, Create" , "err" , err , "envName" , bean .Environment )
163+ common .WriteJsonResp (w , err , nil , http .StatusBadRequest )
164+ return
165+ }
131166
132167 // RBAC enforcer applying
133168 token := r .Header .Get ("token" )
0 commit comments