Skip to content

Commit

Permalink
Add validation of app and job name
Browse files Browse the repository at this point in the history
  • Loading branch information
wpjunior committed Aug 16, 2023
1 parent 9fee015 commit 1ca1170
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
15 changes: 15 additions & 0 deletions api/types/rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"fmt"
"net"
"reflect"
"regexp"
"sort"
"strings"
"time"
Expand All @@ -17,6 +18,8 @@ import (
"k8s.io/apimachinery/pkg/util/validation"
)

var tsuruNameRegexp = regexp.MustCompile(`^[a-z][a-z0-9-]{0,39}$`)

type Rule struct {
RuleID string
RuleName string
Expand Down Expand Up @@ -73,13 +76,21 @@ func (r *RuleType) Validate() error {
if r.TsuruApp.AppName != "" && r.TsuruApp.PoolName != "" {
return errors.New("cannot set both app name and pool name")
}

if r.TsuruApp.AppName != "" && !validateTsuruName(r.TsuruApp.AppName) {
return errors.New("invalid app name")
}
countSet++
}

if r.TsuruJob != nil {
if r.TsuruJob.JobName == "" {
return errors.New("cannot have empty tsuru job name")
}

if !validateTsuruName(r.TsuruJob.JobName) {
return errors.New("invalid job name")
}
countSet++
}

Expand Down Expand Up @@ -227,6 +238,10 @@ func validatePorts(ports []ProtoPort) error {
return nil
}

func validateTsuruName(name string) bool {
return tsuruNameRegexp.MatchString(name)
}

type ProtoPorts []ProtoPort

type ProtoPort struct {
Expand Down
25 changes: 25 additions & 0 deletions api/types/rule_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,31 @@ func TestValidateRuleType(t *testing.T) {
},
expected: `Invalid rpaas instance name`,
},
{
rt: RuleType{
TsuruApp: &TsuruAppRule{
AppName: "blaah-blah",
PoolName: "pool-name",
},
},
expected: `cannot set both app name and pool name`,
},
{
rt: RuleType{
TsuruApp: &TsuruAppRule{
AppName: "blaah-blah.cluster",
},
},
expected: `invalid app name`,
},
{
rt: RuleType{
TsuruJob: &TsuruJobRule{
JobName: "blaah-blah.cluster",
},
},
expected: `invalid job name`,
},
}

for _, tt := range tests {
Expand Down

0 comments on commit 1ca1170

Please sign in to comment.